I am using node-xcs module to create XMPP CCS server in NodeJs, But in that module there is no method to send ACK message which is required to send back to FCM.
do you use fcm-node package for get FCM token . using that we can register device look at my full coding i have use it for send notification to mobile
var FCM = require('fcm-node');
exports.SendNotification = function(msg,title,type,id,user_id,api_token)
{
var fcm = new FCM(constants.serverKey);
var message = {
registration_ids : api_token,
notification: {
title: title,
body:msg
},
data: {
type: type,
id:id,
user_id:user_id
}
};
fcm.send(message, function(err, response){
if (err)
{
console.log("Error for Send Notification",err);
return;
}
else
{
console.log("Successfully sent Notification", response);
return;
}
});
}
and than call this function like this
msg='new notification for you'
title='Hello'
id='34'
user_id='34'
result='api_token'//save this token in database and retrive using user_id
SendNotification(msg,title,'START_APPOINTMENT',id,user_id,result);
Related
I'm trying to send notifications to my android app.
I have a NodeJS backend with Firesbase as my DB and my client is an Android app.
This is my observer on my NodeJS:
var observer = db.collection(‘bookings’)
.onSnapshot(querySnapshot => {
querySnapshot.docChanges.forEach(change => {
if (change.type === ‘added’) {
// This registration token comes from the client FCM SDKs.
var registrationToken = ‘YOUR_REGISTRATION_TOKEN’; //can't find this
// See documentation on defining a message payload.
var message = {
data: {
score: ‘850’,
time: ‘2:45’
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
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:’, error);
});
console.log(‘New booking: ’, change.doc.data());
}
else if (change.type === ‘modified’) {
console.log(‘Modified booking: ’, change.doc.data());
}
else if (change.type === ‘removed’) {
console.log(‘Removed booking: ’, change.doc.data());
}
});
});
I am unable to figured out how to persist the FirebaseInstanceID Token somewhere in the server or DB?
Here is the situation: I have a firebase cloud function that is running on every write to a certain database collection (called "jamrooms"). The NodeJS script is as follows:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.newJamroom = functions.database.ref('/jamrooms/{jamroomId}').onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
var jamroomId = event.params.jamroomId;
var topic = "new-jamroom";
var payload = {
data: {
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
On the client side (Android), I've subscribed to the topic "new-jamroom":
FirebaseMessaging.getInstance().subscribeToTopic("new-jamroom");
The script is successfully executed each time a new key-value pair is added to the collection:
but the client never receives the notification, either in background or in foreground.
I don't know where to look at to understand what's not going right.
Update
Even sending notifications from the console (using topic "new-jamroom", that exists in the console) doesn't send it to the client (Firebase records 0 sent).
Because your payload contains the data key, you are sending a data-only message, not a notification:
var payload = {
data: {
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
Data messages and notification messages are handled differently by the receiver. Data-only messages cause onMessageReceived() to be invoked in the receiver. To generate a notification, build your payload with the notification key:
var payload = {
notification: { // <= CHANGED
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
I am trying to make a cloud function that sends a push notification to a given user.
The user makes some changes and the data is added/updated under a node in firebase database (The node represents an user id). Here i want to trigger a function that sends a push notification to the user.
I have the following structure for the users in DB.
Users
- UID
- - email
- - token
- UID
- - email
- - token
Until now i have this function:
exports.sendNewTripNotification = functions.database.ref('/{uid}/shared_trips/').onWrite(event=>{
const uuid = event.params.uid;
console.log('User to send notification', uuid);
var ref = admin.database().ref('Users/{uuid}');
ref.on("value", function(snapshot){
console.log("Val = " + snapshot.val());
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
When i get the callback, the snapshot.val() returns null. Any idea how to solve this? And maybe how to send the push notification afterwards?
I managed to make this work. Here is the code that sends a notification using Cloud Functions that worked for me.
exports.sendNewTripNotification = functions.database.ref('/{uid}/shared_trips/').onWrite(event=>{
const uuid = event.params.uid;
console.log('User to send notification', uuid);
var ref = admin.database().ref(`Users/${uuid}/token`);
return ref.once("value", function(snapshot){
const payload = {
notification: {
title: 'You have been invited to a trip.',
body: 'Tap here to check it out!'
}
};
admin.messaging().sendToDevice(snapshot.val(), payload)
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
})
Just answering the question from Jerin A Mathews...
Send message using Topics:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//Now we're going to create a function that listens to when a 'Notifications' node changes and send a notificcation
//to all devices subscribed to a topic
exports.sendNotification = functions.database.ref("Notifications/{uid}")
.onWrite(event => {
//This will be the notification model that we push to firebase
var request = event.data.val();
var payload = {
data:{
username: request.username,
imageUrl: request.imageUrl,
email: request.email,
uid: request.uid,
text: request.text
}
};
//The topic variable can be anything from a username, to a uid
//I find this approach much better than using the refresh token
//as you can subscribe to someone's phone number, username, or some other unique identifier
//to communicate between
//Now let's move onto the code, but before that, let's push this to firebase
admin.messaging().sendToTopic(request.topic, payload)
.then((response) => {
console.log("Successfully sent message: ", response);
return true;
})
.catch((error) => {
console.log("Error sending message: ", error);
return false;
})
})
//And this is it for building notifications to multiple devices from or to one.
Return this function call.
return ref.on("value", function(snapshot){
console.log("Val = " + snapshot.val());
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
This will keep the cloud function alive until the request is complete. Learn more about returning promises form the link give by Doug in the comment.
Send Notification for a Topic In Cloud function
Topics a basically groups you can send notification for the selected group
var topic = 'NOTIFICATION_TOPIC';
const payload = {
notification: {
title: 'Send through Topic',
body: 'Tap here to check it out!'
}
};
admin.messaging().sendToTopic(topic,payload);
You can register the device for any new or existing topic from mobile side
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotificationToTopic =
functions.firestore.document('Users/{uuid}').onWrite(async (event) => {
//let title = event.after.get('item_name');
//let content = event.after.get('cust_name');
var message = {
notification: {
title: "TGC - New Order Recieved",
body: "A New Order Recieved on TGC App",
},
topic: 'orders_comming',
};
let response = await admin.messaging().send(message);
console.log(response);
});
For sending notifications to a topic, The above code works well for me, if you have any doubt, let me know.
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.
I have setup a Mobile Service in Azure and connected it to my Android app. Through this app I am calling the Azure API to insert an object into a database table linked to the mobile service.
I have written the script that is executed before it gets inserted. That script is intended to send a push notification to another device.
Now the case is, the object gets inserted into table but no push notification is received. What could be wrong? How can i debug?
Here's my insert script:
function insert(item, user, request) {
var devices = tables.getTable('Devices');
var receiverHandle;
devices.where({userId: item.receiver}).read({
success: populateHandle
});
request.execute({
success: function() {
// Write to the response and then send the notification in the background
request.respond();
console.log(item);
push.gcm.send(item.handle, item, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
});
function populateHandle(results){
receiverHandle = results[0].handle;
}
}
Although logs state successful delivery of push notification. I am not receiving it on my device.
Here is one of the logs:
Push notification sent: { isSuccessful: true, statusCode: 201, body: '', headers: { 'transfer-encoding': 'chunked', 'content-type': 'application/xml; charset=utf-8', server: 'Microsoft-HTTPAPI/2.0', date: 'Sun, 10 Aug 2014 15:01:52 GMT' }, md5: undefined }
Refer to Migrate a Mobile Service to use Notification Hubs.
Microsoft had been upgraded the Mobile Service, to push notifications powered by Notification Hubs. You will not be affected if you created the mobile service before the upgrade.
Base on the response { isSuccessful: true, statusCode: 201, body ... }, it indicate that your Mobile Service is the new version.
If you prefer to send push without Notification Hubs, don't use push.gcm.send, use the following code snippet instead.
var legacyGcm = require('dpush');
legacyGcm.send(your_GCM_APIKEY, regId, item, function (error, response) {
if (!error) {
// success code
} else {
// error handling
}
});