npm-gcm does not send notification to the device - android

guys, I want to send a notification to the android device using npm-gcm
and here is my code:
var sender = new gcm.Sender('myAPIkey');
var message = new gcm.Message();
message.addNotification('title', 'Backend!!!');
message.addNotification('body', 'Bitch');
var regTokens = ['deviceToken1'];
console.log(message)
regTokens.push('deviceToken2')
sender.send(message, { registrationTokens: regTokens }, function (err, response) {
if (err) console.error(err);
else console.log(response);
});
and in the console I get:
{ multicast_id: 7664202372197545000,
success: 2,
failure: 0,
canonical_ids: 0,
results:
[ { message_id: '0:1481660978053751%cc7dad02f9fd7ecd' },
{ message_id: '0:1481660978045814%cc7dad02f9fd7ecd' } ]
}
but the devices did not receive any notification. What is the problem?
Why is this happening? Can you give me an advice?!

Based on this SO post,there might be an issue with "notification" object on node-gcm code. Try to use message.addData and check if it works. Make sure that you followed this tutorial and this thread that gives sample code on how to send simple message to your device.
var sender = new gcm.Sender(googleApiKey);
var message = new gcm.Message();
message.addData('key1','testdarinodegcm');
message.delay_while_idle = 1;
var registrationIds = [];
registrationIds.push('APA91bHCzBP6wEfExCZlSXgf0wuOC6QEWJ-7MVFl3hgaW3Jv8FslsofGJ- qgdliyS8zjwy_W7zPaKsEZx6kbeuWdoAAexawKl1Qd6GEGV_v844n1LMRaTsWeiwI9iaLGKKq_R3scY_wuRG8uG2SZ5X9q0J67Ko3gcw');
sender.send(message, registrationIds, 4, function (err, result) {
console.log(result);
});
Hope this helps!

Related

Any way to improve sending push notification quickly using cloud function and fcm or some alternative?

I'm working on a Android Chat App and for sending a push notifications for the chat i have deployed a Cloud Function to which is sending notification through Firebase Cloud Messaging. But there's a quite delay in receiving notifications. Is there any alternative for send notification quickly or improving it?
The code for my cloud function:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.sendUserMessageNotification = functions.firestore.document("MessagesCollection/{messageChannel}/Messages/{messageId}").onCreate((snap, context) => {
const document = snap.data();
const message = document.message;
const toUserId = document.toUserId;
const fromUserId = document.fromUserId;
const fromUserName = document.fromUserName;
const isAudioMessage = document.audioMessage;
db.collection("TokenCollection").doc(toUserId).get().then(document => {
if(document.exists) {
var tokenDocument = document.data();
var payload;
if (isAudioMessage) {
payload = {
data: {
"title": "Message Recieved",
"body" : "Voice Message from " + fromUserName,
"type": "Message",
}
};
} else {
payload = {
data: {
"title": "Message Recieved",
"body": "Text Message from " + fromUserName,
"type": "Message"
}
};
}
return admin.messaging().sendToDevice(tokenDocument.deviceToken, payload).then(response => {
console.log("Message Sent Successfully");
});
}
});
});
I'm attaching an image to my cloud function log too maybe it's helpful
If you are referring to last execution visible in the logs it seems to be matter of "cold start".
From the log I can see that previous executions have been performed an hour earlier, so I suppose that the execution environment is often initialized from scratch.
You can read few words about it in Firebase functions Tips & tricks article.

Repeating push notification in back4app

I am sending push notification from iOS and Android both by calling a cloud function, and in each device I am getting 5 times a single push notification. I am using parse database hosted on back4app.
Cloud code is given below:
Parse.Cloud.define("push", function (request, response) {
var query = new Parse.Query(Parse.Installation);
var userID = request.params.user;
var message = request.params.message;
var notificationType = request.params.notificationType;
var user = new Parse.User();
user.id = userID;
query.equalTo('user', user);
query.equalTo("allowPush", true);
Parse.Push.send({
where: query,
data: {
alert: message,
sound: 'default',
"type": notificationType
}
}, { useMasterKey: true });
});
Try to call reponse.success and response.error functions in the end of your cloud code function. Since your client code is not receiving the feedback if the call worked or not it is probably attempting to send again.
Parse.Cloud.define("push", function (request, response) {
var query = new Parse.Query(Parse.Installation);
var userID = request.params.user;
var message = request.params.message;
var notificationType = request.params.notificationType;
var user = new Parse.User();
user.id = userID;
query.equalTo('user', user);
query.equalTo("allowPush", true);
Parse.Push.send({
where: query,
data: {
alert: message,
sound: 'default',
"type": notificationType
}
},
{
success: function () { response.success(); },
error: function(err) { response.error(err); },
useMasterKey: true
});
});

