How to send push notification from Firebase using google apps script? - android

I want to write a little script that tells Firebase to push notification if a certain condition is met. How to send push notification from Firebase using google apps script?

I'd never tried this before, but it's actually remarkably simple.
There are two things you need to know for this:
How to send a HTTP request to Firebase Cloud Messaging to deliver a message
How to call an external HTTP API from with Apps Script
Once you have read those two pieces of documentation, the code is fairly straightforward:
function sendNotificationMessage() {
var response = UrlFetchApp.fetch('https://fcm.googleapis.com/fcm/send', {
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: 'key=AAAAIM...WBRT'
},
payload: JSON.stringify({
notification: {
title: 'Hello TSR!'
},
to: 'cVR0...KhOYB'
})
});
Logger.log(response);
}
In this case:
the script sends a notification message. This type of message:
shows up automatically in the system tray when the app is not active
is not displayed when the app is active
If you want full control over what the app does when the message reaches the device, send a data message
the script send the message to a specific device, identified by its device token in the to property. You could also send to a topic, such as /topics/user_TSR. For a broader example of this, see my blog post on Sending notifications between Android devices with Firebase Database and Cloud Messaging.
the key in the Authorization header will need to match the one for your Firebase project. See Firebase messaging, where to get Server Key?

Related

Device-Device communication in react native app based on firebase

I have just started learning react-native and thinking of integrating firebase to it. Now consider my question scenario:
There are two users A & Bwho have the react app running in their device( none of them are admin). Now I have studied that when we connect our react native app to firebase, every instance of the app running on a device gets a unique token and that token is stored in firebase itself.
Now suppose user A wants to send a " notification or message" to user B. Now see the below code I saw on firebase official website:
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
This method seems quite straightforward, but is there really any method using which user A can know the unique token of user B like this:
const token= firebase.getToken('B');
And then use this token in the above code to send notification to user B. Is it poosible to do it using firebase?
Thank You.
The code you found uses the Firebase Admin SDK to send messages. This SDK grants its users full administrative access to the Firebase project, so can only be used in trusted environments, such as your development machine, a server you control, or Cloud Functions. It cannot be used in the app you send to your users.
You will need a trusted environment to send the messages to the users. For more on this, see:
The Firebase documentation on FCM architecture, which has this handy diagram
How to send one to one message using Firebase Messaging
How to send Device to device notification by using FCM without using XMPP or any other script.?

Call Firebase Cloud Messaging from HTML page

I've created an Android app with Firebase messaging. Notifications are working fine from the Firebase console. I want to make it work when I click a button from HTML page. Is this possible?
To send a message to devices via the Firebase Cloud Messaging API, you need to pass in the so-called FCM Server Key.
As its name implies, this key should only be used in trusted environment, such as a server you control, your development machine, or Cloud Functions. The reason for that is that somebody who has the FCM Server Key can send any message they want to any of your users.
So if you embed this key in an untrusted environment (such as your web page), a malicious user can simply copy it, and send messages on your behalf. And your users will have no way to know what message came from you, and what messages came from the malicious users.
The typical solution is to implement the sending of messages in a trusted environment, such as in Cloud Functions. That way your (server-side) code can ensure that the sender is authorized to send messages.
For more on this, see:
Sending notifications between Android devices with Firebase Database and Cloud Messaging; while it's for Android, and uses Node.js, the flow described here is still relevant for all platforms.
is there anyway to send notification from one device to other device using FCM without Firebase Database?
How to send one to one message using Firebase Messaging
Finally it is working from the below coding
$.ajax({
type : 'POST',
url : "https://fcm.googleapis.com/fcm/send",
headers : {
Authorization : my_key
},
contentType : 'application/json',
dataType: 'json',
data: JSON.stringify({
"to": my_token,
"notification": {
"title":"Test",
"body":"Test"
}
}),
success : function(response) {
console.log(response);
},
error : function(xhr, status, error) {
console.log(xhr.error);
}
});

Firebase Cloud Messaging - Create topic message from client [duplicate]

