What are the procedures to follow in using GCM for a node based application?
Are there specific codes required on both server side(Node js) and client side(Android/iOS)?
Android device should sent a device token to the server to be able to receive notifications. Here an example how to do it.
Get gcm key to send pushes from server.
Send push with node-gcm package from npm with node.js app.
Basic example:
const gcm = require('node-gcm'); //Google Cloud Messaging
const gcmKey = ''; // Your gcm key in quotes
const deviceToken = ''; // Receiver device token
const sender = new gcm.Sender(gcmKey);
var message = new gcm.Message();
message.addData({
title: 'Push',
body: 'This is push notification',
otherProperty: true,
});
sender.send(message, {registrationIds: [token]}, (err) => {
if (err) {
console.error(err);
}
else {
console.log('Sent');
}
});
Related
I want to know wether it is possible to send push notification using firebase cloud messaging and node.js server? How can I do this?
Yes, It is possible using either API endpoints provided by firebase or by using firebase-admin npm package.
Minimal Example -
const firebaseAdmin = require('firebase-admin')
if (!firebaseAdmin.apps.length) {
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccountJson),
databaseURL: databaseUrl
})
}
// This registration token comes from the client FCM SDKs.
const registrationToken = 'YOUR_REGISTRATION_TOKEN';
const message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
firebaseAdmin.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);
});
For further documentation please refer to -
https://firebase.google.com/docs/cloud-messaging/send-message
I am trying to use firebase cloud messaging to deploy a http push notifications onto an actual device. When so, I am getting the error
"The credential used to authenticate this SDK does not have permission to send messages to the device corresponding to the provided registration token. Make sure the credential and registration token both belong to the same Firebase project."
I have checked the credentials on both the frontEnd and backEnd side and they all match up with my firebase correctly. I have tried to follow plenty of examples on here and I have missed on all of them. My node.js file looks like
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
export GOOGLE_APPLICATION_CREDENTIALS = "/Users/myname/mylocation/myfile.json"
exports.sendPushNotifications = functions.https.onRequest((req, res) => {
res.send("Attempting to send push notification")
console.log("LOGGER --- Trying to send push message..");
var uid = 'randomUIDString'
var fcmToken = 'myToken'
return admin.database().ref('/users/' + uid).once('value', snapshot => {
var user = snapshot.val();
console.log("username is " + user.name);
var payload = {
notification: {
title: 'Push Notification Title',
body: 'Test Notification Message'
}
}
admin.messaging().sendToDevice(fcmToken, payload)
.then(function(response) {
console.log('Succesfully sent message:', response);
console.log(response.results[0].error);
})
.catch(function(error) {
console.log('Error sending message', error);
});
})
})
The users name prints from calling the uid, but I am having trouble accessing the fcmToken.
I have checked my info.plist and the correct project is listed. Same with apple developer and appDelegate. is there something more that I am missing??
I try to find simple client-server app using Firebase Cloud Messaging.
I use Nodejs and this package, but I don't know how and where I can find the client token?
Here the example code:
var fcm = require('fcm-notification');
var FCM = new fcm('path/to/privatekey.json');
var token = 'token here';
var message = {
data: { //This is only optional, you can send any data
score: '850',
time: '2:45'
},
notification:{
title : 'Title of notification',
body : 'Body of notification'
},
token : token
};
FCM.send(message, function(err, response) {
if(err){
console.log('error found', err);
}else {
console.log('response here', response);
}
})
Usually, the person is on the website / app and the client code asks for permission to send notifications. If granted, the client then calls the FCM server to get a token that represents that person.
The client code then saves that token to a database with the person's id.
Then when sending the message your server side software reads the token from the database.
(I hope that is the answer to your question.)
I'm using Admin SDK for node.js for sending the push notifications. Followed the tutorial and initialized the multiple projects with like examples given with this link.
I need to know how to send push notifications with two projects using with node.js. Used below methods for sending notifications two projects based its working with default project but another project getting error like below
exports.send_test_mailer = function(req, res) {
// Default project
var registrationToken = ["f-vRsDouUFQ:APA91bGktVzu3WjKGqeXqdiYPI8B0lQXs34TkJS4p7LaMiFGfp5LdfB1ZjEhO3CY5ci92apqgt1hEJY0ml11C4hxYUaPfDl7PeDHhcmDGur0JUx5l3M2mLEj30epwRBWVsE4xMSTls4f"];
var payload = {
notification: {
title: "driver app",
body: "driver app push notfications on the day."
},
data: {
score: "850",
time: "2:45"
}
};
firebaseAdmin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
console.log("Successfully sent message driver:", JSON.stringify(response));
})
.catch(function(error) {
console.log("Error sending message driver:", JSON.stringify(error));
});
// Second project
var registrationTokens = ["dzXRXUMIB5w:APA91bHSArtroO8M33IHxaslQTugTcEzJcfkbsXEhwbXbvVzBws-aqG4aqKNr37j8WpZev7lolX7cFQlAKYZ1QV_EgC6zTGeT41n3lvSpcDyBg6t4SZZaoPe7nUO9sbdcXA2KDguxAbk"];
var payloads = {
notification: {
title: "customer app",
body: "customer app push notfications on the day."
},
data: {
score: "850",
time: "2:45"
}
};
firebaseAdmin.messaging().sendToDevice(registrationTokens, payloads)
.then(function(response) {
console.log("Successfully sent message customer:", JSON.stringify(response));
})
.catch(function(error) {
console.log("Error sending message customer:", JSON.stringify(error));
});
};
Error
{"results":[{"error":{"code":"messaging/registration-token-not-registered","message":"The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages."}},{"error":{"code":"messaging/mismatched-credential","message":"The credential used to authenticate this SDK does not have permission to send messages to the device corresponding to the provided registration token. Make sure the credential and registration token both belong to the same Firebase project."}}],"canonicalRegistrationTokenCount":0,"failureCount":2,"successCount":0,"multicastId":9014981858701063000}
Here is my answer
var ServiceAccount = require("./path your default app file.json");
var ServiceAccount1 = require("./path your second app file.json");
var serviceAppConfig = {
credential: firebaseAdmin.credential.cert(ServiceAccount),
databaseURL: "https://your firebase default app url"
};
// Initialize the default app
var serviceApp = firebaseAdmin.initializeApp(serviceAppConfig);
//console.log(serviceApp.name); // "[DEFAULT]"
// Retrieve services via the defaultApp variable...
var serviceAuth = serviceApp.auth();
var serviceDatabase = serviceApp.database();
// Get the Messaging service for the default app
global.serviceMessaging = firebaseAdmin.messaging();
var service1AppConfig = {
credential: firebaseAdmin.credential.cert(ServiceAccount1),
databaseURL: "https://your firebase url second app"
};
// Initialize another app with a different config
var service1App = firebaseAdmin.initializeApp(service1AppConfig, "App2 name");
// Use the otherApp variable to retrieve the other app's services
var service1Auth = service1App.auth();
var service1Database = service1App.database();
// Get the Messaging service for a given app
global.service1Messaging = firebaseAdmin.messaging(service1App);
Which is the right plugin to be used for Azure notification hub, for ionic app?
There are many plugins for push notification in Phonegap/Cordova and some of them are already deprecated.
Please provide some reference links for code snippets of ionic client side implementation Azure notification hub, and node.js server side implementation for the same.
In my test Ionic project, I used Mobile Services plug-in repository at https://github.com/Azure/azure-mobile-services-cordova.git and PushPlugin at https://github.com/phonegap-build/PushPlugin.git .
Here is the code snippet integrating GCM:
Initial mobile service client and GCM configurations:
/****
Mobile service configs
****/
var mobileServiceClient;
var mobileServiceUrl = 'https://<your_mobile_service_name>.azure-mobile.net/';
var mobileSerivceKey = '<your service key>';
/****
Notification hubs configs
*****/
var GCM_SENDER_ID = 'gcm_sender_id_number'; // Replace with your own ID.
var androidConfig = {
"senderID": GCM_SENDER_ID,
};
Configure GCM and Azure notification hub in app configuration of angular module:
angular.module('myapp', ['ionic','ngCordova'])
.run(function($ionicPlatform,$rootScope,$cordovaPush) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
//init mobileServiceClient
mobileServiceClient = new WindowsAzure.MobileServiceClient(mobileServiceUrl,mobileSerivceKey);
//register notification push
console.log("======mobileServiceClient inited going on ======");
$cordovaPush.register(androidConfig).then(function(result) {
// Success
console.log("=============register finished========");
}, function(err) {
// Error
})
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
$rootScope.GCM_status = true;
alert('registration ID = ' + notification.regid);
//register to Azure Mobile Service
if (mobileServiceClient) {
// Template registration.
var template = '{ "data" : {"message":"$(message)"}}';
// Register for notifications.
mobileServiceClient.push.gcm.registerTemplate(notification.regid,
"myTemplate", template, null)
.done(function () {
$rootScope.Azure_Push_status = true;
alert('Registered template with Azure!');
});
// .fail(function (error) {
// alert('Failed registering with Azure: ' + error);
// });
}
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
// WARNING: dangerous to unregister (results in loss of tokenID)
$cordovaPush.unregister().then(function(result) {
// Success!
}, function(err) {
// Error
})
});
})
Please refer to Microsoft Azure : Push Notifications to Cordova Apps with Microsoft Azure for more information about integrating Azure notification hub in Cordova apps.