Is it possible to send push notification with REST API on Firebase? I can send notifications with Firebase console but i need to send notifications with REST API.
Just for helping,
If anyone wants to use REST POST API, here it is, use the Postman with below configuration
URL:
https://fcm.googleapis.com/fcm/send
Header:
"Content-Type": "application/json",
"Authorization": "key=<Server_key>"
BODY:
{
"to": "<Device FCM token>",
"notification": {
"title": "Check this Mobile (title)",
"body": "Rich Notification testing (body)",
"mutable_content": true,
"sound": "Tri-tone"
},
"data": {
"url": "<url of media image>",
"dl": "<deeplink action on tap of notification>"
}
}
That's it. Thanks!!!
If you want to get more details about Rich Notification with FCM, you can check my article on Medium Rich Push Notification with Firebase Cloud Messaging (FCM) and Pusher on iOS platform
I used the below rest API to send notification.
curl -X POST \
https://fcm.googleapis.com/fcm/send \
-H 'Authorization: key=AAAAG-oB4hk:APA91bFUilE6XqGzlqtr-M-LRl1JisWgEaSDfMZfHuJq3fs7IuvwhjoGM50i0YgU_qayJA8FKk15Uvkuo7SQtQlVt4qdcrrhvnfZyk_8zRGAskzalFUjr2nA2P_2QYNTfK6X8GbY0rni' \
-H 'Content-Type: application/json' \
-H 'Postman-Token: c8af5355-dbf2-4762-9b37-a6b89484cf07' \
-H 'cache-control: no-cache' \
-d '{
"to": "ey_Bl_xs-8o:APA91bERoA5mXVfkzvV6I1I8r1rDXzPjq610twte8SUpsKyCuiz3itcIBgJ7MyGRkjmymhfsceYDV9Ck-__ObFbf0Guy-P_Pa5110vS0Z6cXBH2ThnnPVCg-img4lAEDfRE5I9gd849d",
"data":{
"body":"Test Notification !!!",
"title":"Test Title !!!"
}
}'
Authorization : key=AAAAG-oB4hk:APA91bFUilE6XqGzlqtr-M-LRl1JisWgEaSDfMZfHuJq3fs7IuvwhjoGM50i0YgU_qayJA8FKk15Uvkuo7SQtQlVt4qdcrrhvnfZyk_8zRGAskzalFUjr2nA2P_2QYNTfK6X8GbY0rni
where key is web_server_key from the console and you need to specify the unique registration key which you will get from the app.
"to": "ey_Bl_xs-8o:APA91bERoA5mXVfkzvV6I1I8r1rDXzPjq610twte8SUpsKyCuiz3itcIBgJ7MyGRkjmymhfsceYDV9Ck-__ObFbf0Guy-P_Pa5110vS0Z6cXBH2ThnnPVCg-img4lAEDfRE5I9gd849d" is the FCM registration token from device. Please refer to the below link.
https://firebase.google.com/docs/cloud-messaging/android/client?authuser=0
this may help - https://firebase.google.com/docs/cloud-messaging/http-server-ref
where sample message you can find here - https://firebase.google.com/docs/cloud-messaging/downstream
from Firebase console you can get Server Key as an authorization you put in the http header, in the tab Cloud messaging.
Using ARC For Sending Request to Firebase Console To Send Notification
You can use ARC OR Postman or your own server to send notification.
You need to collect your web_server_key from the console and you need to specify the unique registration key which you will get from the app when calling the onRefreshToken() method.
You need to send the request to https://fcm.googleapis.com/fcm/send with Content-Type : json and Authorization: web_server_key. On To value user your app_registration_token .
Try this,
URL - https://fcm.googleapis.com/fcm/send
Method - Post
Headers
Authorization -> key= Server Key which you can get it from console
Content-Type -> application/json
Body
{
"to" : "FCM Token goes here",
"notification" : {
"body" : "New Lesson Added 1",
"title": "Lokesh"
}
}
We used the following documentation to send notifications from a web client.
There is an easy way to send a notification via Chrome App or Extension.
function sendMessage() {
var message = {
messageId: getMessageId(),
destinationId: senderId + "#gcm.googleapis.com",
timeToLive: 86400, // 1 day
data: {
"key1": "value1",
"key2": "value2"
}
};
chrome.gcm.send(message, function(messageId) {
if (chrome.runtime.lastError) {
// Some error occurred. Fail gracefully or try to send
// again.
return;
}
The new version of API (called v1) creates more challenges to send a message via ARC. You need a special token, which will expire. You have to create firebase admin sdk key(service account key) in firebase console:
Firebase-admin sdk
They key is stored in json format something like this:
{
"type": "service_account",
"project_id": "<your project ID>",
"private_key_id": "8b..............................37",
"private_key": "-----BEGIN PRIVATE KEY-----
MIIE.....
....
-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-6fzie#<yourprojectID>.iam.gserviceaccount.com",
"client_id": "1...................4",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":
"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-
6fzie%40<yourprojectID>.iam.gserviceaccount.com"
}
The key is used to identify you while obtaining token for http communication. You need a kind of server access to firebase. I have used python in WSL with this piece of code:
import requests
import google.auth.transport.requests
from google.oauth2 import service_account
SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
credentials = service_account.Credentials.from_service_account_file('service-account.json', scopes=SCOPES)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
print(credentials.token)
Where service-account.json is your private key in file on your filesystem where python is running. You will get the token and it could be used inside ARC:
ya29.c.b0Aa9VdylWfrAFWysdUeh3m7cGF-Cow1OAyyE4bEqFL....................48Ye7w
ARC config is similar like in legacy API, but there are some changes. The URL has changed and it contains your project ID:
https://fcm.googleapis.com/v1/projects/<your project ID>/messages:send
We still use POST method and headers have only one line Content-Type application/json. The authentication has a separated tab and we are supposed to use Bearer + token from python:
Firebase authentication
It is important to select Bearer and enable it, because it is disabled by default.
The changes are in the body as well. This is an example of the message to individual application based on application token:
{
"message" : {
"token" : "e6e....FurF",
"notification" : {
"body" : "Great deal!",
"title" : " Buy everything"
}
}
}
where keyword "to" has changed to "token". That's all and we can send the message to the app. I wanted to have it here to be able to migrate to API v1 as Goggle requires these days. The last piece of code is for curl:-)
curl " https://fcm.googleapis.com/v1/projects/<your project id>/messages:send" \
-X POST \
-d "{\r\n \"message\" : {\r\n \"token\" : \"e6e....FurF\",\r\n \"notification\" : {\r\n \"body\" : \"Great deal!\",\r\n \"title\" : \" Buy everything\"\r\n }\r\n }\r\n}" \
-H "Content-Type: application/json" \
-H "authorization: Bearer ya29.c.b...."
Here is source I have used:
Firebase cloud messaging doc
GIT HUB code for messaging
For c# application (Xamarin.Forms etc.) you can just copy this code:
public async static void SendPushToTokenID(string tokenID, string title, string body)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
var url = serverURL;
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + serverKey);
var notification = new
{
title = title,
body = body
};
var postModel = new
{
to = tokenID,
notification = notification
};
var response = await client.PostAsJsonAsync(url, postModel);
// format result json into object
string content = await response.Content.ReadAsStringAsync();
string xw = (response.Content.ReadAsStringAsync().Result);
}
for url use: https://fcm.googleapis.com/fcm/send
and for your server key use your firebase server key. thats literally all. just dont forget to store the device token ID on your server and then you can send messages all day for free to individual users. its dead simple.
Related
I have a problem, I am trying to send FCM notification by http. When I send below payload:
{
"notification" : {
"body" : "test Notification",
"title": "test Notification",
"image" : "https://www.fillmurray.com/640/360"
},
"to":"firebasetoken",
"priority":"high"
}
I get notification on my mobile devices but the notification contains only Title and Body. I tried changing image to imageurl but that also didn't work.
I want display my notification as below.
I will be grateful for help. I tried at the beginning of last year and this payload was good.
This is because you are using legacy HTTP API which doesn't support image payload. Try migrating to HTTP v1 API and you'll be able to send image payload. Follow these links.
Migration guide.
Send image in notification payload
When migrating to HTTP v1, you'll need oAuth token and in case you don't know how to generate it, I'll provide step by step guide here.
To create oAuth token, follow these steps.
Step 1. Get serviceaccount json file from firebase console.
Go to firebase console -> project setting -> service account tab and click generate new private key to download json file. The json file contains some credential information.
Step 2. Generate token
Generating token will require running some program code using node,python or java and here I'll be using node.
Create generatekey.js file with below code, and change path of json file inside code.
var {google} = require("googleapis");
// Load the service account key JSON file.
var serviceAccount =
require("path/to/downloaded.json"); //change path to your downloaded json file
// Define the required scopes.
var scopes = [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/firebase.messaging"
];
// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(serviceAccount.client_email,
null,serviceAccount.private_key,scopes);
// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
if (error) {
console.log("Error making request to generate access token:",
error);
} else if (tokens.access_token === null) {
console.log("Provided service account does not have permission to generate access tokens");
} else {
var accessToken = tokens.access_token;
console.log(accessToken);
// See the "Using the access token" section below for information
// on how to use the access token to send authenticated requests to
// the Realtime Database REST API.
}
});
Run generatekey.js file from terminal with command
node genereatekey.js and it will print OAuth2 token.
try
const message = {
"notification" : {
"body" : "test Notification",
"title": "test Notification",
"android": {
"notification": {
imageUrl: 'https://www.fillmurray.com/640/360'}
}
I try to implement push-notifications to my Ionic4-Capacitor-App.
In the app I have this code:
PushNotifications.register();
PushNotifications.createChannel({ id: '1', description: '2019', importance: 2, name: '2019'});
PushNotifications.addListener('pushNotificationReceived', (notification) => {
console.debug(JSON.stringify(notification));
});
With POSTMAN I try to send the following message:
{
"to": "<User-Token>",
"notification": {
"title": "Default Title",
"body": "Default Body"
},
"android": {
"notification": {
"title": "Android Title",
"body": "Android Title",
"channel_id": "1"
}
}
}
Here is the documentation I used.
The notification I recive has "Default Title" as a title and "Default Body" as a body.
I expected it to have "Android Title" and "Android Body". Additionally, the notification is not pushed to channel 1, but to Miscellaneous.
When I leave out the "root" notification part, no notification is displayed at all.
For everyone who faces the same problem:
Here are the configuration steps I made to send firebase cloud messages via Postman.
Google-Cloud Configuration:
Go To: https://console.cloud.google.com/apis/credentials/consent
Add getpostman.com to the authorized domains
Go To: https://console.cloud.google.com/apis/credentials
Add a new OAuth-Client-ID
Select Webapplication and give it a name.
Set authorized redirect-URL to https://www.getpostman.com/oauth2/callback and save.
Download Json for this account
POSTMAN Configuration:
Set Request-Type to POST
Enter the url: https://fcm.googleapis.com/v1/projects/{your-firebase-project-name}/messages:send
Go to Authorization, select type OAuth 2.0 and click "Get New Access Token"
Grant-Type Authorization Code
Callback URL: https://www.getpostman.com/oauth2/callback
Auth URL: [auth_uri from the json File]
Access Token URL: [token_uri from the json File]
Client ID: [client_id from the json File]
Client Secret: [client_secret from the json File]
Scope: https://www.googleapis.com/auth/firebase.messaging
State: [empty]
Client Authentication: Send as Basic Auth header
When you have done these steps, you should be able to Send messages as described in this documentation: https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send
I'm using react-native-firebase to manage notifications on React-native app.
I try to handle FCM message on the background when application is off without display the notification.
I’m using react-native-firebase to manage notifications on React-native app.
When my app is off, I try to catch FCM messages and wake up my app without displaying any notification, just as described here https://rnfirebase.io/docs/v4.2.x/messaging/introduction#Data-only-messages 1.
In React Native Firebase doc, they say :
You will need to specify the FCM message priority as high for this functionality to work. If this isn’t set, the app is not given permission to launch the background message handler.
Where I must specify this priority ? I don’t understand how this works.
Edit 1 : I tried to set priority : "high"on FCM message but it's still not working. I have the same problem related to this issue : https://github.com/invertase/react-native-firebase/issues/500
The priority is considered as a platform specific config. You can set different priorities for different platforms.
For instance look at the example below:
(Message priority in Fcm docs)
{
"message":{
"topic":"subscriber-updates",
"notification":{
"body" : "This week's edition is now available.",
"title" : "NewsMagazine.com",
},
"data" : {
"volume" : "3.21.15",
"contents" : "http://www.news-magazine.com/world-week/21659772"
},
"android":{
"priority":"normal"
},
"apns":{
"headers":{
"apns-priority":"5"
}
},
"webpush": {
"headers": {
"Urgency": "high"
}
}
}
}
Using "priority":10 did the trick for me.
curl -X POST --header "Authorization: key=<your_key>" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d {"data":{"body":"Test body from curl"},"registration_ids":["<reg_ids>"],"apns":{"headers":{"apns-priority":"10"}},"webpush":{"headers":{"Urgency": "high"}},"android":{"priority":"high"},"priority":10}
I am sending the following JSON through GCM (Google Cloud Messaging) but I have not been able to get the right response data through the Client. I get a push notification response, but the title is the App's name, and the texts reads: "message" so I can't display my notification properly.
Here is the JSON that I am trying to send:
{
"to": "somekey",
"notification": {
"body":"Test",
"title":"Test"
},
"data": null
}
I think that your problem is on the key-values of the payload of your message.
As you can see at GCM Server documentation, the payload can be set using two different keys:
data: This parameter specifies the key-value pairs of the message's payload.
notification: This parameter specifies the key-value pairs of the notification payload.
You should use the data key and set inside the payload of the notification. Once send, you can print the result of the notification received and see that there are the right payload inside the data key.
Your message should be like the following JSON data:
{
"registration_ids" => "some_target_device_id",
"data": {
"title": "My title",
"message": "This is the message!",
}
}
Authorization: key= AIz......#GCM project key
{ "data": {
"title": "Summer Offer.",
"message": "Click to visit the offer."
},
"to" : "Device Token"
}
Can I use POSTMAN client on Google Chrome to send payload message to GCM server for testing purpose.
Secondly if yes, what is the header and url parameter to be sent.
Yes, you can.
1. Send a notification with a JSON payload
URL: https://android.googleapis.com/gcm/send
Headers:
Authorization: key=<your-api-key>
Content-Type: application/json
Body (click on the 'raw' tab):
{
"collapse_key": "score_update",
"time_to_live": 108,
"delay_while_idle": true,
"data": {
"score": "4x8",
"time": "15:16.2342"
},
"registration_ids":["4", "8", "15", "16", "23", "42"]
}
Note: registration_ids is the only required field, all the others are optional.
2. Send a notification with a plain text payload
URL: https://android.googleapis.com/gcm/send
Headers:
Authorization: key=<your-api-key>
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Body (click on the 'x-www-form-urlencoded' tab):
collapse_key=score_update
time_to_live=108
delay_while_idle=1
data.score=4x8
data.time=15:16.2342
registration_id=42
Note: registration_id is the only required field, all the others are optional.
Source: https://developer.android.com/google/gcm/http.html
Just for the record and to complete the nice answer from #Alexandru Rosianu the GCM endpoint changed a while ago and it is suggested to use the new one. Here is an example taken from the official docs:
Authentication
To send a message, the application server issues a POST request. For example:
https://gcm-http.googleapis.com/gcm/send
A message request is made of 2 parts: HTTP header and HTTP body.
The HTTP header must contain the following headers:
Authorization: key=YOUR_API_KEY
Content-Type: application/json for JSON; application/x-www-form-urlencoded;charset=UTF-8 for plain text. If Content-Type is omitted, the format is assumed to be plain text.
For example:
Content-Type:application/json
Authorization:key=YOUR_API_KEY
{
"notification": {
"title": "Portugal vs. Denmark",
"text": "5 to 1"
},
"to" : "bk3RNwTe3H0:CI2k_H..."
}
The HTTP body content depends on whether you're using JSON or plain text. See the Server Reference for a list of all the parameters your JSON or plain text message can contain.
Example using Curl:
# curl --header "Authorization: key=YOUR_API_KEY" \
--header Content-Type:"application/json" \
https://gcm-http.googleapis.com/gcm/send \
-d "{\"notification\": { \"title\": \"Portugal vs. Denmark\"," \
"\"text\": \"5 to 1\" }, \"to\" : \"bk3RNwTe3H0:CI2k_H...\" }"
Yes, you can use POSTMAN.
This GCM Notification Test Tool simplifies the server side testing immensely by reducing the number of items you enter in POSTMAN everytime - http://techzog.com/development/gcm-notification-test-tool-android/