How to send SMS using Amazon SNS from a AWS lambda function

时间秒杀一切 提交于 2021-01-01 06:14:18

问题


Amazon SNS provides a facility to send SMS globally.

I want to send SMS from a Lambda function were we provide the mobile number and text message and use SNS to deliver that message but I didn't find a helpful documentation or example code for NodeJS or java.

Can any one suggest a solution?

Code:

  var params = {
  Message: 'Hi this is message from AWS_SNS', /* required */
  MessageAttributes: {
    someKey: {
      DataType: 'String' ,
      StringValue: 'String'
    },
      },
  MessageStructure: 'String',
  PhoneNumber: '+91MyNUMBER',
  Subject: 'MYSubject',
  //TargetArn: 'arn:aws:sns:us-west-2:798298080689:SMS',
  //TopicArn: 'arn:aws:sqs:us-west-2:798298080689:SendSMS'
};
sns.publish(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});
};

回答1:


So, you need to write Lambda function which is invoked somehow, let's say via HTTP request so you'll also need to setup API Gateway to route connections to your Lambda function.

Next, your Lambda function will push that data to "SNS Topic" while SMS Subscription will "poll" for any new data in this "Topic". As soon as any data gets into this topic, it will be consumed by subscription and SMS will be sent.

Few days ago I wrote a post about SNS & Lambda which might help you. Flow you wanted to achieve is pretty similar to one described in this article.

https://medium.com/@rafalwilinski/use-aws-lambda-sns-and-node-js-to-automatically-deploy-your-static-site-from-github-to-s3-9e0987a073ec#.3x6wbrz91

Documentation pages that might help:

  • Pushing to SNS: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#publish-property
  • Subscribing to SNS: http://docs.aws.amazon.com/sns/latest/dg/SubscribeTopic.html



回答2:


Please try with setting the region explicitly to "us-east-1". I managed to send SMS to India by explicitly setting this region. I also tried with "ap-south-1", but was not successful.




回答3:


Based on latest AWS SNS > SMS documenration, When you don't have any topicArn and you need to send a text message directly to a phone number, you need to send following params:

const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-west-1'});
const sns = new AWS.SNS();

const publish = (phone, text, subject) => {
 
// Create publish parameters
var params = {
  Message: text,
  Subject: subject,
  PhoneNumber: phone,
  MessageAttributes: {
        'AWS.SNS.SMS.SMSType' : {
          DataType : 'String',
          StringValue: 'Transactional'
        },
      },
};

console.log('------------- text message param before sending------------');
console.log(params);
console.log('----------------------------------------------------');
    
// Create promise and SNS service object
var publishTextPromise = sns.publish(params).promise();

// Handle promise's fulfilled/rejected states
publishTextPromise.then(
  function(data) {
    console.log("MessageID is " + data.MessageId);
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });

}

exports.publish = publish;



回答4:


Here is a link to a tutorial for building an Alexa skill that connects with AWS SNS to send a text message.




回答5:


It works fine if can make sure you have the right access to publish to SNS.

const smsParams = ()=>({
        Message: getUpdateMessage(order),
        PhoneNumber: `+91${order.contactNo}`,
        MessageAttributes: {
            'AWS.SNS.SMS.SMSType' : {
                DataType : 'String',
                StringValue: 'Transactional'
            },
        },
    })

Permissions to my lambda:

- Effect: 'Allow'
      Action:
        - "sns:Publish"
      Resource:
        - '*'

Note that you have to allow all the resources to send SMS using PhoneNumber

Here is a link to all the supported SNS regions




回答6:


Here's what I did

  1. Create a new Lambda function Author from scratch with your Runtime of choice. (I went to latest, Node.js 12.x)

  2. For execution role, choose Create a new role from AWS policy templates.

  3. Type in your Role name and because you want to send SMS to any mobile number, you must set Resource to *.

  4. Type this as your IAM Role Template.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "sns:Publish"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
  1. Use this code snippet
const AWS = require('aws-sdk');
const SNS = new AWS.SNS();

exports.handler = async (event) => {
    let params = {
        PhoneNumber: '+123xxxxxxx',
        Message: 'You are receiving this from AWS Lambda'
    };

    return new Promise((resolve, reject) => {
        SNS.publish(params, function(err, data) {
            if(err) {
                reject(err);
            }
            else {
                resolve(data);
            }
        })
    })
}
  1. That's all. Click Deploy then Test and you should receive an SMS.


来源:https://stackoverflow.com/questions/38588923/how-to-send-sms-using-amazon-sns-from-a-aws-lambda-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!