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

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

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);
}
});

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

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?

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

Sending targeted push notification to Android app, which is based on Azure

I have Android app, which is working with Azure IoT hub.
There are several tables on Azure, one of which stores credentials of registered users of my app. This table has one column called "userId" and records are unique here.
I also have node.js script which will be processing data in one of the tables and sending push notifications based on that data via GCM.
function sendPush(userId, pushText)
{
var payload = pushText;
push.gcm.send(null, payload, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse, payload);
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
}
});
}
I know that to make targeted push notification with Google Cloud Messaging, you have to get token with InstanceID class.
But can I somehow use "userId" column record to become that token to make my push notification targeted?
Generally speaking, you can leverage Tags param as tag identifier to push notifications to specified device. Refer to Sending push notifications with Azure Notification Hubs and Node.js for more.
And you can register with tags from your backend application, if your requirements are in the proper scenarios listed at https://msdn.microsoft.com/en-us/library/azure/dn743807.aspx
In backend nodejs application, you can try to use following code to register with tags:
var notificationHubService = azure.createNotificationHubService('<nb-name>', '<nb-keys>');
notificationHubService.createRegistrationId(function(err,registerId){
notificationHubService.gcm.createNativeRegistration(registerId,"identifier-tags",function(err,response){
console.log(response)
})
})
Then you can try to use the tags in send function.
Any further concern, please feel free to let me know.

Categories

Resources