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

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

Related

FCM Topic Data Only Messages not being received in IoS Physical Devices

I am trying to send an FCM topic message to my React Native mobile app, but they don't seem to be going through. I am using NodeJs as follows and logging the output to show that the message is getting sent successfully (no issues with android):
admin
.messaging()
.send({
data: {
title,
body,
lat: data.Location.Latitude.toString(),
lng: data.Location.Longitude.toString(),
},
android: {
priority: "high",
data: {
sound: "alert",
},
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
'apns-push-type': 'background',
'apns-priority': '5',
'apns-topic': 'com.xxxx',
},
},
topic: topic,
})
The react app is subscribed to the topic as follows:
useEffect(() => {
await requestUserPermissions();
messaging().subscribeToTopic(Config.INCIDENTS_TOPIC);
messaging().onMessage(sendMessage);
messaging().setBackgroundMessageHandler(sendMessage);
});
const sendMessage = (remoteMessage) => {
if (Platform.OS === 'ios') {
notificationRadiusCalculationService.sendMessage(remoteMessage);
}
};
I have set a breakpoint in the sendMessage and its never being hit.My APN was registered in firebase.

Fauna returning 'unauthorized' when using Auth0 as a third party access provider

I am trying to integrate Fauna and Auth0 into my Vue 3 app.
To achieve that I am following this Auth0 guide and this youtube video.
In short, I have configured Auth0 as a Provider inside Fauna. And I am sending the Auth0 generated JWT token as the Fauna secret. Fauna should then decode the JWT and give access to the call.
To test it out my code fetches some dummy "products" data from Fauna and prints it to the console.
But when I make the call it returns as unauthorized.
What am I doing wrong?
Here is the script inside my Vue component that is making the call:
import { defineComponent, inject } from "vue";
import { query as q, Client } from "faunadb";
export default defineComponent({
name: "Api",
setup() {
let apiMessage = null;
let executed = false;
const auth = inject("Auth");
const callApi = async () => {
const accessToken = await auth.getTokenSilently();
console.log(accessToken);
try {
const client = new Client({ secret: accessToken });
const { Paginate, Documents, Collection } = q;
const data = await client.query(
Paginate(Documents(Collection("products")))
);
console.log(data);
apiMessage = data;
executed = true;
} catch (e) {
console.log(e);
apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
}
};
return {
callApi,
};
},
});
Here is a copy of the unauthorized response object that is returned:
{
"name": "Unauthorized",
"message": "unauthorized",
"description": "Unauthorized",
"requestResult": {
"method": "POST",
"path": "",
"query": null,
"requestRaw": "{\"paginate\":{\"documents\":{\"collection\":\"products\"}}}",
"requestContent": {
"raw": {
"paginate": {
"raw": {
"documents": {
"raw": {
"collection": "products"
}
}
}
}
}
},
"responseRaw": "{\"errors\":[{\"code\":\"unauthorized\",\"description\":\"Unauthorized\"}]}",
"responseContent": {
"errors": [
{
"code": "unauthorized",
"description": "Unauthorized"
}
]
},
"statusCode": 401,
"responseHeaders": {
"content-length": "65",
"content-type": "application/json;charset=utf-8",
"x-txn-time": "1634006015704445"
},
"startTime": 1634006014934,
"endTime": 1634006015885
}
}
Figured it out.
The client has to be initiated with some other values, most importantly is the domain value.
var client = new faunadb.Client({
secret: 'YOUR_FAUNA_SECRET',
domain: 'db.fauna.com',
// NOTE: Use the correct domain for your database's Region Group.
port: 443,
scheme: 'https',
})

Firebase Cloud Messaging click_action not working

I am sending notification from Firebase console to web application (Firebase). When I am sending a POST request from POSTMAN, I am able to navigate to the URL when I click on the notification. But when I am sending it from Firebase console I am not able to open the URL. Also, I need to add my logo as my Icon to the notification.
POSTMAN
{
"notification": {
"title": "Push notification test",
"body": "It works! 🎉",
"icon": "https://soft-ing.info/img/firebase.png",
"click_action": "https://google.com"
},
"to": "dLXCbmVCh5Y:APA91bGmFN7BUsKqwWFokyoBsoph6k4EhBQEflwJLFrPaUzTceYhAPYfFf8LqTRBVJGCA0gWS_0k0DUCeJBa7jdopIyjFQNprtp3lkQgLmUNRUibLIIMxAuBZeXuHTqaU-BA4QwbekN6"
}
Service Worker File Code
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = payload.data.title;//'Background Message Title';
const notificationOptions = {
body: payload.data.body,//'Background Message body.',
icon: payload.data.icon,
image : payload.data.image,
data:{
time: new Date(Date.now()).toString(),
click_action : payload.data.click_action
}
};
return self.registration.showNotification(notificationTitle,notificationOptions);
});
self.addEventListener("notificationclick", (event) => {
event.waitUntil(async function () {
const allClients = await clients.matchAll({
includeUncontrolled: true
});
let chatClient;
let appUrl = 'https://www.google.com';
for (const client of allClients) {
//here appUrl is the application url, we are checking it application tab is open
if(client['url'].indexOf(appUrl) >= 0)
{
client.focus();
chatClient = client;
break;
}
}
if (!chatClient) {
chatClient = await clients.openWindow(appUrl);
}
}());
});
There's some discrepancy in the above two snippets you shared.
In your case body: payload.data.body should be body: payload.notification.body, you need to do similarly for other places in service worker since that's how you are sending the request.

Push notifications with firebase

I'm getting this error when i test with token which I got from firebase
Error -The request's Authentication (Server-) Key contained an invalid or malformed FCM-Token (a.k.a. IID-Token)
these are the codes that i used to get token from firebase.
async getToken() {
let fcmToken = await AsyncStorage.getItem('fcmToken');
console.log("before fcmToken: ", fcmToken);
if (!fcmToken) {
fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
console.log("after fcmToken: ", fcmToken);
await AsyncStorage.setItem('fcmToken', fcmToken);
}
}
}
async requestPermission() {
firebase.messaging().requestPermission()
.then(() => {
this.getToken();
})
.catch(error => {
console.log('permission rejected');
});
}
async checkPermission() {
firebase.messaging().hasPermission()
.then(enabled => {
if (enabled) {
console.log("Permission granted");
this.getToken();
} else {
console.log("Request Permission");
this.requestPermission();
}
});
}`
But I got this Error 401 when I test with APNS & GCM Tester Online
https://pushtry.com/
Please may I have any methods to get push notification for react native android application?
You can use postman. Make a post request to this url "https://fcm.googleapis.com/fcm/send".
you need to send an object like this:
{
"data":
{
"title": "your title",
"body": "your body"
},
"notification": {
"title": "your title",
"body": "your body"
},
"registration_ids" : ["czf_nv_t1JA:APA91bGOyY3lTSG9b7Nr71xVo_Xn5RrxOIOwVfnKDv2OBanQjx1eQQyqdM3PFOd1Pjapm_DWn1R327iDyEwEeXjflJ3DyaGFF4iXmqot-OsyDt-Iz99Lu3MZZTvOSFIPiYgiaGHP5ByO"]
}
and registration_ids is your token.Also you need to set a header for your request with key Authorization and it's value comes from firebase console.for finding that you can check this https://developer.clevertap.com/docs/find-your-fcm-sender-id-fcm-server-api-key
Make sure in Authorization value is as per your firebase cloud messaging server key.
Reference link:- https://www.djamware.com/post/5c6ccd1f80aca754f7a9d1ec/push-notification-using-ionic-4-and-firebase-cloud-messaging

Messaging payload contains an invalid "android" property. Valid properties are "data" and "notification"

I'm trying to send Push Notifications with Firebase Cloud Functions with platform specific configuration. I got following config from https://firebase.google.com/docs/cloud-messaging/send-message
var message = {
notification: {
title: '$GOOG up 1.43% on the day',
body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
},
data: {
channel_id: threadId,
},
android: {
ttl: 3600 * 1000,
notification: {
icon: 'stock_ticker_update',
color: '#f45342',
},
},
apns: {
payload: {
aps: {
badge: 42,
},
},
},
};
but got error for admin.messaging().sendToDevice(deviceToken, message)
Messaging payload contains an invalid "android" property. Valid properties are "data" and "notification"
Any idea what is wrong here? Or maybe some samples of proper configuration for iOS/Android platforms?
sendToDevice() is a function that uses the legacy FCM HTTP endpoint. The legacy endpoint doesn't offer platform-specific fields. In order to get that functionality, you can use the new endpoint through the send() function. You may need to update your version of the Admin SDK. You can see an example in the documentation here.
For the code you provided, for example, you would send a message like this:
let message = {
notification: {
title: '$GOOG up 1.43% on the day',
body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
},
data: {
channel_id: threadId,
},
android: {
ttl: 3600 * 1000,
notification: {
icon: 'stock_ticker_update',
color: '#f45342',
},
},
apns: {
payload: {
aps: {
badge: 42,
},
},
},
token: deviceToken,
};
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);
});
Notice the device token is now in the message object.

Resources