How to send push notifications using AWS SNS service to android in NODE JS

2

I am using AWS SNS service to send notifications to mobile app. I have created a Platform Application, and then added an Application Endpoint based on the device token which I generated through FCM (for android). Now, I am trying to send a push notification to the that device (application endpoint). I tried to publish via AWS SNS console and it worked. My aws-sdk version is V3.

Now, I want to do it using Node JS. Following is the code:

File notifications.js:

const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

// Set the AWS region
const region = process.env.AWS_SNS_REGION";
// Create SNS service object
const sns = new SNSClient({ region });

async function sendPushNotification(sns, params) {
    return await sns.send(new PublishCommand(params));
}

/**
 * Function to publish a push notification to specific user
 * @param {*} message
 * @param {*} endpointARN
 */
async function PublishPushNotification(message, endpointARN) {
    // format message
    message = formatMessage(message?.title, message?.body);
    console.log(message);
    try {
        // Set params
        const publishParams = {
            Message: message,
            TargetArn: endpointARN,
        };
        // Send push notification
        const publishData = await sendPushNotification(sns, publishParams);
        console.log("MessageId is " + publishData.MessageId);
        console.log(publishData);
    } catch (err) {
        console.error(err, err.stack);
    }
}

function formatMessage(title, body) {
    const payload = {
        GCM: JSON.stringify({
            notification: {
                title,
                body,
            },
        }),
    };
    return JSON.stringify(payload);
}

module.exports = {
    PublishPushNotification,
};

Calling PublishPushNotification in index.js file.

File index.js

const message = {
  title: "BeeMobile",
  body: "Sample message for Android endpoints"
}

const targetArn = process.env.TARGET_ARN;

PublishPushNotification(message, targetArn);

It is giving following response:

{
  '$metadata': {
    httpStatusCode: 200,
    requestId: '72aef46b-22e4-5555-a55d-a85163cd1111',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  MessageId: '11224caa-7ab5-57de-9aa5-10514b9c80xr'
}

But I am not getting notification on my android device. (When I direct publish through AWS SNS GUI console, it shows the notification)

Can you please let me know where I am making the mistakes?

2 Answers
1
Accepted Answer

Hello,

I suggest checking that everything is in place first.

  1. Make that the ARN being used for the last point has the most up-to-date and correct token for the device. Tokens may stop functioning if the software is uninstalled, reinstalled, or the cache memory is cleaned.
  2. The FCM frequently doesn't automatically display a notification when its application is in the foreground. The application will receive the notification's data instead, and it is up to it to manage it in the code. As a result, try sending the notification while the application is shut down completely or running in the background.
  3. WS SNS requires a certain message format for some systems. In this case, it is acceptable to use the key "GCM" for your useful data, but make sure your JSON format is valid and complies with the requirements of the FCM HTTP v1 API:

https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages

And it should looks like:

{
  GCM: JSON.stringify({
    data: {
      title: "Your title",
      body: "Your message",
    },
  }),
}
  1. To properly process your custom payload while delivering push notifications, you might need to set the message structure property to "json".

You can update the "publishParams" like:

const publishParams = {
    Message: message,
    MessageStructure: 'json',
    TargetArn: endpointARN,
};
  1. Check that your Android manifest file has essential permissions enabled. You must have the 'com.google.android.c2dm.permission' permission. Request permission. Make sure the server key in your Firebase Cloud Messaging configuration and the SNS platform app (in the AWS console) match.

You can also look into CloudWatch logs for any related error messages or issues.

AWS
e_mora
answered a year ago
  • Thank you for the detailed response. Really appreciate that. I have verified everything, the only issue was that I was not specifying the MessageStructure in publishParams. Is this something mentioned in AWS SNS documentation?

1

Hey, good to hear that you've solved the issue!

Yes, the “MessageStructure” parameter is mentioned in the AWS SNS documentation. In the “Publish” request parameters, you'll find the “MessageStructure” parameter. The “MessageStructure” parameter must be set to “json” if distinct messages are being sent for each protocol.

The top-level JSON keys for the JSON object may be any or all of the following: “default”, “email”, “sqs", “lambda”, “http”, “https”, “sms", "APNS", "APNS_SANDBOX", "APNS_VOIP", "APNS_VOIP_SANDBOX", "MACOS", "MACOS_SANDBOX", "GCM", "ADM", "BAIDU", "WNS", "MPNS", and "FCM".

You can send a separate message for each protocol when you set the "MessageStructure" property to "json". In your case, setting it to "json" allows you to specifically format your message for GCM/FCM.

Publish – Amazon Simple Notification Service:

https://docs.aws.amazon.com/sns/latest/api/API_Publish.html

AWS
e_mora
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions