FCM send to two keys at once? - android

Is there a way with FCM to send to two server keys at once with one reqeust? I'm currently using the following code to send notifications
const rp = require("request-promise");
const rawKeys = "key-one, key-two";
function sendToKey(serverKey) {
const requestOptions = {
method: "POST",
uri: "https://fcm.googleapis.com/fcm/send",
headers: {
Authorization: "key=" + serverKey
},
json: true,
body: {
to: "Device Token Here",
priority: "high",
content_available: true,
notification: {
title: "Test Title",
body: "Test Body",
deepLink: "https://google.com",
sound: "default"
},
data: {
title: "Test Title",
body: "Test Body",
deepLink: "https://google.com"
}
}
};
return rp(requestOptions)
.then(resp => {
console.log(JSON.stringify(resp));
});
}
rawKeys.split(",").map(serverKey => sendToKey(serverKey));
I'm trying to avoid running multiple reqeusts so is there a way to send to two keys within a single request?

Related

Is there a way to send firebase push notification to both iOS and android using nodejs?

I have written this code with nodejs to send a push notification from a nodejs server to a specific user of a mobile application:
const { admin } = require("../config/Firebase");
const sendNotification = async (req, res) => {
const requestBody = req?.body;
const registrationToken = requestBody?.registrationToken; // get it from mobile app
const data = {
message: {
token: registrationToken,
notification: {
title: "Notification Title",
body: "Notification Body ",
description: "Notification description",
},
android: {
notification: {
imageUrl: "https://foo.bar.pizza-monster.png",
},
},
apns: {
payload: {
aps: {
"mutable-content": 1,
},
},
fcm_options: {
image: "https://foo.bar.pizza-monster.png",
},
},
webpush: {
headers: {
image: "https://foo.bar.pizza-monster.png",
},
},
data: {
Nick: "Mario",
Room: "PortugalVSDenmark",
},
},
};
try {
admin.messaging().send(data.message);
res.status(200).json({ notificationStatus: "success" });
} catch (error) {
console.log("Error while sending notification: ", error);
res.status(500).json({ notificationStatus: "failed" });
}
};
But it works only for android devices. So i would like to know if there a config or something like that which makes the server sends it to both iOS and android devices ?

How to correctly specify channel_id in FCM using cloud functions

Unfortunately, no answer yet. I am checking out postman, I hope I can use that to test quicker.
I manage to send a notification through my app, however, the notification always ends up in the silent notification of my phone, no sound, no vibration and no notification icon in the top left of the phone, only a notification in the drawer when I swipe down :(
In an attempt to fix / improve the situation I tried the following:
Create an android notification channel with id: high_importance_channel by using flutter_local_notifications package. The channel was created successful, because requesting an overview of the existing channels, showed the newly created channel (among the other channels). The new channel has importance: 5, enableVibration: true and playSound: true, so that should do the job.
Send a FCM through cloud functions with the following code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.chatNotification = functions.firestore
.document('chats/{groupId}/chat/{chatId}')
.onCreate( async (snapshot, context) => {
const message = {
"notification": {
"title": "Message Received",
"body": "Text Message from " + fromUserName,
},
"tokens": registrationTokens,
"android": {
"notification": {
"channel_id": "high_importance_channel",
},
},
};
admin.messaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
}
But so far not luck, the notification still ends up in the silent notifications. What am I doing wrong?
There are 2 ways of doing it. Might work in your case.
Way 1:
var payload = {
notification: {
android_channel_id: 'AppChannel',
/*
https://stackoverflow.com/questions/62663537/how-do-i-add-a-channelid-to-my-notification
https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support
*/
title: 'Push Notification Arrived!',
body: 'Using Cloud Functions',
sound: 'default',
},
data: {
route: '/someRoute',
},
};
try {
const response = await admin.messaging().
sendToDevice(deviceTokens, payload);
console.log('Notification sent succesfully.');
} catch (err) {
console.log('Error sending Notifications...');
console.log(err);
}
Way 2:
const message = {
/*
https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.basemessage.md#basemessagenotification
*/
notification: {
title: 'Push Notification Arrived!',
body: 'Using Cloud Functions',
},
data: {
route: '/someRoute',
},
android: {
/*
https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.androidnotification.md#androidnotificationbodylockey
*/
notification: {
channelId: "AppChannel",
priority: 'max',
defaultSound: 'true',
},
},
token: deviceTokens,
};
// https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.messaging.md#messagingsend
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, for LOVEs sake:', error);
});

