Reply to an Incoming SMS

When an SMS is sent to an 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. You can reply back using the Plivo Message XML.

Note: In order to reply to a US or Canadian phone number, the `'src'` (source) phone number must be a Plivo US or Canadian phone number. You can purchase a Plivo number from the Buy Numbers tab on your Plivo account dashboard.

Getting Started

  1. Sign up for a free Plivo trial account.
  2. Check out our server-side SDKs page and install the right helper based on the programming language you want to use.
  3. 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/reply_to_sms/ this route will be invoked.

Note: For PHP, the route will be example.com/reply_to_sms.php.
  1. Copy the relevant code below into a text file and save it. Let’s call it, 'reply_to_sms'.
  2. Customize the 'body' with your reply.
  3. 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
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from flask import Flask, request, make_response, Response
import plivo
from plivo import plivoxml

app = Flask(__name__)


@app.route('/reply_sms/', methods=['GET', 'POST'])
def inbound_sms():
    # Sender's phone number
    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))

    # send the details to generate an XML
    response = plivoxml.ResponseElement()
    response.add(
        plivoxml.MessageElement(
            'Thank you, we have received your request',  # The text to be sent
            src=to_number,  # Sender's phone number
            dst=from_number,  # Receiver's phone Number
            type='sms',
            callback_url='http://foo.com/sms_status/',
            callback_method='POST'))
    print(response.to_string())  # Prints the XML
    # Returns the XML
    return Response(response.to_string(), mimetype='application/xml')


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
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
require "plivo"
require "sinatra"

include Plivo
include Plivo::XML

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

  # Print the message
  puts "Message received - From: #{from_number}, To: #{to_number}, Text: #{text}"

  # send the details to generate an XML
  response = Response.new
  params = {
    src: to_number,  # Sender's phone number
    dst: from_number, # Receiver's phone Number
    type: "sms",
    callbackUrl: "https://www.foo.com/sms_status",
    callbackMethod: "POST",
  }

  message_body = "Thank you, we have received your request"
  response.addMessage(message_body, params)
  xml = PlivoXML.new(response)

  puts xml.to_xml() # Prints the XML
  content_type "application/xml"
  return xml.to_s() # Returns the XML
end
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
37
38
39
40
var plivo = require('plivo');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(function (req, response, next) {
    response.contentType('application/xml');
    next();
});
app.set('port', (process.env.PORT || 5000));
app.all('/reply_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;
    // Print the message
    console.log('Message received - From: ' + from_number + ', To: ' + to_number + ', Text: ' + text); 

    //send the details to generate an XML
    var r = plivo.Response();
    var params = {
        'src': to_number, //Sender's phone number
        'dst': from_number, //Receiver's phone Number
        'type': "sms",
        'callbackUrl': "https://www.foo.com/sms_status",
        'callbackMethod': "POST"
    };
    var message_body = "Thank you, we have received your request"; //The text to be sent
    r.addMessage(message_body, params);
    console.log(r.toXML()); //Prints the XML
    response.end(r.toXML()); //Returns the XML
});
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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
    require 'vendor/autoload.php';
    use Plivo\XML\Response;
    // 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"];
    // Prints the message
    echo("Message received - From $from_number, To: $to_number, Text: $text");

    // send the details to generate an XML
    $response = new Response();
    $params = array(
        'src' => $to_number, //Sender's phone number
        'dst' => $from_number, //Receiver's phone Number
        'type' => "sms",
        'callbackUrl' => "https://www.foo.com/sms_status/",
        'callbackMethod' => "POST"
    );
    $message_body = "Thank you, we have received your request"; //The text to be sent
    $response->addMessage($message_body, $params);

    Header('Content-type: text/xml');
    echo($response->toXML()); // Returns the XML
?>
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
import static spark.Spark.*;
import com.plivo.api.xml.Message;
import com.plivo.api.xml.Response;

public class Reply {
    public static void main(String[] args) {
        get("/reply_sms", (request, response) -> {
            // Sender's phone number
            String from_number = request.queryParams("From");
            // Receiver's phone number - Plivo number
            String to_number = request.queryParams("To");
            // The text which was received
            String text = request.queryParams("Text");
            response.type("application/xml");
            // Print the message
            System.out.println(from_number + " " + to_number + " " + text);

            // send the details to generate an XML
            Response res = new Response().children(
                    // from_number is passed as destination,to_number is passed as source and text
                    // is being passed
                    new Message(to_number, from_number, "Thank you, we have received your request")
                            .callbackMethod("POST").callbackUrl("http://foo.com/sms status/").type("sms"));
            // Returns the XML
            return res.toXmlString();
        });
    }
}
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
package main

import (
	"net/http"

	"github.com/go-martini/martini"
	"github.com/plivo/plivo-go/xml"
)

func main() {
	m := martini.Classic()
	m.Get("/", func(w http.ResponseWriter, r *http.Request) string {
		w.Header().Set("Content-Type", "application/xml")
		fromnumber := r.FormValue("From")
		tonumber := r.FormValue("To")
		text := r.FormValue("Text")
		print("Message Received - ", fromnumber, " ", tonumber, " ", text)

		response := xml.ResponseElement{
			Contents: []interface{}{
				new(xml.MessageElement).
					SetCallbackMethod("POST").
					SetCallbackUrl("http://foo.com/sms status/").
					// Number from which the SMS needs to be sent.
					SetDst(tonumber).   // Sender's phone number
					SetSrc(fromnumber). // The receiver's number.
					SetType("sms").
					SetContents("Thanks, we have received your request"),
			},
		}
		print(response.String())
		return response.String()
	})
	m.Run()
}
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
37
38
39
40
41
42
43
using Nancy;
using System;
using System.Collections.Generic;
using System.Reflection;
using Plivo.XML;

namespace NancyStandalone
{
  public class FunctionsModule : NancyModule
  {
    public FunctionsModule()
    {
      Post("/reply_sms", parameters =>
      {
          // Sender's phone number
          String from_number = Request.Form["From"];
          // Receiver's phone number
          String to_number = Request.Form["To"];
          // The text which was received
          String text = Request.Form["Text"];
          // Print the message
          Console.WriteLine("Message received - From: {0}, To: {1}, Text: {2}", from_number, to_number, text);

          Plivo.XML.Response resp = new Plivo.XML.Response();
          // Generate the Message XML
          Plivo.XML.Response resp = new Plivo.XML.Response();
          resp.AddMessage("Thank you, we have received your request",
          new Dictionary<string, string>()
          {
            {"src", to_number},
            {"dst", from_number} ,
            {"type", "sms"},
            {"callbackUrl", "http://foo.com/sms_status/"},
            {"callbackMethod", "POST"}
            });
            var output = resp.ToString();
            var res = (Nancy.Response)output;
            res.ContentType = "application/xml";
            return res;
        };
      }
    }
}

Next Step

Learn how to forward an incoming 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. Receive an SMS
  6. Reply to an Incoming SMS
  7. Forward an Incoming SMS
  8. Get Details of all Messages
  9. Get Details of a Single Message
  10. Handling SMS Delivery Reports
  11. Forward SMS to Email