Getting started receiving SMS with Ruby

How to Receive SMS Messages with Ruby on Rails

Published October 23, 2017 by Chris Guzman

This is the third article in a series of “Getting Started with Nexmo SMS and Ruby on Rails” tutorials.

In the previous article, you set up your Rails application to be publicly accessible by Nexmo, and then received a Delivery Receipt for a sent message. In this article you will learn how to receive an inbound SMS by implementing a similar webhook endpoint in Ruby on Rails.

View the source code on GitHub

Prerequisites

For this tutorial I assume you will:

What is an “Inbound SMS”?

When someone sends an SMS message to the Nexmo Number that you purchased in the first tutorial it will be received by Nexmo, and we will then pass the content of that message on to a webhook in your application.

To receive this webhook you will need to set up a webhook endpoint and tell Nexmo where to find it.

DLR diagram receive flow

In the previous tutorial I already covered how to set up ngrok for your application to allow it to be accessible even in a development environment.

Set the Webhook Endpoint with Nexmo

There are 2 ways to set up your number for inbound SMS. The first way is to install the Nexmo CLI tool (a NodeJS command line interface) and then run the following commands to bind your number to an inbound SMS webhook:

Alternatively, head over to the Settings page on the Nexmo Dashboard and scroll down to API settings to configure the Webhook URL for Inbound Message.

dashboard.nexmo.com/settings

Global inbound SMS configuration

Note: This sets the webhook endpoint for inbound SMS at an account level. You can also set up unique webhook endpoints for each virtual number.

Handle an Inbound SMS WebHook

The hard part is really done again at this point. When an SMS has been sent to your virtual Nexmo number, Nexmo will notify your application by sending a webhook. A typical payload for an inbound SMS will look something like this.

In this payload the sending number is identified by the msisdn parameter, and your Nexmo number is the to parameter. Let’s add a new controller to process this payload and store a new SMS record.

Finally, let’s immediately reply back to the sender by reversing the message they sent and sending it back to them.

Ok, now start your server, ensure you have something like ngrok running, and send an SMS to your Nexmo number.

Reversed SMS result

To sum things up

That’s it for this tutorial. We’ve set up our Rails application to receive inbound SMS webhooks, informed Nexmo of where to find our server, processed an incoming SMS webhook, and replied back to the sender.

You can view the code used in this tutorial on GitHub.

Next steps

In the next tutorial we will move on from SMS and start looking at making our first phone call from a Rails application.

Leave a Reply

Your email address will not be published.