How to add settings for Android in the message

I have a code that prepares and sends a notification to a mobile application
// Create the notification
const payload = {
notification: {
title: "Title",
body: "Body",
},
};
// Options
const options = {
contentAvailable: true,
priority: 'high'
};
admin
.messaging()
.sendToDevice(tokenSnapshot, payload, options)
.then(response => {
console.warn(">> Notification sent successfully: ", response);
return response;
})
.catch(error => {
console.warn(">> Notification sent failed: ", error);
});
I would like to add here information such as:
priority: 'max'
visibility: 'public'
These are features supported in Android
It is mentioned in the documentation that it exists.
But there is nothing mentioned how to use it
Can anyone give advice?
The purpose of this is to display Notifications on your phone when it is in the background

Flutter firebase cloud function, playload issue

I'm using firebase cloud function for send push notification. It works but issue by default it shows badge and does not play sound when notification comes.
Below is my playload code.
var playload = {
notification: {
title: msgData.title,
body: msgData.message,
sound: 'default',
badge: '0',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
},
data: {
title: msgData.title,
body: msgData.message,
sound: 'default',
badge: '0',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
}
var options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
return admin.messaging().sendToDevice(tokens, playload, options).then((response) => {
console.log('Sent to all the devices');
return response;
}).catch((err) => {
console.log(err);
return 0;
})
I have set 'sound': 'default' and badge: '0' but doesn't help me.
UPDATED:
I have tried with double quote for both keys and values but didn't work yet.
var playload = {
"notification": {
"title": msgData.title,
"body": msgData.message,
"sound": "default",
"badge": "0",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
},
"data": {
"title": msgData.title,
"body": msgData.message,
"sound": "default",
"badge": "0",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
}
Have you tried to replace your single quotes with double quotes?
From JSON.org:
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array. These structures can be
nested.
The title and the body of your message is processed before it eventually will fail which might be why it seems that your formatting is okay.
Let me know whether this has helped you.

OneSignal push notification on Ionic 3: All included players are not subscribed

I'm developing an Android Application using Ionic 3 and I want to use push notification with tool OneSignal. Here is the code that I use at my main component:
let iosSettings = {
kOSSettingsKeyAutoPrompt: true,
kOSSettingsKeyInAppLaunchURL: false
}
this.oneSignal
.startInit(APP_ID, GOOGLE_PROJECT_NUMBER)
.iosSettings(iosSettings);
this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);
this.oneSignal
.handleNotificationReceived()
.subscribe((notification: OSNotification) => {
console.log(notification)
});
this.oneSignal.endInit();
And here is the code that I use at my node webservice:
function sendNotification(scheduling) {
const schedulingID = scheduling.email + scheduling.date;
const message = {
app_id: APP_ID,
headings: {"en": MY_APP_NAME},
contents: {"en": "Scheduling confirmed!"},
data: {"agendamento-id": schedulingID},
included_segments: ["All"]
};
const headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic " + REST_API_KEY
};
const options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
console.log("Sending notification...");
const req = https.request(options, function (res) {
res.on('data', function (data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function (e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(message));
req.end();
}
But, when I execute the Android App on my devices, I get the message error:
{id: '', recipients: 0, errors: ['All included players are not subscribed']}
This will solve your problem:
'included_segments' => array(
'Subscribed Users'
),

Categories

Resources