nandarustam / fcm-push Goto Github PK
View Code? Open in Web Editor NEWA Node.JS simple interface to Firebase Cloud Messaging (FCM) for Android & iOS
License: MIT License
A Node.JS simple interface to Firebase Cloud Messaging (FCM) for Android & iOS
License: MIT License
TypeError: Object # has no method 'send'
I declare a var at the same lines as example.
Hey guys,
I tested using fcm-push right at the beginning of my node.JS routine and it worked flawlessly. I then added some logic to it and chose to send a push when a certain value was read from the database. I'm calling my function sendPush inside a database read from firebase, and my sendPush function is the following:
function sendPush(userToken, messageTitle, messageBody) {
var message = {
to: userToken, // required fill with device token or topics
notification: {
title: messageTitle,
body: messageBody
}
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong! " + err);
} else {
console.log("Successfully sent with response: ", response);
}
process.exit();
})
}
When I execute this code it gives the following error now:
'TypeError: Converting circular structure to JSON'
I'm sure that my messageTitle, messageBody, and userToken aren't circular since I printed them to the console and it is outputting regular strings. Does anybody know what is going on?
My app is using cordova fcm plugin. FCM Push notifications work perfectly fine in development in ios. But no Push Notifications are received in production (Ad hoc and Distribution).
The token generated in null. I have rechecked all my certificates and provision profiles, all are fine. I have Push Notifications, key sharing and remote notifications enabled in capabilities in xcode. I am not sure what I am missing out.
Thanks.
Hi is it possible to send to multiple tokens at once, most of the time the users are logging in from multiple devices ios, ipad, android and so on, I was wondering is it possible to send the notification to multiple tokens at once. Or on fcm.send(messages[]....)
The problem now is after sending the notification I am saving it to mongodb, but with that logic I have to create some kind of a promise to see when all of them are send then to save it to the database
Hi,
I got this error when I try to send a notification
(node:29273) Warning: a promise was rejected with a non-error: [object String]
NotAuthorizedError
It was first node:27877
before changing after I relaunch.
Here is my nodejs code
var fcm = new FCM(token);
var message = {
to: user.firebase_token,
data: {
id: xxxxxxxxxxx
},
notification: {
title: 'Title'
body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam efficitur ipsum in placerat molestie. Fusce quis mauris a enim sollicitudin'
}
};
fcm.send(message, function(err, response) {
if (err) {
console.log(err);
console.log(errorHandler.getErrorMessage(err));
} else {
console.log('Successfully sent with response');
console.log(response);
}
});
You give string to promise reject function instead of Error.
Warning: a promise was rejected with a non-error: [object String] at IncomingMessage.respond (/Users/Adrien/Documents/projects/apps/node/liita/NodeAPI/node_modules/fcm-push/lib/fcm.js:106:32) at emitNone (events.js:72:20) at IncomingMessage.emit (events.js:166:7) at endReadableNT (_stream_readable.js:905:12) at nextTickCallbackWith2Args (node.js:455:9) at process._tickCallback (node.js:369:17)
fcm-push: ^1.1.2
Sometimes getting an error message while trying to send push notification to Android device.
{"err":"Error: read ECONNRESET\n at exports._errnoException (util.js:1018:11)\n at TLSWrap.onread (net.js:572:26)"}
push message:
{
"to":"SOME_REGISTRATION_ID",
"priority":"high",
"data": {"SOME_DATA":"VALID"}
}
As far as I know the registration id is valid and the data is not unique and sent properly to other devices.
This issue may be related:
#51
but was closed without any comments
Hey,
I'm having an issue where if I send two notifications in parallel, one to an ID of a device I know exists and one to a dummy ID, I get an 'InvalidRegistration' error from both .send() functions. The device does receive the 1st notification.
This causes an issue because when I get an error I want to remove that particular device token from the users tokens on the server. Currently it removes both the invalid token and the valid one resulting in the user having zero tokens and not receiving any future notifications.
Here's a gist of the script to cause this error:
https://gist.github.com/alexfoxy/1e8cdb7c3f127e6594e8e963e39224e6
You should get an output of:
FCM.send
FCM.send
{"multicast_id":8969037943863178607,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
{"multicast_id":8969037943863178607,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
If you send them in series it works correctly [ i.e. by moving send2() into the callback of send1() ] - output:
FCM.send
{"multicast_id":7502545296558413858,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1470046298701173%108c2029108c2029"}]}
FCM.send
{"multicast_id":8933073754773609814,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
This might be a bug in Firebase itself so I'm also raising this as an issue with them.
A
I'm using fcm-push for a node.js server. It's almost working, but I get an InvalidServerResponse
error when the message sends. What does this mean?
Here is my code:
var Firebase = require('firebase'),
FCM = require('fcm-push');
var config = {
serviceAccount: {
projectId: keys.project_id,
clientEmail: keys.client_email,
privateKey: keys.private_key
},
apiKey: keys.firebase_api_key,
authDomain: keys.firebase_auth_domain,
databaseURL: keys.firebase_database_url,
storageBucket: keys.firebase_storage_bucket
};
var app = Firebase.initializeApp(config);
var pushRef = Firebase.database().ref('root/queue/tasks');
// listen for items added to the queue
pushRef.on("child_added", function(snapshot) {
console.log("child added event registers");
var notificationData = snapshot.val();
sendNotification(notificationData);
pushRef.remove();
});
function sendNotification(notificationData) {
var registrationTokens = [notificationData.recipientId];
var serverKey = keys.fcm_server_key;
var fcm = new FCM(serverKey);
var message = {
to: registrationTokens,
priority: 'high',
notification: {
title: "Hello",
body: notificationData.message,
sound: "default"
,
badge: notificationData.badge,
type: notificationData.category
}
};
console.log("about to send message");
console.log("this is the registration token: " + registrationTokens);
console.log("this is the registration badge number: " + notificationData.badge);
fcm.send(message, function(err, response){
if(err) {
console.error("There was an error: " + err);
} else {
console.log("Push Notification sent successfully!");
console.log(response);
}
});
}
And here is the console message:
child added event registers
about to send message
this is the registration token: (correct registration token value)
this is the registration badge number: 3
There was an error: InvalidServerResponse
I know the registration token is the correct one because I'm able to send notifications to it from my dashboard.
please can you add object for notification icon
Both of these styles to send notification (promise and callback) fail when used default syntax.
Here is better way to send:
var message = {
to: ele.token,
data: {
pn_title: ele.title,
pn_body: ele.body
},
notification: {
title: ele.title,
body: ele.body
}
};
return new Promise((resolve, reject) => {
const options = {
host: "fcm.googleapis.com",
path: "/fcm/send",
method: 'POST',
headers: {
'Authorization': process.env.authorization,
'Content-Type': 'application/json'
}
};
fcm.send(message, function(err, res) {
if(err) {
reject(err);
}
else {
resolve(res);
}
});
});
Any way to send messages to an specific Topic? I don't see this in the official documentation either. Thanks.
I have a table in my database that contains user id and device id. I loop through that table and send a notification to each user. Notifications are sent successfully to each user but not always received on the mobile device.
Hi,
I get no errors when sending message with an invalid to-token (tested with both callback and promise).
message :
{ to: 'invalid-token', data: { your_custom_data_key: 'your_custom_data_value' }, priority: 'high', content_available: true, notification: { title: 'Title of your push notification', body: 'Body of your push notification' } }
Sending this message:
{ to: 'fF7bn7WY1do:APA91bGvSCzdicCXwfoaoBYuVLb7-qxK0XlHb_eUiGEAnxeE18MzctudZCJ7lHZcPm5UlxWeH27rm7-MuhkIMW1_rUVyPJKI7NONjud5tXB5lC3Sip43h2J9h-8M_xkpcPWVnv7nCz4Z',
data: { source: '10208273026137463' },
notification: { title: 'h16' } }
I set serverkey from Firebase console, the Firebase Cloud Messaging token
.
What is wrong?
I am using this module for pushing notifications in an Android notifications.
It is very important that the notifications pop up asap according to the app requirements.
It was working perfectly till yesterday but suddenly yesterday, there was an issue and only phones with a few versions of android could get the notifications and mainly Android 8 did not receive the notifications and all.
If anyone has ever faced an issue like this, please help me out asap as it is very urgent for us to solve this problem.
Can someone please shed light on the mismatchedsenderId issue.
Getting an error: MismatchSenderId
var registrationId = ‘Valid device token’
var message = {
to: registrationId,
collapse_key:’OUR BUNDLE ID << DONT KNOW WHAT THIS IS SUPPOSED TO BE',
notification: {
title: 'Title of the notification',
body: 'Body of the notification'
}
};
fcm.send(message)
.then(function(response){
console.log("Successfully sent with response: ", response);
def.resolve({Error: false, message: response})
})
.catch(function(err){
console.log("Something has gone wrong!");
def.resolve({Error: true, message: "Something has gone wrong !", error: err})
console.error(err);
})
The data
parameter of the message to send contained the key from
that caused a rejection and InvalidServerResponse
error.
The message was scrubbed until the culprit from
was identified. Once removed, the notification was successfully sent.
If this is reproducible, the library should either scrub blacklisted keywords (i.e. assuming there may be other keywords causing the same behavior) or the documentation should point to keywords to avoid including the data
parameter of messages.
Here is a sample script:
var FCM = require('fcm-push');
var serverKey = $KEY;
var fcm = new FCM(serverKey);
var message = {
to: $DEVICE_TOKEN, // required fill with device token or topics
data: {
from: 'bar'
},
notification: {
title: 'foo',
body: 'bar'
}
};
//callback style
fcm.send(message, function(err, response){
if (err) {
console.log(err)
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ", response);
}
});
with sample response:
InvalidServerResponse
Something has gone wrong!
Hello,
How can i pass multiple "registration_token_or_topics"?
eg - var fcmNotification = {
to : toekn1, token2, token3,
notification : {
title : 'Bus schedule',
body : msg_body,
sound : 'default'
}
}
Thanks in advance.
SyntaxError: Unexpected token E in JSON at position 0
at Object.parse (native)
at ClientRequest.TopicRequest.https.request.on (/home/social/node_modules/fcm-node/lib/topic_request.js:24:18)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketOnEnd (_http_client.js:346:9)
at emitNone (events.js:91:20)
at TLSSocket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
Hi!
This is my code for send push notification:
In chat.js
function *sendMessage(data){
let sender = yield utils.getMe({ data.token });
let recipient = data.recipient;
let content = data.content;
let devicesList = yield utils.getAndroidDeviceToken(recipient);
for(let device of devicesList){
// Set a custom message:
let message = {
to: device.Android_Device_Token,
data: {
action: 'message',
from : sender.id,
content : content
},
notification: {
title: 'AppName',
body: `${sender.firstName} ${sender.lastName} sent you a message`
}
};
// Send push notification:
yield fcm.sendPushNotification(message);
}
}
In fcm.js
const FCM = require('fcm-push');
const config = require('../config.js');
const serverKey = config.firebase.serverKey;
let fcm = new FCM(serverKey);
module.exports.sendPushNotification = function *sendPushNotification(message){
fcm.send(message)
.then(function(response){
console.log("[FCM] Successfully sent with response: ", response);
})
.catch(function(err){
console.log("[FCM] Something has gone wrong: ", err);
});
}
The message object is :
{
to:'eU2zIkuCiss:APA91bE8KUg54SOhwfkuU9xFPqIuOXLaAbXJAx2YPq6U2oW8GqdfXwhtSnD1dCRcrp3ylIlQU3HqNqDCiN94HjqrQz7Ty0ANe0IJo4Oea95WIy5gFrWJUin0jmscwdfnVjMRxmkjbTtC',
data:{
action:'message',
from:'6103',
content:'hello!'
},
notification:{
title:'AppName',
body:'Cristina Shady sent you a message'
}
}
But I receive an error from FCM InvalidServerResponse, and does not send push notification.
Can someone help me? Thank you!
Hi everybody, i'm testing "fcm-push" trying to send a message to my app.
In my test.js (where i call the fcm.send function) i've got the "Invalid server response error".
Also, in the fcm.js , by printing on the console.log the data i've received, i read: "Invalid (legacy) Server-key delivered or Sender is not authorized to perform request" - Error 401.
What's going on?
I've tried all the keys i've found on Firebase Console Settings section and also the api Key i have in my google-services.json file.
Any help would be appreciated.
Thanks!
The following lines to copy the values to parse fcmOptions.agent into an object instead copying it.
//copying the fcmOptions object to avoid problems in parallel calls
var mFcmOptions = JSON.parse(JSON.stringify(self.fcmOptions));
workaround (but not really pretty)
var agent = self.fcmOptions.agent;
var mFcmOptions = JSON.parse(JSON.stringify(self.fcmOptions));
mFcmOptions.agent = agent;
How to send action buttons on notification like this http://i.stack.imgur.com/24I2x.png?
Using the mini example I get the following (when I also print out err)
Something has gone wrong! { [Error: getaddrinfo ENOTFOUND fcm.googleapis.com]
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'fcm.googleapis.com' }
I am behind a proxy and I suppose this information has to be given to "request" somehow
How to set "content-available": true property payload I'm want to receive notification when app is in background mode,used following link for same but don't know to set payload in fcm-push.https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#push-message-arrives-with-app-in-foreground
Hello every one i'm working with this package i have just question how can i use (badge,sound,alert,vibrate) ?
Thank you very much.
SyntaxError: Unexpected token =>
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object. (/Users/corozco/Documents/Grupo Ecodev/Proyectos/Mr. Quick/Aplication/Weiter/node_modules/fcm-push/index.js:1:80)
Can you helpme? please. hnks
i am unable to send multiple notification in single box as we do in Android...how to do "style":"inbox"?
I am using this module to send push notifications. Tried to send to a single device . everytime getting duplicated 2 messages. It was supposed to be delivered only one.
code:
`Alerts.pushmessage = function (cb) {
var serverKey = "abcd"; //put your server key here
var deviceToken = 'group_key'; // required
var FCM = require('fcm-node');
var message = { //this may vary according to the message type (single recipient, multicast, topic, et cetera)
to: deviceToken,
notification: {
title: 'Group 555 test'+ ((new Date()).getTime()),
body: 'Body of your push notification'
},
data: {
my_key: 'my value',
my_another_key: 'my another value'
}
};
fcm.send(message, function(err, response) {
console.log("sent");
if (err) {
console.log(err);
console.log("Something has gone wrong!");
cb(err);
} else {
console.log("Successfully sent with response: ", response);
cb(null, response);
}
});
};`
I can't send notification message with sound. So, how can i use? Thanks!
How to integrate to send notifications to ios devices?
Does registration token will work for both IOS/Android in the same way?
There are two variables anyFail
& anySuccess
which not declared but used in lib/fcm.js
(line 73-83). I found it is fixed in latest master branch but we are not able to get it via npm install since valid install targets are 1.1.0, 1.0.7, 1.0.6, 1.0.5, 1.0.3, 1.0.2, 1.0.1, 1.0.0
How can we install fcm-push 1.1.2 via npm install? Please find the fcm-push code below
`anyFail = ((JSON.parse(data)).failure > 0);
if (anyFail) {
error = data.substring(0).trim();
}
anySuccess = ((JSON.parse(data)).success > 0);
if (anySuccess) {
id = data.substring(0).trim();
}`
Can we send notification on multiple devices using multiple device tokens using single api call ? if yes then how ?
network error.
Here is what I have.
var FCM = require('fcm-push');
var serverKey = '...-6Zmw'; //i have a legit key here
var fcm = new FCM(serverKey);
var message = {
data: {
your_custom_data_key: 'your_custom_data_value'
},
condition:"'dogs' in topics || 'cats' in topics",
notification: {
title: 'Title of your push notification',
body: 'Body of your push notification'
}
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!");
console.log(err)
} else {
console.log("Successfully sent with response: ", response);
}
});
Every time i run this, it sends me an error, but on my client 4 messages come in.
Anything that may result in this?
{
"multicast_id": 7497838685051704056,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "NotRegistered"
}
]
}
it's show error.
return new Promise((resolve, reject) =>{
^
SyntaxError: Unexpected token >
Hi
How can I send the image in notification, I have tried to put a "image" key in notification object, but no success. plz help
What are the fields that needs to be filled out? It didnt work when I tried out/
TypeError: Agent option must be an Agent-like object, undefined, or false.
at new ClientRequest (_http_client.js:106:11)
at Object.request (http.js:38:10)
at Object.request (https.js:239:15)
at Object.request (D:\Projects\FCM_TEST\node_modules\https-proxy-agent\node_modules\agent-base\patch-core.js:23:20)
at RetryOperation._fn (D:\Projects\FCM_TEST\node_modules\fcm-push\lib\fcm.js:48:33)
at RetryOperation.attempt (D:\Projects\FCM_TEST\node_modules\fcm-push\node_modules\retry\lib\retry_operation.js:88:8)
I am currently using typescript and couldn't find typings for this library. Anyone know when it will be support/ has anyone created their own custom typings file.
Thanks
https://www.npmjs.com/package/fcm-push
still has 1.1.2
I'm initializing correctly with: var fcm = new FCM(mykeyhere);
That returns a pretty object that looks correct.
Later in the story, I do a:
var fcmMessage = {
to: [ channel ],
data: {
"content-available": 1,
attachment_id: idgoeshere,
},
notification: {
title: 'New attachment',
body: "Message goes here"
}
};
followed up by a:
fcm.send(fcmMessage, function(error, response){
if (error) {
return console.error("error while sending", channel, "push notification", error);
} else {
console.log("sent to fcm", channel, "with response", response);
}
});
The log shows that response is "sent to fcm channelhere with response null".
If the fcm object initializes correctly, and there is no error in the fcm.send callback, why is response null?
What is the disconnect?
Thanks.
From coffeescript console ------>
`coffee> fh = require('./helpers/fcm')
FCMPush {}
coffee> m = {"token":"dPiO7s50M8o:APA91bGH_B7FirN6Zvy1ZPBkYtDiYUCwjesPJ1fR12fHmeUsvRrc2v6JOqY9iJbpcOnuRH5hvsmmr6rXBZkWwWSWm5pWD61Gh-Atfqq_qg
7j6gF18UeedNAxI2crYMXTmkqKyQHO1slW","notification":{"title":"Chow","body":"Hey tap to see the yummy and wholesome food you just pic
ked!"},"data":{"blablubleeamount121212":100,"thisthatthoseitems":[{"name":"A","description":"asda sdad","price":"150","quantity":"2"},{"name":"B","de
scription":"asda sdad","price":"180","quantity":"3"}]}}
coffee> fh.send m, (e,r) -> console.log e,r
coffee> InvalidServerResponse undefined
For clarity, my object is ---->
{
"token": "dPiO7s50M8o:APA91bGH_B7FirN6Zvy1ZPBkYtDiYUCwjesPJ1fR12fHmeUsvRrc2v6JOqY9iJbpcOnuRH5hvsmmr6rXBZkWwWSWm5pWD61Gh-Atfqq_qg7j6gF18UeedNAxI2crYMXTmkqKyQHO1slW ",
"notification ": {
"title ": "Chow",
"body ": "Hey tap to see the yummy and wholesome food you just picked!"
},
"data ": {
"blablubleeamount121212 ": 100,
"thisthatthoseitems ": [{
"name ": "A ",
"description ": "asda sdad ",
"price ": "150 ",
"quantity ": "2 "
}, {
"name ": "B ",
"description ": "asda sdad ",
"price ": "180 ",
"quantity ": "3 "
}]
}
}
and in the fcmhelper --->
var FCM, FCMPush, serverKey;
FCM = require('fcm-push');
serverKey = 'MY_SERVER_KEY';
FCMPush = (function() {
function FCMPush() {}
FCMPush.prototype.send = function(message, callback) {
var fcm;
fcm = new FCM(serverKey);
return fcm.send(message, function(err, response) {
if (callback != null) {
return callback(err, response);
} else {
return console.log("FCM complete: ", err, response);
}
});
};
return FCMPush;
})();
Please help!
Update : Closing issue. It's been a long night - completely missed out the "token" for "to"
https://firebase.google.com/docs/cloud-messaging/android/device-group
This package currently implements device tokens and topics, any chance support for Device Group Messaging and notification_key can be added?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.