Skip to content

Instantly share code, notes, and snippets.

@iamEtornam
Last active August 16, 2021 20:56
Show Gist options
  • Save iamEtornam/897b9870fec01047d84eead9fcf9f9e8 to your computer and use it in GitHub Desktop.
Save iamEtornam/897b9870fec01047d84eead9fcf9f9e8 to your computer and use it in GitHub Desktop.
How to send sms using AWS SNS service in javascript
'use strict';
const AWS = require('aws-sdk');
AWS.config.update({
secretAccessKey: process.env.secretAccessKey,
accessKeyId: process.env.accessKeyId,
region: process.env.region
});
const sendSms = function (event, context, callback) {
try {
const requestBody = JSON.parse(event.body);
const phone_number = requestBody.phone_number;
const params = {
Message: `Your OTP code for Social Savings app is ${code}`,
PhoneNumber: phone_number,
MessageAttributes: {
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': 'Aura'
},
'AWS.SNS.SMS.SMSType': {
'DataType': 'String',
'StringValue': 'Transactional'
}
}
};
if (typeof phone_number !== 'string') {
console.error('phone number validation failed');
callback(null, {
statusCode: 406,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
},
body: JSON.stringify({
status: false,
message: 'Couldn\'t proceed because of phone number is not valid.'
})
});
}
const publishTextPromise = new AWS.SNS({
apiVersion: '2010-03-31'
}).publish(params).promise();
publishTextPromise.then(data => {
console.log(data, 'data');
if (data) {
callback(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
},
body: JSON.stringify({
status: true,
message: `Successfully sent an SMS to ${phone_number}`,
}),
})
} else {
callback(null, {
statusCode: 406,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
},
body: JSON.stringify({
status: false,
message: 'Could send sms'
}),
})
}
})
} catch (error) {
console.log(error, 'error');
callback(null, {
statusCode: 500,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
},
body: JSON.stringify({
status: false,
message: error
}),
})
}
}
module.exports = {
sendSms
}
//if you are using serverless, you can set your environment variables like this
// # you can define service wide environment variables here
// environment:
// SECRET_ACCESS_KEY: ${file(./secrets.json):SECRET_ACCESS_KEY}
// ACCESS_KEY_ID: ${file(./secrets.json):ACCESS_KEY_ID}
// REGION: us-east-1
@iamEtornam
Copy link
Author

if you are using serverless, you can set your environment variables like this

# you can define service wide environment variables here
   environment:
     SECRET_ACCESS_KEY: ${file(./secrets.json):SECRET_ACCESS_KEY}
     ACCESS_KEY_ID: ${file(./secrets.json):ACCESS_KEY_ID}
     REGION: us-east-1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment