Add Twilio SMS Messaging to your Rails App

Below is a detailed walk through of adding SMS messaging to your Rails app written by Chris Rittersdorf of Mutally Human. Chris is an experienced developer who enjoysbuilding excellent web applications and in his spare time maintains manlyco.de.
This content was originally posted on the Mutually Human blog found here.  

Introduction

The use of smart phones is on the rise, however SMS text messaging is still the best way to reach the broadest customer base, especially in developing countries. If you have a Ruby on Rails application that needs to reach this broad customer base, Twilio is an excellent tool to have in your toolbox.
It’s easy to add Twilio to a Rails application. This post will walk you through the process of integrating Rails with Twilio, including:
  • Signing Up for a Twilio Account
  • Testing with Twilio’s Sandbox App
  • Integrating Twilio with a Rails Application
  • Configuring your Twilio enabled Rails application for Production
Let’s get started!

Signing Up for Twilio

Signing up for Twilio is as simple as providing your name, email and password. After you sign up and log in for the first time, you are taken to the Dashboard. This will give you plenty of information to get started. Upon signing up, you are given $30 in credits to get started. These credits are spent every time a text message is sent or received by Twilio.

In the bottom left section of your dashboard, you’ll see a box called Sandbox App. The Twilio Sandbox is where you want to do development work with Twilio. The Sandbox not only lets you test out your SMS enabled application, but it also lets you lock down which mobile phones can send text messages to it and which mobile phones it can send text messages to. This is in contrast to the live account that can send and receive text messages to and from any mobile phone. Now that you know what the Sandbox is, let’s try it out.

Testing Your Account Using the Sandbox

To test the SMS sandbox, send a text message from your phone to the sandbox number. The content doesn’t matter, it can be anything. Try texting “hello twilio”. You’ll then see a reply similar to this:
Sent from the Twilio Sandbox Number - Error: No PIN.
Make sure you begin your message with the Sandbox PIN from your Twilio Dashboard.
Any time you interact with the Twilio Sandbox, you must provide a PIN along with all communications (whether SMS or Voice). This PIN is located below the Sandbox number on your dashboard. Enter the pin at the beginning of your text message, for example:
28910293 hello twilio
You’ll then get a reply from the default Twilio Service located at:
http://demo.twilio.com/welcome/sms
Now that you’ve confirmed that your account is in working order, let’s see how was can leverage service in a Ruby on Rails application.

Integrating Twilio with Your Rails Application

Web applications communicate with Twilio using an XML variant called TwiML. For example:
<?xml version="1.0" encoding="UTF-8"?>
<!-- page located at http://example.com/simple_sms.xml -->
<Response>
    <Say>Our store is located at 123 Easy St.</Say>
    <Sms>Store Location: 123 Easy St.</Sms>
</Response>
view raw gistfile1 This Gist brought to you by GitHub.
This section of TwiML describes how to respond to a user calling a phone number. It speaks a message during the phone call, then sends the user an SMS message. But, it’s no fun writing TwiML. And since we’re using Ruby, there’s a gem for that! The twiliio-ruby gem abstracts TwiML into an easy to use Ruby API. In your Rails application, simply add the twilio-ruby gem to your Gemfile:
source 'http://rubygems.org'
gem 'rails', '3.1.0'
gem 'twilio-ruby'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
gem 'jquery-rails'
...
view raw Gemfile This Gist brought to you by GitHub.
Now you have the necessary library to start sending text messages. So now let’s use it!

Sending a Text Message Using Twilio

Sending a text message with your Rails application is simple. But before doing so, there is one configuration we have to make. To test your application using the Twilio Sandbox, you’ll need to white-list any phone numbers you plan to send SMS messages to. You can do this by going to the Numbers tab and clicking the Verify Number button. There is a series of steps you’ll have to complete to verify your number.

After you’ve verified the phone number, your application can now send text messages. The following code example show you how:
class SendTextController < ApplicationController
  def index
  end
  def send_text_message
    number_to_send_to = params[:number_to_send_to]
    twilio_sid = "abc123"
    twilio_token = "foobar"
    twilio_phone_number = "6165555555"
    @twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token
    @twilio_client.account.sms.messages.create(
      :from => "+1#{twilio_phone_number}",
      :to => number_to_send_to,
      :body => "This is an message. It gets sent to #{number_to_send_to}"
    )
  end
end
In this example, the send_text_message action receives a phone number from a form post, then relays a hard-coded message to that phone number via SMS. The twilio_sid, twilio_token, and twilio_phone_number variables contain the configuration information for authentication using the twilio-ruby gem. Generally, you’d want to pull this into a configuration file that gets loaded when your application loads, but I’ve put them into local variables for simplicity.

Receiving a Text Message Using Twilio

In order to receive a text message from a mobile device, you’ll have to expose an endpoint that is reachable by Twilio. Here is an example:
class ReceiveTextController < ActionController
  def index
    # let's pretend that we've mapped this action to
    # http://localhost:3000/sms in the routes.rb file
    
    message_body = params["Body"]
    from_number = params["From"]
    SMSLogger.log_text_message from_number, message_body
  end
end
In this example, the index action receives a POST from Twilio. It grabs the message body, and the phone number of the sender and logs it. Retrieving the information from the Twilio POST is as simple as looking at the params hash:
In order for text messages to reach your application you have to tell Twilio where to send requests. This is again done in the Sandbox App section of the Twilio Dashboard. Specify your publicly facing endpoint in the SMS URL field and click “Save”.
If you’re running your server locally and have no publicly facing endpoint, you can use a service like tunnlr to create one. This creates a publicly accessible URL with an SSH tunnel back to your local machine.
So the publicly facing endpoint for your application would look something like:
http://web1.tunnlr.com:89530/sms

Configuring Twilio for Production

To deploy your SMS enabled application in a production environment, there are three things you’ll need to do: buy a Twilio phone number, configure that phone number in your application, and then configure the production end-point in Twilio.
Purchasing a phone number requires you to enter payment information and decide on a phone number to provision. Twilio will guide you through the process. At the time of writing, Twilio’s pricing is set at $1.00 a month plus an additional 1¢ charge per text.
Also, you will need to update the Twilio phone number in your application to the new number that you’ve provisioned. The examples above contained a variable with the value for a Twilio phone number. Change this value to the new phone number you provisioned.
Finally, you’ll now have to configure the SMS endpoint much like how we did for the Sandbox. Click on the “Numbers > Twilio Numbers” tab. Then click on the phone number you provisioned. Finally, in the “SMS Request URL” field, specify your publicly facing production endpoint URL, then click “Save Changes”.

Conclusion

Whether it be for those on-the-go, or those who otherwise are not able to use a computer or smart phone, SMS provides excellent alternative interface for the users of your web application. For those looking for a simple and affordable way to get started, Twilio is an outstanding option. So now that you know how to get started, what will you build using Twilio?
Posted by Meghan Murphy on February 8, 2012