GCM Push Notification NodeJS - node.js

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.

Related

Azure SMS message is not received on phone after a successful response

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
}

Firebase push token works only a few times

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.

Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM

I got this code from my client iOS app on XCode console
Firebase registration token: diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h
diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h
NodeJS
console.log("START");
var FCM = require('fcm-node');
var serverKey = require('/Users/bheng/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json')
var fcm = new FCM(serverKey)
var collapseKey = 'new_message';
var message = {
to: 'diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
data: {
cpeMac: '000000000000',
type: 'malware'
},
notification: {
title: 'Hello baby',
body: 'Nice body',
tag: collapseKey,
icon: 'ic_notification',
color: '#18d821',
sound: 'default',
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!")
console.log(JSON.stringify(err));
} else {
console.log("Successfully sent with response: ", JSON.stringify(response))
}
})
console.log("END");
Result
When I run it
node app.js
I kept getting
START
END
Successfully sent with response: {"results":[{"error":{"code":"messaging/invalid-registration-token","message":"Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM."}}],"canonicalRegistrationTokenCount":0,"failureCount":1,"successCount":0,"multicastId":7577724855311354000}
How would one go about debugging this further?
your token has some additional random string such as
to: 'diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
just remove : diWY78iar8s: from your token string
console.log("START");
var FCM = require('fcm-node');
var serverKey = require('/Users/bheng/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json')
var fcm = new FCM(serverKey)
var collapseKey = 'new_message';
var message = {
to: 'APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
data: {
cpeMac: '000000000000',
type: 'malware'
},
notification: {
title: 'Hello baby',
body: 'Nice body',
tag: collapseKey,
icon: 'ic_notification',
color: '#18d821',
sound: 'default',
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!")
console.log(JSON.stringify(err));
} else {
console.log("Successfully sent with response: ", JSON.stringify(response))
}
})
console.log("END");
Response from FCM :
Successfully sent with response: { results: [ { messageId: '0:1543448946734425%479ec0e2479ec0e2' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 6133765431734591000 }
One of the interesting reasons for invalid registration is: that device have a different token. Maybe you are trying to use a past token.
In my case what happened was I was getting the FCMRegistrationToken from my colleague via Discord and the Ctrl+C Ctrl+V was modifying the token. On obtaining the token via email solved the issue.

How can I get 'payload' property from the Messages list? Gmail API

I'm new in node, and I want to get info about my gmail messages, like who's wrote the message and the text.
I follow quickstart exemple and write the following code, but there are just 'id' and 'threadId' field in output.
function listMessages(auth) {
var gmail = google.gmail('v1');
gmail.users.messages.list({
auth: auth,
userId: 'me'
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var messages = response.messages;
if (messages.length == 0) {
console.log('No messages found.');
} else {
console.log('Messages:');
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
console.log(message);
}
}
});
}
Could somebody explain me? Thanks.
messages.list() API returns only the message IDs and thread IDs by design. If you need to get details of those messages you need to make another API call messages.get() to get specific details of each message.
API reference:
https://developers.google.com/gmail/api/v1/reference/users/messages/get
While this will work, you may want to have a look at GMail's batch operations which allow getting details of messages in one call (with limitations though).
Google's guide on batch:
https://developers.google.com/gmail/api/guides/batch
Similar queries have been answered here at SO:
Gmail API all messages
Gmail API Users.messages: list
function getMessage(userId, messageId, callback) {
var request = gapi.client.gmail.users.messages.get({
'userId': userId,
'id': messageId
});
request.execute(callback);
}
add "me" as userId and add your message id in messageId filed. others fields are optional.

Push Notifications With Firebase, Node.js, and Google Cloud Messaging for iOS app

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
}
});

Resources