Anyone using Node.js with Amazon SNS and Apple Push Notifications?

CargoMeister picture CargoMeister · Feb 6, 2014 · Viewed 11.5k times · Source

I'm looking for examples of using node.js with Amazon SNS and Apple APN push notifications. We use Amazon for our hosting, and I have used SNS before, it's pretty simple. But the examples they have for push notifications are for java, and there is no examples for Node. It's confusing, as usual with them, and I'm hoping to cut my research and time spent short. It can't be that hard. I'm also wondering how they deal with errors, and the differences between the sandbox and production. Apple reacts differently between the two environments, not failing in the sandbox as they do in production.

Answer

CargoMeister picture CargoMeister · Feb 7, 2014

It ends up not being that hard, just figuring out the documentation was unpleasant. You need to create the main endpoint for the SNS topic in the console, by far the easiest way, including the loading of the certificate. You then used createPlatformEnpoint to create an endpoint for each device id. That returns another SNS topic, specific fo that device, that you then use to send the message.

So, the following works to send a single message to a single client. If you want send something en masse, not sure you can do that. Also not sure how you deal with Apple's feedback, which you are supposed to check for failed sends.

config = require("./config.js").config;

var token = "1234567898123456789";

var AWS = require('aws-sdk');

AWS.config.update({accessKeyId: config.AWSAccessKeyId, secretAccessKey: config.AWSSecretKey});
AWS.config.update({region: config.AWSRegion});

var sns = new AWS.SNS();

var params = {'PlatformApplicationArn':config["AWSTargetARN"],'Token':token};

var message = 'Test';
var subject = 'Stuff';

sns.createPlatformEndpoint(params,function(err,EndPointResult)
{
    var client_arn = EndPointResult["EndpointArn"];

    sns.publish({
    TargetArn: client_arn,
    Message: message,
    Subject: subject},
        function(err,data){
        if (err)
        {
            console.log("Error sending a message "+err);
        }
        else
        {
            console.log("Sent message: "+data.MessageId);

        }
    });
});