I am thinking about keeping all registration ids(push token) in DB and sending notifications to user from iPhone. I tried something like this but did not get any notification.
func sendPNMessage() {
FIRMessaging.messaging().sendMessage(
["body": "hey"],
to: TOKEN_ID,
withMessageID: "1",
timeToLive: 108)
}
What I am doing wrong or maybe it is impossible at all?
Currently it's not possible to send messages from the application itself.
You can send messages from the Firebase Web Console, or from a custom server using the server-side APIs.
What you might want to do is to contact a server (like via http call) and that server will send the message to the user.
This way ensure that the API-KEY of the server is protected.
PS: the sendMessage(..) api is called upstream feature, and can be used to send messages from your app to your server, if you server has an XMPP connection with the FCM server.
Yes you can send push notification through Firebase.Please make sure do NOT include the server-key into your client. There are ways "for not so great people" to find it and do stuff... The Proper way to achieve that is for your client to instruct your app-server to send the notification.
You have to send a HTTP-Post to the Google-API-Endpoint.
You need the following headers:
Content-Type: application/json
Authorization: key={your_server_key}
You can obtain your server key within in the Firebase-Project.
HTTP-Post-Content: Sample
{
"notification": {
"title": "Notification Title",
"text": "The Text of the notification."
},
"project_id": "<your firebase-project-id",
"to":"the specific client-device-id"
}
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the Google Cloud Functions documentation:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
Diego's answer is very accurate but there's also cloud functions from firebase it's very convenient to send notifications in every change in the db. For example let's say you're building chat application and sending notification in every new follower change.
This function sample is very good example.
For more information about cloud functions you can check official docs.
I have an app that has a "send feedback to developer" section. I also have a User collection in my firestore database. When a user logs into the app, I have that Users data update their FCM token with the following code in my SceneDelegate.swift:
import Firebase
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil {
DispatchQueue.main.async {
let docRef = Firestore.firestore().collection("User").document((user?.email)!)
docRef.getDocument { (snapshot, error) in
guard let snapshot = snapshot else {return}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
docRef.updateData(["FCMtoken":token])
print("FCM registration token: \(token)")
}
}
}
}
}
})
guard let _ = (scene as? UIWindowScene) else { return }
}
then in my feedback view controller i have this code to send my specific device (but you can look up/fetch which specific device you want in your database where the FCMtoken is stored where i have INSERT-DEVICE-TOKEN-HERE). The url to send to is "https://fcm.googleapis.com/fcm/send" and you can find YOUR-APP-FCM-KEY by going to your project settings in firebase, going to cloud messaging tab and its the server key.
func sendMePushNotification() {
let token = "INSERT-DEVICE-TOKEN-HERE"
if let url = URL(string: "https://fcm.googleapis.com/fcm/send") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = ["Content-Type":"application/json", "Authorization":"key=YOUR-APP-FCM-KEY"]
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"title\":\"Feedback Sent!\",\"body\":\"\(self.feedbackBox.text!)\",\"sound\":\"default\",\"badge\":\"1\"},\"data\": {\"customDataKey\": \"customDataValue\"}}".data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, urlresponse, error) in
if error != nil {
print("error")
} else {
print("Successfully sent!.....")
}
}.resume()
}
}
Use onesignal,you can send device to notifications or device to segments ,it can work with firebase in this way
Use onesignal functions to create a specific id,save it in a firebase database ,then when the id can be put in another function that is used to send a notification
Notes: 1-i am using it in my apps with firebase works perfectly
2-i can submit that code,just someone comments so i can find this answer

Android Firebase messaging - notification from one user to another user [duplicate]

