Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send SMS programmatically using Amazon Amplify SDK for my Android app users?

I want to send a welcome message (SMS) to phone number of my app's user when they will sign up using their phone number. I couldn't find official documentation for this particular task.

like image 230
Ssubrat Rrudra Avatar asked Sep 03 '25 04:09

Ssubrat Rrudra


2 Answers

Amazon lets you do this. Assuming you're using Cognito for sign-up, you'll want to use the post-confirmation Cognito lambda trigger.

  1. Set up your SNS account via the AWS Console, to send SMS messages. Send yourself a test message via the console.

  2. Run amplify auth update

  3. When it gets to the question Do you want to configure Lambda Triggers for Cognito?, answer Yes and choose the Post Confirmation trigger

  4. You need to grant SNS (SMS) permissions to the lambda. Update the PostConfirmation-cloudformation-template.json file to add a new statement under Resources.lambdaexecutionpolicy.Properties.PolicyDocument.Statement:

    {
    "Resources": {
        "lambdaexecutionpolicy": {
            "Properties": {
                "PolicyDocument": {
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "sns:*",
                            "Resource": "*"
                        }
                    ]
                    ...
                }
            ...
            }
        ...
        }  
    ...
    }
    ...
    }
    
  5. Use this code for the trigger:

    var aws = require('aws-sdk');
    
    var sms = new aws.SNS();
    
    exports.handler = (event, context, callback) => {
      console.log(event);
    
      if (event.request.userAttributes.phone_number) {
        sendSMS(event.request.userAttributes.phone_number, "Congratulations " + event.userName + ", you have been confirmed: ", function (status) {
    
          // Return to Amazon Cognito
          callback(null, event);
        });
      } else {
        // Nothing to do, the user's phone number is unknown
        callback(null, event);
      }
    };
    
    function sendSMS(to, message, completedCallback) {
      const params = {
        Message: message, /* required */
        PhoneNumber: to
      };
      sns.publish(params, function (err, data) {
        if (err) {
          console.log(err, err.stack); // an error occurred
        } else {
          console.log(data);
        }
        completedCallback("SMS Sent");
      })
    };
    
like image 71
cobberboy Avatar answered Sep 05 '25 00:09

cobberboy


Not sure if sending SMS is a service, Amazon Amplify provides.

But you could use a service like Twilio to send SMS (and much more) to phones.

like image 45
Markus Strobl Avatar answered Sep 04 '25 23:09

Markus Strobl