Firebase Function - device token empty

I need help, I've been searching for solutions all day but I can't fix my issue, the code below won't read the device tokens.
Below contains my db structure. I manage to receive the log: 'We have a new News for you.' When I added a new post but I received the log "There are no notification tokens to send to." Which means it cannot detect the device tokens even though there is already ones. What am I doing wrong?
{
"Newsv2" : {
"All" : {
"-Ktr7ZkuChCjsUIMb_4f" : {
"title" : "",
"type" : "",
}
},
"Usersv2" : {
"h0RzzpdO7nZVLpAR4fi7xRWUqsT2" : {
"device_token" : "",
"name" : "",
"user_no" : ""
}
},
}
/--News
--All
--name
--desc
/--Usersv2
--{userID}
--device_token
exports.sendNotif = functions.database.ref('/Newsv2/All/{newsID}').onWrite(event => {
const newsID = event.params.newsID;
const userID = event.params.userID;
if (!event.data.val()) {
return console.log('News! ', newsID);
}
console.log('We have a new News for you!',newsID);
// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database().ref(`/Usersv2/${userid}/device_token`).once('value');
return Promise.all([getDeviceTokensPromise]).then(results => {
const tokensSnapshot = results[0];
//const follower = results[1];
// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
//console.log('Fetched follower profile', follower);
// Notification details.
const payload = {
notification: {
title: 'Test Message',
body: '',
icon: ''
}
};
// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.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);
});
});
});
To get the device token I store it in my firebase DB when a user registers or logs in.
private DatabaseReference mUserDatabase;
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users/");
//and if the login/register is successful
mUserDatabase.child("device_token").setValue(deviceToken).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
application.startActivity(intent);
}
});
as for my firebase funciton:
const deviceToken = admin.database().ref(`/Users/${unique_id}/device_token`).once('value');

Fcm Notifications push android/IOS nodejs

I am looking for to send a notification from a Nodejs server, but I am getting some errors that I don't know how solve it. Could someone help me? I found this possible solution on Internet --> URL
This is my code in nodejs
var FCM = require('fcm-push');
function sendNotification (){
var serverKey = 'AAAAJnK3Ing:AP-(more caracters)AwAlBL_CvXIkFM2UufYZHYkvhC7FP3Tu16mlI';
var fcm = new FCM(serverKey);
var message = {
to: 'd2b2v(more caracters token)DUmAXqU-uHptJJLRPXukl',
/*data: {
your_custom_data_key: 'your_custom_data_value'
},*/
notification: {
title: 'notification',
body: 'This is a notification from node'
}
};
//callback style
fcm.send(message, function(err, response){
if (err) {
console.log("****************************************************")
console.log(message)
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ", response);
}
});
//promise style
fcm.send(message)
.then(function(response){
console.log("Successfully sent with response: ", response);
})
.catch(function(err){
console.log("----------------------------------------------------")
console.log("Something has gone wrong!");
console.error(err);
})
}
module.exports = {
sendNotification
}
I am getting this error
Try to check if your firewall allow to connect on 443 port. It seems like it can't create the connection.

Unable to push GCM notification using node-gcm

I need to push GCM from node, I am using node-gcm, but I am getting ENOTFOUND error
var gcm = require('node-gcm');
var gcmMessage = new gcm.Message({
collapseKey: 'notify',
delayWhileIdle: false,
timeToLive: 3600,
data: {
title: "Hai",
message: "Message",
}
});
var gcmIds = ['<myid>'];
var sender = new gcm.Sender('<mysender id>',{'proxy':'<proxyip>:8080'});
sender.send(gcmMessage, gcmIds, 4, function(err, ret){
console.log('>>> sendGcm: ', err, ret);
});
I am getting error
sendGcm: { [Error: tunneling socket could not be established, cause=getaddr
info ENOTFOUND] code: 'ECONNRESET' } null

Categories

Resources