Firebase messaging, message not recieved - firebase

My cloud function states it has sent a message successfully undefined messages were sent successfully but I don't receive it:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
var serviceAccount = require("./config.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pushmessage-bd1eb.firebaseio.com"
});
const messaging = admin.messaging();
const message = {
data: { title: "Testing", body: "Test" },
token:
"fm8hZocb9X0:APA91bGANY8U1k7iXSAofh8PEtyA3SfkAvyvicjHbSzDC7s1DwzhCxBBhj5oeAhiZpNLFC1wUHOPX_C0vlGtUMv882EXxBjsM4qeBpFndka8kzir9kgmJnuPTRImx2cxUT53oXzJuAzB"
};
messaging.send(message).then(response => {
console.log(
response.successCount + " messages were sent successfully"
);
});
If I use the same token in the firebase dashboard to send a message, the message sends successfully.
How can I get my cloud function to send a message?
config.json:
{
"type": "service_account",
"project_id": "pushmessage-bd1eb",
"private_key_id": "xxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nxxx-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-8dd2o#pushmessage-bd1eb.iam.gserviceaccount.com",
"client_id": "xxx",
"senderID": "388436954224",
"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-8dd2o%40pushmessage-bd1eb.iam.gserviceaccount.com"
}

Are you using admin.messaging().send()?
See:
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging#send
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Message
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Notification
Please try the following code.
Change data to notification.
And the admin.messaging().send() return string.
const message = {
notification: { title: "Testing", body: "Test" },
token:
"The registration token here"
};
admin.messaging().send(message).then(response => {
console.log(
response + " messages were sent successfully"
);
});
Or you can use admin.messaging().sendToDevice().
See:
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging#sendToDevice
https://firebase.google.com/docs/reference/admin/node/admin.messaging.MessagingPayload
https://firebase.google.com/docs/reference/admin/node/admin.messaging.MessagingDevicesResponse
Please try the following code.
const token= "The registration token here";
const payload = {
notification: { title: "Testing", body: "Test" }
};
admin.messaging().sendToDevice(token, payload).then(response => {
console.log(
response.successCount + " messages were sent successfully"
);
});

Related

Problem with sending Push-notification from Firebase to my WordPress-PWA

I want a scheduled task. This task gets Temperature Values from my Thinkspeakaccount. If the temperature is below 5 degrees the function sends a message to my WordPress PWA. The code doesn't work. I don't get the problem.
Does anyone now a good tutorial for this problem?
(In WP I use a Plugin which is connect to firebase)
admin.initializeApp({
credential: admin.credential.cert({
"type": "service_account",
"project_id": "XX",
"private_key_id": "XX",
"private_key": "XX",
"client_email": "XX",
"client_id": "XX",
"auth_uri": "XX",
"token_uri": "XX",
"auth_provider_x509_cert_url": "XXX",
"client_x509_cert_url": "hXX"
}),
databaseURL: "XX"
});
const functions = require('firebase-functions');
const axios = require('axios');
exports.checkTemperature = functions.pubsub.schedule('\*/2 \* \* \* \*').onRun(async () = \ > {
try {
const response = await axios.get('https://api.thingspeak.com/channels/XXX/feeds.json?api_key=XXX&results=1&timezone=Europe%2FBerlin');
const temperature = response.data.feeds\[0\].field1;
if (temperature\ < 8) {
const payload = {
notification: {
title: 'Temperature Alert',
body: `Temperature is below 5 degrees: ${temperature}`,
}
};
return admin.messaging().sendToTopic('\<topic_name\>', payload);
}
} catch (error) {
console.error(error);
}
});
When I want to upload the code to firebase I get in firebase a warning

FirebaseMessaging callback not triggered while sending notification from cloud functions

