This article originally appeared on the Nexmo blog. If you want to try it out, I've set up a few Nexmo phone numbers for different countries, and you can send an SMS message to +447451272987 or +13095902987 to get your messages back as emojis. If you want me to set up a number for your country, tell me on Twitter, I'll provision it and update the post here for others to use.
Webhooks are ever-more popular in the API world, and Nexmo uses them for quite a few of our APIs. So I end up writing quite a few of them. Since Iโm a Node.js fan, I used to do most of them with Express. It was a hassle to spin up a webserver and get that deployed somewhere, so I started looking for alternatives. Serverless kept popping up in my research as one of the good alternatives, so I thought Iโd use Azure Functions and Node.js to send and receive SMS messages.
For SMS, Iโm going to use the Nexmo SMS API, which allows you to send and receive a high volume of SMS anywhere in the world. Once you get your virtual phone number, you can use the API to manage outbound messages (โsendingโ) and inbound messages (โreceivingโ).
In this article, you will learn how to send and receive SMS messages with Node.js and an Azure Functions App.
The code for this tutorial can be found on GitHub.
Prerequisites
Before you begin, make sure you have:
- A Nexmo account
- An Azure account
- Node.js installed on your machine
Set up an Azure Functions App
There are a few ways you can set up an Azure Functions App. Iโve chosen to do so from the Azure Portal.
Iโve named it send-receive-sms
, created a new resource for it, and chose Node.js as the runtime. Iโve chosen the defaults in terms of deployment, region, and plans.
Once the deployment finishes (usually around 2 minutes), you can go to the newly created resource and create your first function. There is a wizard helping you through the process, and Iโve selected VS Code as my development environment and โDirect publishโ as my deployment method. That gave me a set of instructions on how to set up VS Code for Azure.
Once I was done with the setup, I created my first function, an HTTP Trigger. Iโve called it inbound
, but you can use any name you want. For the security mechanism, you have a few options that control the authorization level on the function. โFunctionโ requires a function-based API key, โAdminโ requires your master API key from Azure, and โAnonymousโ doesnโt require an API key. Iโve chosen โAnonymousโ as the security mechanism for it. That created a new file with a default template.
Receiving an SMS Message
Create a Webhook Function
Iโve replaced the contents of the function to match the Receive an SMS code snippet we use on our developer portal. It combines the body and query parameters of a request and logs that to the console. Itโs a simple Webhook you can use to receive SMS messages on the Nexmo platform.
module.exports = async function(context, req) {
const params = Object.assign(req.query, req.body);
if (params.text) {
context.log("SMS received", params);
}
context.res = {};
};
Deploy Function
Because Nexmo needs to be able to access a public URL, Iโve deployed my function with Azure. You can do so in VS Code. Once the deployment finishes, youโll get back a live URL for your function, for example, mine is https://send-receive-sms.azurewebsites.net/api/inbound
.
Set Inbound URL
To receive a SMS message on the Nexmo platform, you have to own a Nexmo number. If you donโt have one, you can buy one in the Nexmo Dashboard:
When a Nexmo phone number receives an SMS message, Nexmo will pass that message to a Webhook you have specified in the Nexmo dashboard. Weโll use our Azure Function as the receiving Webhook. To set up the webhook URL, go to the little gear icon next to your phone numbers in the Nexmo Dashboard and fill in the โInbound Webhook URLโ field with the URL you got after deploying the Azure function (mine was https://send-receive-sms.azurewebsites.net/api/inbound
).
You can test it works by sending an SMS from your phone to your Nexmo phone number, and it will show up in the Azure function logs.
Sending an SMS Message
I thought it would be nice if the Function did a little more than logging the SMS messages, so Iโm going to make it respond to SMS messages as well, changing the message from text to emojis.
Iโm going to use the Nexmo Node.js SDK for sending the SMS message, so youโll need to install it in the Azure function. The top-level folder for your function has a package.json
file in it that gets installed with each deployment. So if you navigate to that folder in the Terminal and use npm install nexmo
, that will give you access to the Nexmo SDK inside the Azure function.
Iโve also updated the function to initialize the Nexmo SDK, convert the SMS message to emojis and then send it as an SMS back to the original sender.
module.exports = async function(context, req) {
const Nexmo = require("nexmo");
const nexmo = new Nexmo({
apiKey: process.env["NEXMO_API_KEY"],
apiSecret: process.env["NEXMO_API_SECRET"]
});
const params = Object.assign(req.query, req.body);
if (params.text) {
var response = [];
// transform inbound SMS into emojis
for (let i = 0; i < params.text.length; i++) {
const emoji = String.fromCodePoint(127715 + params.text.charCodeAt(i));
response.push(emoji);
}
// send SMS back with emojis
nexmo.message.sendSms(
params.to,
params.msisdn,
response.join(""),
{
type: "unicode"
},
(err, responseData) => {
if (err) {
context.log(err);
} else {
if (responseData.messages[0]["status"] === "0") {
context.log("Message sent successfully.");
} else {
context.log(
`Message failed with error: ${responseData.messages[0]["error-text"]}`
);
}
}
}
);
}
context.res = {};
};
Youโll notice my code initializes the Nexmo SDK with process.env["NEXMO_API_KEY"]
and process.env["NEXMO_API_SECRET"]
. The Azure Function App has Application settings and Iโve added my NEXMO_API_KEY
and NEXMO_API_SECRET
in there, and those get updated with each deployment from my local machine. You can do so as well, or replace those values with your actual API key and secret. You can find those on the โGetting Startedโ page in the Nexmo Dashboard.
The SDK method for sending an SMS, nexmo.message.sendSms()
, takes the sender ID, the recipient phone number, the text message and options as parameters. Iโve added {type: "unicode"}
in the options because Iโm sending emojis. It also accepts a callback that gets called when the API request is done.
The response data contains an array for all the messages that were sent, with information about their status. In most cases, itโs going to be one element in that array, but if the SMS was longer than 160 characters, it gets split into a multipart SMS, and then the array contains data about each part sent. If the status of the message is 0, the SMS was sent successfully, otherwise, the error data for the message is on the error-text
property of the message.
Because my text has an emoji in it, Iโm setting the type unicode
in the options object, otherwise, that emoji is going to be sent on the network as ?
.
Try It Out
Now send an SMS message from your phone to your Nexmo number. You should get back an SMS message converting your text characters to emojis. If you send Hello World!
in the SMS, you should get back ๐ท๐๐๐๐๐๐๐๐๐๐๐๐๐๐.
I hope it worked and youโve just learned how to send and receive SMS messages with the Nexmo APIs. Azure Functions and Node.js.
Top comments (1)