A2P Two-way SMS using Amazon AWS SDK and NodeJS

Did you ever wonder how companies send SMS to all their customers at once, or how you get an instant autogenerated reply when you send something? This blog will explore how it works and how to implement A2P two-way SMS using Amazon AWS services!

What is A2P?

A2P SMS, or application-to-person SMS, delivers text messages from business applications to individual mobile subscribers. A2P SMS messages can be from order confirmations and appointment reminders to notifications about account balances and outages. Given their high open rates—90 percent versus 20 to 40 percent for email—A2P SMS messages offer companies a valuable means of communicating with their customers.

How to implement it in your node.js project?

To follow the steps with me you will need an Amazon AWS account and an AWS Pinpoint phone number.

We’ll send SMS from our Node js app to the users/customers using Amazon AWS Pinpoint, and the autogenerated response will be sent to the users/customers using AWS SNS.

Amazon Pinpoint is an outgoing and inbound marketing communications service that is both versatile and scalable. Customers can be contacted by email, SMS, push notifications, voice, or in-app messaging.

Amazon Simple Notification Service (Amazon SNS) is a fully managed messaging service for both A2A and A2P communication.

Create a node.js project and install AWS SDK using this command given below

npm i aws-sdk

Create a file named sms.js, name it whatever you like, and import aws-sdk, then set your AWS secret key, access key, and chosen region. Do not disclose your AWS access key or secret key to anybody.

var AWS = require("aws-sdk");
SECRET_KEY = "Itisasecret";
ACCESS_KEY = "thisoneisasecrettoo";
REGION = "yourwish";

Now update the AWS configuration using your credentials and create a pinpoint object and SNS object, make sure to define the API version while creating the SNS object.

const CONFIG= {
  accessKeyId: ACCESS_KEY,
  secretAccessKey: SECRET_KEY,
  region: REGION,
};
AWS.config.update(CONFIG);


const pinpoint = new AWS.Pinpoint();

const sns = new AWS.SNS({apiVersion: "2010-03-31"});

Before moving ahead please make sure to buy a pinpoint phone number and create a pinpoint project and enable SMS channel using the AWS console

Let’s try sending one SMS now using the pinpoint sendMessages method. Keep in mind that you will be charged for each and every text message you send.

function sendMessage() {
  // The phone number or short code to send the message from. The phone number
  var originationNumber = "+19105974313";

  // The recipient's phone number.
  var destinationNumber = "+12xx23xx813";

  // The content of the SMS message.
  var message =
    `Hello There! Here is a song for you -
  Never gonna give you up
  Never gonna let you down
  Never gonna run around and desert you
  Never gonna make you cry
  Never gonna say goodbye
  Never gonna tell a lie and hurt you`;

  // The Amazon Pinpoint project/application ID to use when you send this message.
  var applicationId = "xxxxn3v3rg0nnag1v3y0uupcxxxxxxxxxxxxxxxxx";

  // You must select the type of SMS message you wish to send.     //Specify TRANSACTIONAL if you intend to convey time-sensitive //material. PROMOTIONAL should be used if you intend to transmit //marketing-related information.
  var messageType = "PROMOTIONAL";

  // The sender ID to use when sending the message. Support for sender ID
  // varies by country or region. For more information, see
  // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html
  var senderId = "MySenderID";

  var params = {
    ApplicationId: applicationId,
    MessageRequest: {
      Addresses: {
        [destinationNumber]: {
          ChannelType: "SMS",
        },
      },
      MessageConfiguration: {
        SMSMessage: {
          Body: message,
          Keyword: registeredKeyword,
          MessageType: messageType,
          OriginationNumber: originationNumber,
          SenderId: senderId,
        },
      },
    },
  };
  pinpoint.sendMessages(params, function (err, data) {
    if (err) {
      console.log(err.message);
    } else {
      console.log(
        "Message sent! " +
          data["MessageResponse"]["Result"][destinationNumber]["StatusMessage"]
      );
    }
  });
}

Great👍, so our A2P part is done here, now we can proceed to two-way SMS.

We will need to create an AWS SNS topic and subscribe to it. A logical access point that also serves as a communication channel is an Amazon SNS topic. Multiple endpoints (such as Amazon SQS, HTTP/S, or an email address) can be grouped together using a topic.

Let’s start with our create and subscribe topic function. Note- in subscribe part you can choose the protocol and endpoint according to your preference. You can refer to this AWS documentation for other protocols. https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html

We will be using SMS as our protocol and phone number as our endpoint

function createAndSubscribeTopic() {
  const snsTopic = sns.createTopic({
      Name: 'twoWaySMSHandler',
      Attributes: {
          DisplayName: "Two-way SMS Handler",
      },
  }).promise()


  snsTopic.then(
      function(data) {
          const subscribePromise = sns.subscribe({
              Protocol: 'sms', //change according to preference
              TopicArn: data.TopicArn,
              Endpoint: '+1209xxxx739', //change according to your protocol,
              ReturnSubscriptionArn: true
          }).promise();

          subscribePromise.then(
              function(data) {
                  console.log('subscribe topic data', data);

              }).catch(
              function(err) {
                  console.error(err, err.stack);
              });

      }).catch(
      function(err) {
          console.error(err, err.stack);
      });
}

Now let’s move to the amazon console for once and make some tweaks in our pinpoint phone number.

STEP 1- Select the number and click on the two-way SMS dropdown at the bottom

STEP 2 – Select the SNS topic you just created and add a custom keyword as you wish

Step 3 – Save the changes and send another SMS using our node.js project

Our autogenerated message is now sent when the user/customer answers with the keyword.

Great, our two-way SMS is working too. If you are wondering “what if we the user send something else?” then you can check what reply was sent by them by checking the payload sent by the SNS to the number(or whatsoever protocol you chose while subscribing to SNS topic) and manage the conditions accordingly.

This is the example of the payload you will receive –

If you followed everything till now then..

Thank you!