How to implement APNS notifications through nodejs?

岁酱吖の 提交于 2019-12-12 08:15:04

问题


Does someone now a good npm module to implement Apple PUSH notifications? A simple example would be great.

The solution I've found is the following which uses the apn module.

var apn = require('apn');

var ca = ['entrust_2048_ca.cer'];

/* Connection Options */
var options = {
        cert: 'path to yuour cert.pem',
        key: 'path to your key.pem',
        ca: ca,
        passphrase: 'your passphrase',
        production: true,
        connectionTimeout: 10000
};

var apnConnection = new apn.Connection(options);


/* Device */
var deviceToken = 'your device token';    
var myDevice = new apn.Device(deviceToken);

/* Notification */
var note = new apn.Notification();

note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
note.payload = {'message': 'hi there'};

apnConnection.pushNotification(note, myDevice);

If you need to use the APNS feedback service to avoid to send notifications to devices which cannot receive it (application uninstalled) you can add the following:

/* Feedback Options */
var feedbackOptions = {
        cert: 'path to yuour cert.pem',
        key: 'path to your key.pem',
        ca: ca,
        passphrase: 'your passphrase',
        production: true,
        interval: 10
};

var feedback = new apn.feedback(feedbackOptions);

feedback.on('feedback', handleFeedback);
feedback.on('feedbackError', console.error);

function handleFeedback(feedbackData) {
    var time, device;
    for(var i in feedbackData) {
        time = feedbackData[i].time;
        device = feedbackData[i].device;

        console.log("Device: " + device.toString('hex') + " has been unreachable, since: " + time);
    }
}

To handle the different events connected to the connection you can use the following:

apnConnection.on('connected', function(openSockets) {
  //
});

apnConnection.on('error', function(error) {
  //
});

apnConnection.on('transmitted', function(notification, device) {
  //
});

apnConnection.on('transmissionError', function(errCode, notification, device) {
  //
});

apnConnection.on('drain', function () {
  //
});

apnConnection.on('timeout', function () {
  //
});

apnConnection.on('disconnected', function(openSockets) {
  //
});

apnConnection.on('socketError', console.error);

来源:https://stackoverflow.com/questions/26590109/how-to-implement-apns-notifications-through-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!