How to implement APNS notifications through nodejs

2019-03-30 09:35发布

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);

0条回答
登录 后发表回答