FCM push notification - image not push - android

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'}
}

Related

how to push notification to all users in flutter like

hello guys i want to send notification to all users in my firebase by API like this :
`var serverToken ="" ;
sendNotify(String title , String body , String id) async{
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers:<String,String>{'Content-Type':'application/json',
'Authorization':'key=$serverToken',},
body:jsonEncode(
<String,dynamic>{
'notification':<String,dynamic>{
'body':body.toString(),
'title':title.toString()
},
'priority':'high',
'data':<String,dynamic>{
'click_action':'FLUTTER_NOTIFICATION_CLICK',
'id':id.toString()},
//'to':'all', <<<<<<< here i want to send it to all users not by token }));`
For this you should use topics ,
You need to subscribe users to the all topic and no need for tokens when sending the notification
Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.
// subscribe to topic on each app start-up
await FirebaseMessaging.instance.subscribeToTopic('all');
and your data
jsonEncode({
'topic': "all",
'data': {
'via': 'FlutterFire Cloud Messaging!!!',
'count': _messageCount.toString(),
},
'notification': {
'title': 'Hello FlutterFire!',
'body': 'This notification (#$_messageCount) was created via FCM!',
},
});

Sending individual push notifications with FCM

I have a simple WebView application of a mobile responsive website with authentication feature(the authentication is not in the app itself but in the WebView -> it's using sessions and cookies for long-term login)
What I want to do is send push notifications individually for each user based on the data in the database of the website.
My problems are the following:
How do I make the 'connection' between the logged in user in the WebView and the app?(Perhaps extract the login cookie from the WebView?)
How do I use FCM specifically for individual users(the one's gathered and associated at question 1) and not general notifications. I've found some info on this that I'd have to create a 'topic' for each user which doesn't sound too reliable, is this how FCM is used for individual notifications?
The function looks like this(node.js):
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/user_'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
source: https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html
Aside from topic, notifications can also be sent using a device-specific Notification Token. These notification tokens are device-specific and to my knowledge, outside of the auth system. If I understand correctly, your app depends on the WebView for all purposes of the app.
What I would suggest is to follow the aforementioned link, and implement the token retrieval in your app, then pass it along as a URL parameter. Instead of topic, you can pass a list(or single) notification token(s) to target individual devices(not users).
I hope this helps!!

Capacitor doesn't recive android specific push-notifications

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

Firebase : Send notification with REST API

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.

Azure mobile service for Android Google Cloud message(GCM) never sents notification to device

xamarian Android project not always receives the push message triggered from push.gcm.send(). Broadcast receiver calls only onregister() first time, but not calls onmessage(). my php server script works well with https://android.googleapis.com, and it calls onmessage() of broadcast reciver. Also Native android project with azure mobile service use push sharp client behaves same, it doesn't call onmessage() when push.gcm.send() executed in azure server. let me know what iam doing wrong, i use the perfect Applicationkey,server key,project number,........Below is the log details.I am getting status code 201.
Log entry details:
INFORMATION
Test Push notification sent: APA91bELUme4gM35eHBH4dmxo7AVBkmVu6Gsown_8zrROb5SsKzHn7MgpypBirmmDDuyPlr8hRjBDRX2lBc_j9voAPYv2RotXiVTHMaXFRRADu0xNfrPk-g-bCkfsCO7Uv-OnPMW8bgmTHIX8u8exKpGxfSrFZvN8dEDAoC5iw { isSuccessful: true,
statusCode: 201,
body: '',
headers:
{ 'transfer-encoding': 'chunked',
'content-type': 'application/xml; charset=utf-8',
server: 'Microsoft-HTTPAPI/2.0',
date: 'Tue, 27 May 2014 19:40:00 GMT' },
md5: undefined }
Input Script:
function insert(item, user, request) {
request.execute({
success: function() {
// Write to the response and then send the notification in the background
request.respond();
push.gcm.send(item.channel, item.text, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
});
}
Please double-check your test is correct by ensuring your client code matches the completed example with appropriate fields replaced from here: http://go.microsoft.com/fwlink/p/?linkid=331303&clcid=0x409
The full instructions are found at: http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-mobile-services-android-get-started-push/
If you still encounter issues after double-checking these, send me email at toddreif#microsoft.com with your Mobile Service account name.
Refer to Migrate a Mobile Service to use Notification Hubs.
Microsoft had been upgraded the Mobile Service, to push notifications powered by Notification Hubs. You will not be affected if you created the mobile service before the upgrade.
Base on the response { isSuccessful: true, statusCode: 201, body ... }, it indicate that your Mobile Service is the new version.
If you prefer to send push without Notification Hubs, don't use push.gcm.send, use the following code snippet instead.
var legacyGcm = require('dpush');
legacyGcm.send(your_GCM_APIKEY, regId, item, function (error, response) {
if (!error) {
// success code
} else {
// error handling
}
});

Categories

Resources