I have written a firebase cloud function to send notifications on IOS and Android devices. I want collapsible notification messages. This is what is written in documentation:
Collapsible : When there is a newer message that renders an older, related message irrelevant to the client app, FCM replaces the older message. For example: messages used to initiate a data sync from the server, or outdated notification messages.
Set the appropriate parameter in your message request:
collapseKey on Android
apns-collapse-id on iOS
so I have the following lines of code in my function:
const payload = {
notification: {
title: `Hey`,
body: 'Your turn',
sound: 'default',
}
};
const options = {
collapseKey: 'myturnkey',
apns-collapse-id: 'myturnkey',
};
But I get the following message when I try to deploy the rule in terminal:
SyntaxError: Unexpected token -
I also tried with apns-collapse-id and I get a slightly different message for the same line of code:
Invalid or unexpected token
Do you see what is wrong ?
EDIT
with:
const options = {
'apns-collapse-id': 'myturnkey',
};
I can deploy the rule but the notifications do not collapse
And with:
const payload = {
notification: {
title: `hey`,
body: 'your turn',
sound: 'default',
}
};
const patchedPayload = Object.assign({}, payload, {
apns: {
headers: {
'apns-collapse-id': 'myturnkey',
}
}
});
I get the following error message in my firebase cloud functions logs when the function is called:
Error: Messaging payload contains an invalid "apns" property. Valid
properties are "data" and "notification".
Related
I have an Ionic 5 app with Capacitor 3 and I'm trying to receive notifications using Firebase Cloud messaging, on an Android device. I followed the configurations,(I downloaded the google JSON file and put my app id name correctly ) and I'm getting correctly the device token. Once my app is open I get the token successfully without any error and then I send a notification sharing my token to the Firebase test message, the notification never arrived, and also I never get an error of push notification in my logger. This is the code that I use for push notification.
export class PushNotificationsService {
constructor(private readonly http: HttpClient, private notificationState: NotificationsStore) { }
public initPush() {
if (Capacitor.getPlatform() !== 'web') {
this.registerPush();
}
}
private registerPush() {
PushNotifications.requestPermissions().then(async result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
console.log('granted');
await PushNotifications.register();
} else {
// Show some error
console.log('errorr');
}
});
// On success, we should be able to receive notifications
PushNotifications.addListener('registration',
(token: Token) => { (I get through this step and access the token successfully)
console.log('Push registration success, token: ' + token.value);
this.notification state.setToken(token.value);
}
);
// I never get this step error
PushNotifications.addListener('registrationError',
(error: any) => {
console.log('Error on registration: ' + JSON.stringify(error));
}
);
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotificationSchema) => {
console.log('Push received: ' + JSON.stringify(notification));
}
);
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: ActionPerformed) => {
console.log('Push action performed: ' + JSON.stringify(notification));
}
);
}
I also have capacitor.config.json like this:
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
Also, I checked that my device and app have permission for notifications and are enabled both. I tried and test this issue with my app open and closed and open only in the background and the notification never arrives. What it could be? Any clue? Thank you
Android Phone Please Create the channel Like this, Test or Add screenshot for console Error
if (Capacitor.getPlatform() === 'android') {
PushNotifications.createChannel({
id: 'fcm_default_channel',
name: 'app name',
description: 'Show the notification if the app is open on your device',
importance: 5,
visibility: 1,
lights: true,
vibration: true,
});
}
Here is the situation: I have a firebase cloud function that is running on every write to a certain database collection (called "jamrooms"). The NodeJS script is as follows:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.newJamroom = functions.database.ref('/jamrooms/{jamroomId}').onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
var jamroomId = event.params.jamroomId;
var topic = "new-jamroom";
var payload = {
data: {
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
On the client side (Android), I've subscribed to the topic "new-jamroom":
FirebaseMessaging.getInstance().subscribeToTopic("new-jamroom");
The script is successfully executed each time a new key-value pair is added to the collection:
but the client never receives the notification, either in background or in foreground.
I don't know where to look at to understand what's not going right.
Update
Even sending notifications from the console (using topic "new-jamroom", that exists in the console) doesn't send it to the client (Firebase records 0 sent).
Because your payload contains the data key, you are sending a data-only message, not a notification:
var payload = {
data: {
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
Data messages and notification messages are handled differently by the receiver. Data-only messages cause onMessageReceived() to be invoked in the receiver. To generate a notification, build your payload with the notification key:
var payload = {
notification: { // <= CHANGED
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
i am coding an Api Rest in rails 5, using gem 'fcm' to send notifications. I have already configure firebase in my android app and I can send notifications successfully from the Firebase console, but from my rails api i cannot receive the notificacion in my device, this is my code:
this is my rails controller:
class AccionesController < ApplicationController
def enviar
require 'fcm'
fcm = FCM.new("AAAAlBfTsV4:AheregoesmySERVEKEYsXXm-vQGfMjVuo8TpYrApHsnGU4ZasdfajsdfñalUtf26LeND4U4lXFZZplpzJjTWoiisWP-Esl5afCSTmiDI9y5gP6OObqY76NVcOn9ceaIUGMZ")
# fcm = FCM.new("my_server_key", timeout: 3)
registration_ids= [params[:devicetoken]] # an array of one or more client registration tokens
options = {data: {score: "mynewscore"},
notification: {
title: "Message Title",
body: "Hi, Worked perfectly",
icon: "myicon"}
,collapse_key: "testeando desde rails", priority: "high"}
response = fcm.send(registration_ids, options)
render json: response
end
def noti_params
params.permit(:devicetoken)
end
end
I execute from Postman this is the route that execute the controller:
http://localhost:3000/acciones/enviar?here goes the device token as parameter
And, here is the response:
{"body":"{\"multicast_id\":5276983113254623155,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1502991819420287%2293308c2293308c\"}]}","headers":{"content-type":["application/json;
charset=UTF-8"],"date":["Thu, 17 Aug 2017 17:43:39
GMT"],"expires":["Thu, 17 Aug 2017 17:43:39
GMT"],"cache-control":["private,
max-age=0"],"x-content-type-options":["nosniff"],"x-frame-options":["SAMEORIGIN"],"x-xss-protection":["1;
mode=block"],"server":["GSE"],"alt-svc":["quic=\":443\"; ma=2592000;
v=\"39,38,37,35\""],"accept-ranges":["none"],"vary":["Accept-Encoding"],"connection":["close"]},"status_code":200,"response":"success","canonical_ids":[],"not_registered_ids":[]}
the response shows success: 1 and status code: 200 but the notification never reaches the device,and the firebase console does not show the message.
Am I missing something?
please help?
or is there another way or ruby gem to send notification with a clear example?
any suggestions are welcome... thanks in advance
Instead of using fcm gem, you can also use RestClient gem. The usage for fcm notifications is as follow.One thing to note is if the payload is passing using ".to_json", the header content type also must be specified as json. Hope this help.
def self.send_noti(device_token)
options = data().merge ({"to": "#{device_token}"})
RestClient.post("https://fcm.googleapis.com/fcm/send", options.to_json, headers={'Content-Type' => 'application/json','Authorization' => "key=#{ENV['fcm_token']}"})
end
def self.data()
options = {
"notification": {
"body": "Your noti body",
"title": "Your noti title"
},
"data": {
"d1": "Your data" #can be any, d1, status or whatever
}
}
end
rest-client gem
fcm_client = FCM.new(your_firebase_key)
registration_ids= [user_device_token]
options = {
priority: 'high',
data: {
message: "Hai",
location: location
},
notification: {
body: "Hai",
location: "location",
sound: 'default'
}
}
fcm_client.send(registration_ids, options)
end
end
try this message options because the error should be your notification syntax.
options = {
priority: 'high',
data: {
message: "Hai",
location: location
},
notification: {
body: "Hai",
location: "location",
sound: 'default'
}
}
I have an android Client Application and and Admin Application using Firebase. Whenever a user registers in Client Application, I need to send a push notification to Admin app. I am trying to use Cloud Functions for Firebase. I have exported the function, and i can see that on firebase console as well.
This is my index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendMessageToAdmin = functions.database.ref('/tokens/users/{userId}/{regToken}').onWrite(event => {
if (event.data.previous.exists()) {
return;
}
const userId = event.params.userId;
const regToken = event.params.regToken;
// Notification details.
const payload = {
notification: {
title: 'You have a new User.',
body: `${userId} is the id.`,
}
};
return admin.messaging().sendToDevice(regToken, payload);
});
Here is my database structure at firebase :
If i use any online portal to send push or even FCM to send push to admin app for testing purpose, i am receiving the push. But this Cloud Function is not sending the push. Can someone guide me whats wrong i am doing.
EDIT
If i change the function to the following , then it works. But i am still wondering why the above function didn't work.
exports.sendMessageToAdmin = functions.database.ref('/tokens/users/{userId}').onWrite(event => {
if (event.data.previous.exists()) {
return;
}
const userId = event.params.userId;
var eventSnapshot = event.data;
const regToken = eventSnapshot.child("regToken").val();
Notification details.
const payload = {
notification: {
title: 'You have a new User.',
body: `${userId} is the id.`,
}
};
return admin.messaging().sendToDevice(regToken, payload);
});
In your original code, you have:
const regToken = event.params.regToken;
event.params.regToken does not return the value of regToken it returns the value of the wildcard path segment in your reference.
I have setup a Mobile Service in Azure and connected it to my Android app. Through this app I am calling the Azure API to insert an object into a database table linked to the mobile service.
I have written the script that is executed before it gets inserted. That script is intended to send a push notification to another device.
Now the case is, the object gets inserted into table but no push notification is received. What could be wrong? How can i debug?
Here's my insert script:
function insert(item, user, request) {
var devices = tables.getTable('Devices');
var receiverHandle;
devices.where({userId: item.receiver}).read({
success: populateHandle
});
request.execute({
success: function() {
// Write to the response and then send the notification in the background
request.respond();
console.log(item);
push.gcm.send(item.handle, item, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
});
function populateHandle(results){
receiverHandle = results[0].handle;
}
}
Although logs state successful delivery of push notification. I am not receiving it on my device.
Here is one of the logs:
Push notification sent: { isSuccessful: true, statusCode: 201, body: '', headers: { 'transfer-encoding': 'chunked', 'content-type': 'application/xml; charset=utf-8', server: 'Microsoft-HTTPAPI/2.0', date: 'Sun, 10 Aug 2014 15:01:52 GMT' }, md5: undefined }
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
}
});