How to send SMS using Amazon SNS and Nodejs


Amazon SNS ( Simple Notifications Service ) is a publish/subscribe and mobile notification service. It is used to send message to subscribing endpoints and clients.  You can send a large number of messages to subscribers, services, and mobile devices. like amazon ses this one also a pay-per-use service.

In this tutorial we are going to learn how to send sms using amazon sns and nodejs

Sending SMS using Amazon SNS and Nodejs

Amazon SNS is a bit different than other services. You can’t send message directly to a client or service. Rather you need to create and publish a message to a topic.  The clients/services will recieve the message who had subscribed to that topic.

Let’s start with creating a topic.

To create a topic, navigate to Amazon SNS Dashboard and click on Create topic.

amazon sns - create topic

 

Type Topic name and Display name then click on Create Topic.

amazon sns - create new topic form

Create a Nodejs project

Create a directory for your project

mkdir amazonSNS

cd amazonSNS

Now run npm init 

npm init

It will prompt you for several things but for now just leave it as default.

package name: (amazonSNS) 
version: 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC)

Once you have done with npm init package.json file should look like below

package.json

{
  "name": "amazonSNS",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Install express.js framework

npm install express --save

It will install all the required  dependencies in your express project.

And finally install the aws-sdk module. It acts like a mediator between amazon web services and your application.

npm install aws-sdk --save

In your project folder create a file called config.json and paste the following code

{
"accessKeyId":"", //enter your accesskeyId
"secretAccessKey":"", // enter your secretAccessKey
"region":"" // enter your region which you choose on account setup
}

To find security credentials

Go to AWS Console -> Account Name -> My Security Credentials -> Create New Access key

amazon sns - create access key

Find Topic ARN

Go to Amazon SNS dashboard -> Topics  and click on your topic , there you can find the Topic ARN

amazon sns - topic arn

index.js

const express = require( 'express' );
const app = express();
app.get('/', (req, res) => {
    
    //load aws-sdk module
    var AWS = require('aws-sdk');

    //loads config.json which we created earlier which contains aws security credentials.
    AWS.config.loadFromPath('config.json');
  

    var sns = new AWS.SNS();

    var SNS_TOPIC_ARN = "type_your_topic_arn_which";
    
   
    //subscribing a mobile number to a topic
    sns.subscribe({
        Protocol: 'sms',
        TopicArn: SNS_TOPIC_ARN,
        Endpoint: to_number // type mobile number to whom you want to send a message.
    }, function(error, data) {

        if (error) {
            console.log("error when subscribe", error);
        }
        console.log("subscribe data", data);
        var SubscriptionArn = data.SubscriptionArn;

        var params = {
            TargetArn: SNS_TOPIC_ARN,
            Message: message,//type your message
            Subject: 'type_your_subject' //type your subject
        };

        

        //publish a message.
        sns.publish(params, function(err_publish, data) {
            if (err_publish) {
                console.log('Error sending a message', err_publish);

            } else {
                console.log('Sent message:', data.MessageId);
            }

            var params = {
                SubscriptionArn: SubscriptionArn
            };
            

            //unsubscribing the topic
            sns.unsubscribe(params, function(err, data) {
                if (err) {
                    console.log("err when unsubscribe", err);
                }
            });
        });
   });
});

app.listen(3000, () => console.log('Example app listening on port 3000!'))

also read How to send Email using Amazon SES and Nodejs


Leave a Reply

Your email address will not be published. Required fields are marked *