Send Push Notification using Node Js


send push notifications to their corresponding iOS and Android devices using the apn and node-gcm-service node modules.

apn = require('apn');
gcm = require('node-gcm-service');

For ios, assuming we have our cert.pem and key.pem files generated from the APNS certificate at root level in our project folder, use  device ID  to create our apn connection instance.

function IosPush(deviceid, message) {
var apnConnection = new apn.Connection({ production: false });
var apnDevice = new apn.Device(deviceid);

var apnNotification = new apn.Notification(); apnNotification.alert = message; apnNotification.badge = 0;
apnNotification.contentAvailable = true;

apnNotification.sound = "ping.aiff";
apnNotification.pushNotification(apnNotification, apnDevice);
}



Above we set the message that the user will see when receiving the push and an optional badge number that will appear on the app icon.

For Android make sure you have your API key from the Google Developers Console.


function AndroidPush(deviceID, msg) { var message = new gcm.Message({ data: { title: "Your App Name" , msg: msg } , delay_while_idle: false , dry_run: false }); var sender = new gcm.Sender();
sender.setAPIKey('Your Api Key'); sender.sendMessage(message.toString(), deviceID, true,
function (err, data) {
if (err) { console.log("error", err) } else { console.log(data); } }); }

Note:  To Generate Key.pem and cert.pem  goto your key.p12 file path in terminal  and Run below command in terminal
 openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days XXX

Comments

Popular posts from this blog

How To Migrate MVC 3 Application To MVC 5

Private Chat Using Node js and socket.io with encrypt and decrypt message and insert into mongo db

Populate a drop-down in Vue.js and Asp.net Core from an ajax call