I am working with sending push notifications to my react native apps via firebase cloud messaging. I get the push token from the device and store it in my database.
When calling the push notification from the back end (nodejs), it works a few times and I see the push notification on my phone. After about two times of sending the notification, all of a sudden it starts giving me a failure
List of tokens that caused failures: {"responses":[{"success":false,"error":{"code":"messaging/invalid-argument","message":"Request contains an invalid argument."}}],"successCount":0,"failureCount":1}
Then I get another message on the next one, which is the message going forward:
List of tokens that caused failures: {"responses":[{"success":false,"error":{"code":"messaging/registration-token-not-registered","message":"Requested entity was not found."}}],"successCount":0,"failureCount":1}
This is my code for sending push notifications on nodejs:
const message = {
tokens: registrationTokens,
notification: {
"title": "TEST",
"body": "TEST body"
},
data: {
"action": "New_Card",
"unique_id": 1
}
}
fbMsging.sendMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(registrationTokens[idx]);
}
});
console.log('List of tokens that caused failures: ' + JSON.stringify(response));
console.log('List of tokens that caused failures: ' + failedTokens);
callback(false);
} else {
console.log(response.successCount + ' messages were sent successfully');
callback(true);
}
});
Please advise.
Related
I know there are lot of questions around this question, and I promise I've checked quiet a number of them but non seems to give me an exact answer
I'm using firebase cloud function's admin messaging SDK to send push notifications to an array of device token I put together from my users collection.
The code:
let deviceToken = [<device tokens>];
let payload = {
notification: {
title: main_title,
body: notf_body,
},
data: {
<data object>
},
};
await messaging
.sendToDevice(deviceToken, payload)
.then((response) => {
console.log("Successfully sent message to::", response.successCount);
})
.catch((error) => {
console.log("Error sending message:", error);
});
} else {
console.log("ARTICLE PUBLISHED BUT NOT BROADCASTED");
return;
}
seems to be working fine but the push notification is never sent to all the device token in the array...
Below is a log of the function triggered, where 49 device token are present in the array but only 32 notifications are successful
What could be the reason for this, as some clients have been complaining they aren't getting notification
There are quite some reasons why sending a message to a token might fail. The specific reason for each token that failed is specified in the response.results that you get back.
The most common reasons are that tokens get outdated/expired over time, meaning they won't work anymore. In a well working app, you'll register new tokens for the those same devices, but failure to clean up the old tokens from your database will result in more and more failures over time.
For a good example of how to deal with these errors and clean up outdated tokens, see this code from the example of sending notifications in Cloud Functions:
// Listing all tokens as an array.
tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
functions.logger.error(
'Failure sending notification to',
tokens[index],
error
);
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
I'm using the latest Azure Communication SMS package, and basically directly copy/pasted the sample code to try sending a text to my cell. I got a successful 202 code back and can see the event successfully in the event grid I set up. But my phone never got the text, if it helps T-Mobile is my cell provider and I reside in the US with a US cell number.
Here is my code sample and response with sensitive information redacted
public sendSms = async (message: string, numbers: string[]) => {
if (this.checkIfReachLimit()) {
return;
}
const endpoint = `https://<resource name>.communication.azure.com`;
const credential = new AzureKeyCredential("<cred>");
const client = new SmsClient(endpoint, credential);
try {
const sendResults = await client.send(
{
from: "My Azure Toll Free #", // Your E.164 formatted phone number used to send SMS
to: numbers, // The list of E.164 formatted phone numbers to which message is being sent
message, // The message being sent
},
{
enableDeliveryReport: true,
tag: "workoutBuilder",
},
);
this.updateMonthlyCount(sendResults.length);
for (const sendResult of sendResults) {
if (sendResult.successful) {
console.log("Success: ", sendResult);
} else {
console.error("Something went wrong when trying to send this message: ", sendResult);
}
}
} catch (ex) {
// no op
}
};
Response:
{
to: 'my cell',
messageId: 'message id',
httpStatusCode: 202,
repeatabilityResult: 'accepted',
successful: true
}
I am using fcm to send push notifications to mobile devices including both ios and android. I have a table in firestore that has device ids of the registered users. I loop through that table and send push notifications to mobile devices. I am using following code for push notification.
const sendNotification = (deviceId, userId) => {
return new Promise((resolve, reject) => {
let message = {
notification: {
title: 'TITLE',
body: `notification is sent to ${userId}`
}
};
let options = {
contentAvailable: true,
priority: "high",
timeToLive: 60 * 60 * 24
};
firebase.messaging().sendToDevice(deviceId, message, options)
.then(function (response) {
resolve({
message: `Successfully sent message`
})
console.log(`notification sent to ${userId}`);
})
.catch(function (error) {
reject({
message: "There is an issue sending push notification"
})
console.log('Error sending message:', error);
});
});
};
the problem is notification is sent successfully to all devices but is not received by all devices. Sometimes it is delivered on device A and when I rerun the code, push notification is not delivered to that device.
Sometimes push notifications are received on all devices and sometimes none of the devices gets any push notification.
I am calling sendNotification in a for loop that is basically iterating the documents present in a table and each document contains user id of the user and device id of that user's mobile device.
I am newbie to push notifications, and i have done the code part which i have taken reference from googling and it is working fine, but my query is :
sending push notification to group of people (using array)
and there is chance to be at least one wrong gcm-id in that array
if there is a wrong gcm-id, populates error like "Not Registered" or "MisplacingId" (while sending individually)
Now, the gcm-id is in an array, then the push will send for remaining people or it will block there itself?
and here is my code :
var GCM = require('gcm').GCM;
var apiKey = 'xyz';
var gcm = new GCM('apiKey');
var message = {
registration_id: ['x','y'],
collapse_key: 'Hello',
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 3,
};
gcm.send(message, function(err, messageId){
if (err) {
console.log("Something has gone wrong!");
console.log(err);
} else {
console.log("Sent with message ID: ", messageId);
}
});
and please tell me there is any limt(Number of gcmid's)? in one push?
It will send push notifications to all the registration ids even if few of them appear to be invalid in between the array.
Sample response when the registration id is not valid
{
multicast_id: 8976424350191695000,
success: 1,
failure: 1,
canonical_ids: 1,
results: [
{
registration_id: "value-of-correct-registration-id",
message_id: "0:1460568231005603%ade1213ff9fd7ecd"
},
{
error: "InvalidRegistration"
}
]
}
The success and failure count will show the number of push notifications sent and failed. And there is no limit applied on the number of registration ids.
I am trying to use Firebase, Node.js, and Google Cloud Messaging to send push notifications for an iOS app. Below is the Node.js code
var Firebase = require('firebase'),
gcm = require('node-gcm')
;
var pushRef = new Firebase("https://<myapp>.firebaseio.com/ios/queue/tasks");
pushRef.on("child_added", function(snapshot) {
console.log("child added event registers");
var notificationData = snapshot.val();
sendNotification(notificationData);
snapshot.ref().remove();
});
function sendNotification(notificationData) {
var message = new gcm.Message({
notification: {
title: "Title",
body: notificationData.message
}
});
var sender = new gcm.Sender(<my Google Server Key>);
var registrationTokens = [notificationData.recipientId];
console.log("about to send message");
console.log("this is the registration token: " + registrationTokens);
sender.send(message, { registrationTokens: registrationTokens }, 10, function (err, response) {
if(err) {
console.error(err);
} else {
console.log(response);
}
});
}
There are no errors, and all of the console.log statements register. However, I never receive a push notification on my device. Here is the console.log(response):
{ multicast_id: 7398179070839209000,
success: 1,
failure: 0,
canonical_ids: 0,
results: [ { message_id: '0:1457564370785913%939a5f18939a5f18' } ] }
What might be going on? It looks like things should be working, but they aren't
By default messages are sent with standard priority, which according to Google Cloud Messaging docs:
This is the default priority for message delivery. Normal priority messages won't open network connections on a sleeping device, and their delivery may be delayed to conserve battery. For less time-sensitive messages, such as notifications of new email or other data to sync, choose normal delivery priority.
Somehow this normal priority seems to affect iOS more than Android apps.
To get the messages delivered immediately, you'll want to add priority: 'high' to you message:
var message = new gcm.Message({
priority : "high",
notification: {
title: "Title",
body: notificationData.message
}
});