client side code
final FirebasebaseMessaging _firebaseMessaging = new FirebaseMessaging();
_firebaseMessaging.configure(onMessage: (Map<String,dynamic> notification){
print("onMessage : $notification");
}, onResume: (Map<String,dynamic> notification){{
print("onResume: $notification");
}}, onLaunch: (Map<String,dynamic> notification){
print("onLaunch: $notification");
});
_firebaseMessaging.getToken().then((String token){
print("token is : $token");
});
server side
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
const payload = {
"notification": {
"body": postingUserDocumentSnapshot.data()['username'] + " commented on your post",
"title": "You got a comment",
"sound": 'enabled',
},
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"senderId": postingUserDocumentSnapshot.data()['userId'],
"postID": context.params.postId,
"notificationType": "COMMENT",
},
};
admin.messaging().sendToDevice(receiverMessagingToken, payload);
I do receive notification in the system tray but the firebaseMessaging callbacks are not triggered. However if i send notification from google console those callbacks are triggered.
Can anyone explain me or suggest me on why those callbacks are not triggered while sending notification via admin.messaging().sendToDevice?

admin.messaging(...).send is not a function

I am using firebase-admin to send a push notification via Cloud Functions, but I keep getting this error:
TypeError: admin.messaging(...).send is not a function
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:43:27)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Any idea why it's not working? I am using firebase-admin version 5.9.1, so it is the latest version. It should include the .send function but it's still not working. I have uninstalled the plugin and re-installed it, but still, it did not work.
This is the code I am using:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.cert({
projectId: "xxx",
clientEmail: 'xxx#xxx.iam.gserviceaccount.com',
privateKey: '-----BEGIN PRIVATE KEY-----<KEY>-----END PRIVATE KEY-----\n'
}),
databaseURL: "https://xxx.firebaseio.com"
});
exports.sendNotification = functions.database.ref("xxx").onWrite((event) => {
console.log("notify");
const registrationToken = "xxx";
// See documentation on defining a message payload.
var message = {
notification: {
title: "You have a new service request",
body: "this is the main body"
},
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
return admin.messaging().send(message)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
What am I doing wrong?
It should be sendToDevice not send, maybe something like this :
var message = {
notification: {
title: "You have a new service request",
body: "this is the main body"
},
data: {
score: '850',
time: '2:45'
}
};
return admin.messaging().sendToDevice(registrationToken, message)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});

Why Does FireFox Trigger OnMessage() sometimes and does not trigger the other time, while using FCM

While Using FCM when a notification is send against token for firefox browser , the messaging.onMessage function gets called sometimes and not for the other times.
I really Can't Understand what is the issue
My JS Code is:-
var config = {
apiKey: "my api key",
authDomain: "my auth domain",
databaseURL: "my db url",
projectId: "my proj id",
storageBucket: "my stirage bucket url",
messagingSenderId: "my msging sender ID"
};
firebase.initializeApp(config);
var messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
console.log('Notification permission granted.');
messaging.getToken()
.then(function(token){
console.log(token)
})
.catch(function (error) {
console.log('Unable to generate Token')
})
})
.catch(function (err) {
console.log('Unable to get permission to notify.', err);
})
messaging.onMessage(function (payload) {
console.log(payload.notification.body);
})
my json for notification is:-
{
"notification": {
"title": "My Title",
"body": "My Message",
"icon": "",
"click_action": ""
},
"to": "token"
}

How do I set "collapse_key" in Firebase Admin.messaging() SDK?

admin.messaging().sendToDevice(tokens, payload)
Here's the payload:
const payload = {
collapse_key: "something",
notification: {
body: message.body || "[ Sent you a photo ]",
},
data:{
"thread_id": String(thread_id),
"message_id": String(message_id),
"user_id": String(message.user_id),
"created_at": String(message.created_at),
}
};
Error: Messaging payload contains an invalid "collapse_key" property. Valid properties are "data" and "notification".
Do I need to use REST API for this? If so, that's really bad, because I have to pay extra for outgoing requests...
collapseKey is a property of MessagingOptions .You pass the options as the third parameter of sendToDevice().
const options = {
priority: 'high',
collapseKey: 'myCollapseKey'
};
admin.messaging().sendToDevice(tokens, payload, options)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
A complete example is in the documentation.
For those looking for an updated solution using most recent firebase-admin SDK and the new send() method, here's how I built my notification:
{
"token": TARGET_DEVICE_FCM_TOKEN,
"notification": {
"title": "Notification title",
"body": "Optional body",
},
"android": {
"collapseKey": "YOUR_KEY",
}
...rest of payload
}
Source: Package types

Resources