Naresh Kumar
Naresh Kumar

Reputation: 276

AMAZON SNS Push notification payload to android mobile using Node js

Implementation of Amazon SNS push notification to android device using aws-sdk package in NodeJS. I have few implementations mentioned below. Mobile device is displaying push notifications. I want to send data and notification object in payload.

let payload2 = JSON.stringify({
  default: 'Naresh',
  GCM:  JSON.stringify({
    notification : {
      body : 'great match!',
      title : 'Portugal vs. Denmark'       
    },
    data:{
      testdata: 'Check out these awesome deals!',
      url: 'www.amazon.com'
    }
  })
});

It's not sending push notifications.

let payload1 = {
  "GCM": "{
    \"notification\": {
      \"title\": \"this one last test in app\", 
      \"body\": \"mm hello tests\"
    },
    \"data\": {
      \"turnclass\": \"efwfwe\",
      \"flight\": \"truejet\"}
  }"
};

It's sending push notifications.

sns.publish({ TargetArn: targetArn,
  Message: payload1,
  MessageStructure: 'json'
}, (error, data) => (error) ? reject(error) : resolve(data));

What is right format to send push notifications?

Upvotes: 0

Views: 2595

Answers (1)

Damaged Organic
Damaged Organic

Reputation: 8467

According to documentation:

When sending platform-specific payloads in messages using the Amazon SNS console, the data must be key-value pair strings and formatted as JSON with quotation marks escaped.

Example:

{
   "GCM":"{
      "data":{
         "message":"Check out these awesome deals!",
         "url":"www.amazon.com"
      }
   }"
}

What you are doing in the first payload produces the following output:

{"default":"Naresh","GCM":"{\"notification\":{\"body\":\"great match!\",\"title\":\"Portugal vs. Denmark\"},\"data\":{\"testdata\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com\"}}"}

And that is not a valid format. That happens because you're double JSON.stringify a part of your object. So if you do:

let payload2 = JSON.stringify({
  default: 'Naresh',
  GCM: {
    notification: {
      body: 'great match!',
      title: 'Portugal vs. Denmark'
    },
    data: {
      testdata: 'Check out these awesome deals!',
      url: 'www.amazon.com'
    }
  }
});

It will produce:

{"default":"Naresh","GCM":{"notification":{"body":"great match!","title":"Portugal vs. Denmark"},"data":{"testdata":"Check out these awesome deals!","url":"www.amazon.com"}}}

Which should work as expected.

Upvotes: 2

Related Questions