Receive an SMS

Plivo supports receiving SMS text messages in 19 countries (see complete SMS API coverage). When an SMS is sent to a Plivo phone number, you can receive the text on your server by setting a Message URL in your Plivo app. Plivo will send the message along with other parameters to your Message URL.

Prerequisites

  1. Sign up for a free Plivo trial account.
  2. Check out our Helper Libraries page and install the right helper based on the programming language you want to use.
  3. Buy a Plivo phone number. A phone number is required to receive and reply to SMS text messages. You can buy a Plivo phone number in over 19 countries through the Buy Numbers tab on your Plivo account UI. Check the SMS API coverage page for all the supported countries.
  4. Use a web hosting service to host your web application. There are many inexpensive cloud hosting providers that you can use for just a few dollars a month. Follow the instructions of your hosting provider to host your web application.
    Note: If you are using a Plivo Trial account for this example, you can only send sms to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

Set up a Web Server

Let’s assume your web server is located at http://example.com. Below is a snippet to set up a route on your webserver. Now when we send an HTTP request to http://example.com/receive_sms this route will be invoked.

Note: For PHP, the route will be example.com/receive_sms.php.

  1. Copy the relevant code below into a text file and save it. Lets call it receive_sms.
    Note: Make sure to use the appropriate file extention for your code (e.g., `receive_sms.py` for Python).
  2. Next you will now have to configure this URL in your Plivo application.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import plivo, plivoxml
from flask import Flask, request

app = Flask(__name__)

@app.route("/receive_sms/", methods=['GET','POST'])
def receive_sms():
    # Sender's phone numer
    from_number = request.values.get('From')
    # Receiver's phone number - Plivo number
    to_number = request.values.get('To')
    # The text which was received
    text = request.values.get('Text')

    # Print the message
    print 'Message received - From: %s, To: %s, Text: %s' % (from_number, to_number, text)

    return "Message received", 200

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
require 'sinatra'

post '/receive_sms/' do
    # Sender's phone numer
    from_number = params[:From]
    # Receiver's phone number - Plivo number
    to_number = params[:To]
    # The text which was received
    text = params[:Text]

    # Output the text which was received
    puts "Message received - From: #{from_number}, To: #{to_number}, Text: #{text}"

    "Message received"
end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 5000));
app.all('/receive_sms/', function(request, response) {
    // Sender's phone number
    var from_number = request.body.From || request.query.From;
    // Receiver's phone number - Plivo number
    var to_number = request.body.To || request.query.To;
    // The text which was received
    var text = request.body.Text || request.query.Text;
    console.log('Message received - From: ', from_number, ', To: ', to_number, ', Text: ', text);
    response.send("Message received");
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
    // Sender's phone numer
    $from_number = $_REQUEST["From"];
    // Receiver's phone number - Plivo number
    $to_number = $_REQUEST["To"];
    // The SMS text message which was received
    $text = $_REQUEST["Text"];
    // Output the text which was received to the log file.
    error_log("Message received - From: $from_number, To: $to_number, Text: $text");
?>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.plivo.test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class receiveSms extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String from_number = req.getParameter("From");
        String to_number = req.getParameter("To");
        String text = req.getParameter("Text");
        System.out.println("Message received - From: " + from_number + ", To: " + to_number + ", Text: " + text);
        resp.getWriter().print("Message received");
    }

    public static void main(String[] args) throws Exception {
        String port = System.getenv("PORT");
        if(port==null)
            port ="8080";
        Server server = new Server(Integer.valueOf(port));
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        context.addServlet(new ServletHolder(new receiveSms()),"/receive_sms");
        server.start();
        server.join();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Collections.Generic;
using System.Reflection;
using Nancy;
using RestSharp;
using Plivo.API;

namespace Receive_Sms
{
    public class Program : NancyModule
    {
        public Program()
        {
            Post["/receive_sms"] = x =>
            {
                String from_number = Request.Form["From"]; // Sender's phone number
                String to_number = Request.Form["To"]; // Receiver's phone number
                String text = Request.Form["Text"]; // The text which was received

                // Print the message
                Console.WriteLine("Message received - From: {0}, To: {1}, Text: {2}", from_number, to_number, text);

                return "Message received";
            };
        }
    }
}

Create an Application

  1. Create an Application by visiting the Application Page and click on New Application or by using Plivo’s Application API.
  2. Give your application a name. Lets call it Receive SMS. Enter your server URL (e.g. http://example.com/receive_sms) in the Message URL field and set the method as POST. See our Application API docs to learn how to modify your application through our APIs.
  3. Click on Create to save your application.

Create Application

Assign a Plivo number to your app

  1. Navigate to the Numbers page and select the phone number you want to use for this app.
  2. Select Receive SMS (name of the app) from the Plivo App dropdown list.
  3. Click on Update to save.

Assign Phone Number to Receive SMS App

If you don’t have a number, go to the Buy Number page to purchase a Plivo phone number.

SMS Phone Number Search

Test it out

Send an SMS to your Plivo number using a regular mobile phone. Plivo will send a request to your Message URL with the parameters listed in the XML Request - Messages Documentation.

Next Step

Learn how to reply to an incoming (inbound) SMS.

  1. Send a Single SMS
  2. Send a Long SMS
  3. Send Multiple (Bulk) SMS
  4. Send an SMS with Alphanumeric Sender ID

  5. Reply to an Incoming SMS
  6. Forward an Incoming SMS
  7. Get Details of all Messages
  8. Get Details of a Single Message
  9. Handling SMS Delivery Reports
  10. Forward SMS to Email