Texting has outpaced email and phone calls as the quickest method to get in contact with someone, and it is fast becoming a way to reach anyone. A simple SMS has the capability to reach any of the 4.5 billion text-enabled devices in the world. Today, appointment reminders, ETA alerts for on-demand services, banking notifications, and flight status are all sent conveniently and programmatically directly to the user’s phone via SMS.
Twilio’s Programmable SMS API lets you send and receive text messages right in your web applications. With a few lines of code, you can get an SMS app running in a few minutes. Though Programmable SMS supports several languages, like Java and C#, for the purposes of this tutorial we’re going to focus on using Node.js.
Get a Twilio phone number
Before you can send an SMS from Node.js, you’ll need to sign up for a Twilio account and purchase an SMS-capable phone number. If you sign up for the free trial, you get your first phone number for free. If you search for a number to buy, you’ll be able to see what types of communication it can power.
Click the Buy button to add one of these numbers to your account. Now that you have a Twilio account and a programmable phone number, you can start writing code. To make it easier, we’ll install Twilio’s official helper for Node.js applications.
Install the Twilio Node.js module
Next, we’ll install the Twilio module for Node.js. Fire up a terminal or command-line interface on your machine that already has Node and NPM installed, and run the following command in a new directory:
npm install twilio
This will install the twilio module so that Node.js scripts in the current directory can use it.
Send an outbound SMS message
Let’s put that shiny, new Twilio Node.js library to good use. With a single API request, we can send an outbound text message from the Twilio phone number we purchased. Open a new file called send-sms.js and paste in this code sample.
// Twilio Credentials
var accountSid = ‘ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’;
var authToken = ‘your_auth_token’;
// require the Twilio module and create a REST client
var client = require(‘twilio’)(accountSid,authToken);
client.messages.create({
to: “+15558675309”,
from: “+15017250604”,
body: “This is the ship that made the Kessel Run in fourteen parsecs?”,}, function(err,message) {
console.log(message.sid);
});
Update the account credentials with your own account information. Specify your new Twilio number in the from
parameter and your own mobile number in the to
parameter. Run the code we created with this command:
node send-sms.js
In a few moments, you should receive an SMS from your Twilio number on your phone. Now let’s talk about receiving text messages.
Receive inbound SMS messages
When your Twilio number receives an incoming message, Twilio will send an HTTP request to a server you control. This callback mechanism is known as a webhook. When Twilio sends your application a request, it expects a response in the TwiML XML format telling it how to respond to the message. Let’s see how we would build this in Node.js using Express. Install Express with the following command:
npm install express —save
Next, create a file called server.js and use the following code to create a server that can handle incoming messages.
var http = require(‘http’);
var express = require(‘express’);
var twilio = require(‘twilio’);
var app = express();
app.post(‘/sms’,function(req,res) {
var twilio = require(‘twilio’);
var twiml = newtwilio.TwimlResponse();
twiml.message(‘The Robots are coming! Head for the hills!’);
res.writeHead(200,{’Content-Type’:’text/xml’});
res.end(twiml.toString());
});
http.createServer(app).listen(1337,function() {
console.log(“Express server listening on port 1337”);
});
Run this server with the following command:
node server.js
You’ll see that the server starts up on port 1337. Unfortunately, Twilio can’t directly call a server running on your computer. You’ll either need to deploy this code to a public server or run a tunnel such as ngrok that provides an externally accessible URL. We’ll show you how to set that up next.
Allow Twilio to talk to your Node application
If you haven’t already, install Ngrok and ensure the ngrok
command is on your system path. The following command would use Ngrok to expose port 1337 to the public Internet. (If you used a different port number in your Express app, replace 1337 with the port number you used.)
ngrok http 1337
Now we have a new external URL. Configure this as a webhook for one of your phone numbers in the Twilio console. Select your phone number, scroll down to the Messaging section, and change the setting for A MESSAGE COMES IN
to Webhook
, then enter the public ngrok URL to your service, such as https://adfs3423.ngrok.io/sms
.
Be sure your Node.js app (server.js) is still running. Then grab your smartphone and send a text message to your Twilio phone number. You should see an HTTP request in your Ngrok console. Your Node app will process the text message, and you’ll get a response back as an SMS.
Now that you know the basics of sending and receiving text messages with Node.js, you might want to check out these resources.
- REST API documentation
- TwiML reference docs
- Tutorials with full sample applications in Node.js
Happy hacking!
New Tech Forum provides a venue to explore and discuss emerging enterprise technology in unprecedented depth and breadth. The selection is subjective, based on our pick of the technologies we believe to be important and of greatest interest to InfoWorld readers. InfoWorld does not accept marketing collateral for publication and reserves the right to edit all contributed content. Send all inquiries to newtechforum@infoworld.com.