I am thinking about keeping all registration ids(push token) in DB and sending notifications to user from iPhone. I tried something like this but did not get any notification.
func sendPNMessage() {
FIRMessaging.messaging().sendMessage(
["body": "hey"],
to: TOKEN_ID,
withMessageID: "1",
timeToLive: 108)
}
What I am doing wrong or maybe it is impossible at all?
Currently it's not possible to send messages from the application itself.
You can send messages from the Firebase Web Console, or from a custom server using the server-side APIs.
What you might want to do is to contact a server (like via http call) and that server will send the message to the user.
This way ensure that the API-KEY of the server is protected.
PS: the sendMessage(..) api is called upstream feature, and can be used to send messages from your app to your server, if you server has an XMPP connection with the FCM server.
Yes you can send push notification through Firebase.Please make sure do NOT include the server-key into your client. There are ways "for not so great people" to find it and do stuff... The Proper way to achieve that is for your client to instruct your app-server to send the notification.
You have to send a HTTP-Post to the Google-API-Endpoint.
You need the following headers:
Content-Type: application/json
Authorization: key={your_server_key}
You can obtain your server key within in the Firebase-Project.
HTTP-Post-Content: Sample
{
"notification": {
"title": "Notification Title",
"text": "The Text of the notification."
},
"project_id": "<your firebase-project-id",
"to":"the specific client-device-id"
}
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the Google Cloud Functions documentation:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
Diego's answer is very accurate but there's also cloud functions from firebase it's very convenient to send notifications in every change in the db. For example let's say you're building chat application and sending notification in every new follower change.
This function sample is very good example.
For more information about cloud functions you can check official docs.
I have an app that has a "send feedback to developer" section. I also have a User collection in my firestore database. When a user logs into the app, I have that Users data update their FCM token with the following code in my SceneDelegate.swift:
import Firebase
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil {
DispatchQueue.main.async {
let docRef = Firestore.firestore().collection("User").document((user?.email)!)
docRef.getDocument { (snapshot, error) in
guard let snapshot = snapshot else {return}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
docRef.updateData(["FCMtoken":token])
print("FCM registration token: \(token)")
}
}
}
}
}
})
guard let _ = (scene as? UIWindowScene) else { return }
}
then in my feedback view controller i have this code to send my specific device (but you can look up/fetch which specific device you want in your database where the FCMtoken is stored where i have INSERT-DEVICE-TOKEN-HERE). The url to send to is "https://fcm.googleapis.com/fcm/send" and you can find YOUR-APP-FCM-KEY by going to your project settings in firebase, going to cloud messaging tab and its the server key.
func sendMePushNotification() {
let token = "INSERT-DEVICE-TOKEN-HERE"
if let url = URL(string: "https://fcm.googleapis.com/fcm/send") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = ["Content-Type":"application/json", "Authorization":"key=YOUR-APP-FCM-KEY"]
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"title\":\"Feedback Sent!\",\"body\":\"\(self.feedbackBox.text!)\",\"sound\":\"default\",\"badge\":\"1\"},\"data\": {\"customDataKey\": \"customDataValue\"}}".data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, urlresponse, error) in
if error != nil {
print("error")
} else {
print("Successfully sent!.....")
}
}.resume()
}
}
Use onesignal,you can send device to notifications or device to segments ,it can work with firebase in this way
Use onesignal functions to create a specific id,save it in a firebase database ,then when the id can be put in another function that is used to send a notification
Notes: 1-i am using it in my apps with firebase works perfectly
2-i can submit that code,just someone comments so i can find this answer

Parse push notifcations open source server

Parse is shutting down and they've made their server opensource. However they do not have the extended functionality with push notifications as what used to be the case with parse.com
Can anyone help me set up push notifications on the open source version of Parse on android?
I've been through their wiki and I'm a tad bit confused about it.
If I'm not wrong, should I just add the GCM credentials to where the Parse Server is being initialized and then deploy it manually (possibly to heroku) myself and then use cURL to send notifications as per the wiki?
Or did I misunderstand the whole process and need to do something else?
Thanks in advance!
You can host your own Parser Server in a self-hosting solution or use a Parse Hosting provider like https://www.back4app.com
See all options below:
https://github.com/ParsePlatform/parse-server#parse-server-sample-application
Then you can send the push notifications using dashboard console, API or cloud code. Note that push notifications cannot be sent anymore from client. Because of security issues, Parse Server has discontinued sending push notifications direct from client. The best practice now is to create a cloud function to send the push notifications and then call it from client code. See more details below:
https://github.com/ParsePlatform/parse-server/wiki/Push#4-send-push-notifications
And here there is an example of a cloud function that can be used to send push notifications:
Parse.Cloud.define('push', function (request, response) {
// THIS METHOD NO LONGER WORKS
// Parse.Cloud.useMasterKey();
Parse.Push.send({
channels: request.params.channels,
data: request.params.data
}, {
// ADD THE `useMasterKey` TO THE OPTIONS OBJECT
useMasterKey: true,
success: function () {
response.success('Success!');
},
error: function (error) {
response.error('Error! ' + error.message);
}
});
});
You can also send the push notification throw Parse Dashboard. Parse has just announced this feature is now available:
http://blog.parse.com/announcements/push-and-config-come-to-the-parse-dashboard/
just fill the GCM field and the second field when you initialize Parse server (in the index.js or the ecosystem.json)... this will allow the server to send the Push for Android, for sending push U can use cloud code, curl or whatever. You need to use MasterKey though

Categories

Resources