Search code examples
amazon-web-servicesaws-lambdaamazon-sns

Using AWS Lambda Console to send push using SNS


I tried every possible solution on the internet with no hope

What I am trying to do is simply use aws lambda functions (through the aws console) to fetch user fcm token from lets say DynamoDB (not included in the question), use that token to create endpointArn, send push to that specific device

I tested to send Using SNS console and the push gets to the device successfully but I failed to get it to the device using Lambda functions although it gives success status and message ID

Here is the code I used

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'us-east-1'});
const sns = new AWS.SNS()

const sampleMessage = {
    "GCM": { 
        "notification": { 
            "body": "Sample message for Android endpoints", 
            "title":"Title Test" 
        } 
    }
}



exports.handler = async (event) => {

    const snsPayload = JSON.stringify(sampleMessage);

    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    
    const params = {
        PlatformApplicationArn: '<Platform Arn>',
        Token: '<FCM Token>'
    };
    
     try {
        const endpointData = await sns.createPlatformEndpoint(params).promise();

        const paramsMessage = {
            Message: snsPayload,
            TargetArn: endpointData.EndpointArn
        };
        var publishTextPromise = await sns.publish(paramsMessage).promise();

        response.MessageId = publishTextPromise.MessageId;
        response.result = 'Success';
        
     }
     catch (e) {
         console.log(e.stack)
         response.result = 'Error'
     }
  

    return response;
};

Solution

  • After some trials and errors I figured out the solution for my own question

    1- The GCM part of the payload should be a string not a json 2- The message parameter should have an attribute that explicitly sets the mime type of the payload to Json

    Taking all that into consideration

     const GCM_data = { 
        'notification': { 
            'body': 'Hellow from lambda function', 
            'title': 'Notification Title' 
        } 
    }
    
    const data = {
        "GCM": JSON.stringify(GCM_data)
    }
    const snsPayload = JSON.stringify(data)
    

    and the params should look like

    const paramsMessage = {
            Message: snsPayload,
            TargetArn: endpointData.EndpointArn,
            MessageStructure: 'json'
        };
    

    and this will work :)