Your application must use Plivo XML to control SMS messages synchronously. You can use the Message XML element to send an SMS message in different scenarios — for example, to reply to or forward an incoming message.
Let’s look at an example to see how Plivo XML works. Consider a use case where you want to reply to an incoming SMS message.
This diagram outlines the message flow for a typical case where XML is used:
An incoming SMS message is received on a Plivo number and is connected through the Plivo SMS Platform. Plivo then looks up the message_url
configured for the Application that’s linked to the Plivo number and makes a request to that URL. Your web application at that URL should return an XML document that provides instructions to the Plivo API on how the SMS message should be handled. In this case, it should return a message XML document to reply to the incoming SMS message.
In this example, Plivo works like an HTTP client that receives a message and and makes a request to your web application for instructions on how to handle the message. By default, XML requests to your application are made via POST
, but you can configure Plivo to make XML requests to your application via HTTP GET
or POST
methods by changing the related configuration parameter.
You can set configuration parameters when sending out a message. To deal with incoming messages, Plivo uses the configuration attached to the application that’s linked to the phone number on which your incoming message is received.
When Plivo makes a synchronous HTTP request to your application, the API expects an XML document in response. Plivo also sends a few parameters with the HTTP request that your application can act upon before responding.
To receive a message, your Plivo Application must have a message_url
. Plivo expects an XML response from this URL after it sends the parameters below. Only a Message
XML element can be sent as a response from the message URL. See the Message XML reference page for more information.
From | The source number of the message. |
To | The number to which the message was sent. |
Type | The type of the message. Allowed value: sms |
Text | The message content. |
MessageUUID | A unique ID for the message. |
All requests made by Plivo to your server URLs consist of X-Plivo-Signature-V2
and X-Plivo-Signature-V2-Nonce
HTTP headers. To validate a request and to verify that the request to your server originated from Plivo, you must generate a signature at your end and compare it with X-Plivo-Signature-V2
parameter in the HTTP header to check whether they match. Read more about signature validation.
Methods to compute and verify X-Plivo-Signature-V2 are available in the latest server SDKs. Choose the SDK for the programming language of your choice to see how to use these methods.
uri string | The callback that you want to validate. Allowed values: answer_url, message_url, callback_url, action_url, hangup_url |
X-Plivo-Signature-V2-Nonce string | Random numeric digits posted to the callback_url, used for validation purpose. |
X-Plivo-Signature-V2 or X-Plivo-Signature-Ma-V2 string | Random alphanumeric characters used for validation. You can get this from the relevant event details posted to your callback. See note below. |
auth_token string | Your account Auth Token, which you can find on the Overview page of the Plivo console. |
You can either use X-Plivo-Signature-V2 or X-Plivo-Signature-Ma-V2 to validate the signature.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from flask import Flask, request, make_response, url_for
import plivo
app = Flask(__name__)
@app.route('/receive_sms/', methods =['GET','POST'])
def signature():
signature = request.headers.get('X-Plivo-Signature-V2')
nonce = request.headers.get('X-Plivo-Signature-V2-Nonce')
uri = url_for('signature', _external=True)
auth_token = "<auth_token>"
output = plivo.utils.validate_signature(uri,nonce,signature,auth_token)
print(output)
from_number = request.values.get('From') # Sender's phone numer
to_number = request.values.get('To') # Receiver's phone number - Plivo number
text = request.values.get('Text') # The text which was received
print('Message received - From: %s, To: %s, Text: %s' %(from_number, to_number, text))
return "Text received"
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Was this code helpful
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
require 'sinatra'
require 'rubygems'
require 'plivo'
include Plivo
require 'uri'
get '/receive_sms/' do
auth_token = "<auth_token>"
signature = request.env["HTTP_X_PLIVO_SIGNATURE_V2"]
nonce = request.env["HTTP_X_PLIVO_SIGNATURE_V2_NONCE"]
url = request.url
uri = (url.split("?"))[0]
output = Plivo::Utils.valid_signature?(uri,nonce,signature,auth_token)
puts output
from_number = params[:From]# The phone number of the person who sent the SMS
to_number = params[:To]# Your Plivo number that will receive the SMS
text = params[:Text]# The text which was received on your Plivo number
puts "Message received from #{from_number} : #{ text }"
end
Was this code helpful
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
var plivo = require('plivo');
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(express.urlencoded({ extended: true }))
app.all('/receive_sms/', function(req, res) {
var auth_token = ('<auth_token>');
var signature = req.get('X-Plivo-Signature-V2');
var nonce = req.get('X-Plivo-Signature-V2-Nonce');
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
var from_number = req.body.From;// Sender's phone number
var to_number = req.body.To;// Receiver's phone number - Plivo number
var text = req.body.Text;// The text which was received
var output = plivo.validateSignature(fullUrl, nonce, signature, auth_token)
console.log(output);
console.log ('From : ' + from_number + ' To : ' + to_number + ' Text : ' + text);
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Was this code helpful
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
require 'vendor/autoload.php';
use Plivo\Util\signatureValidation;
$auth_token = "<auth_token>";
$signature = $_SERVER["HTTP_X_PLIVO_SIGNATURE_V2"];
$nonce = $_SERVER["HTTP_X_PLIVO_SIGNATURE_V2_NONCE"];
$url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$uri = explode('?',$url);
$uri1 = $uri[0];
$SVUtil = new signatureValidation();
$output = $SVUtil->validateSignature($uri1,$nonce,$signature,$auth_token);
var_export($output);
$from_number = $_REQUEST["From"];// Sender's phone numer
$to_number = $_REQUEST["To"];// Receiver's phone number - Plivo number
$text = $_REQUEST["Text"];// The SMS text message which was received
echo("Message received from $from_number : $text");
?>
Was this code helpful
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package plivoexample;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.plivo.api.util.Utils;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
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;
import com.plivo.helper.util.*;
public class validateSignature extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String auth_token = "<auth_token>";
String signature = req.getHeader("X-Plivo-Signature-V2");
String nonce = req.getHeader("X-Plivo-Signature-V2-Nonce");
String url = req.getRequestURL().toString();
try {
Boolean isValid = XPlivoSignature.verify(url, nonce, signature, auth_token);
System.out.println("Valid : " + isValid);
} catch (PlivoException e) {
e.printStackTrace();
}
String from_number = req.getParameter("From");
String to_number = req.getParameter("To");
String text = req.getParameter("Text");
System.out.println("From : " + from_number + " To : " + to_number + " Text : " + text);
}
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 validateSignature()),"/receive_sms");
server.start();
server.join();
}
}
Was this code helpful
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using RestSharp;
using Plivo.Utilities;
using Nancy;
namespace validateSignature
{
public class Program : NancyModule
{
public Program()
{
Get["/receive_sms/"] = x =>
{
IEnumerable<string> signature = Request.Headers["X-Plivo-Signature-V2"];
String[] sign = (String[])signature;
String actualsignature = sign[0];
IEnumerable<string> nonce = Request.Headers["X-Plivo-Signature-V2-Nonce"];
String[] key = (String[])nonce;
String actualnonce = key[0];
String auth_token = "<auth_token>";
String url = Request.Url.SiteBase + Request.Url.Path;
bool valid = Plivo.Utilities.XPlivoSignatureV2.VerifySignature(url, actualnonce, actualsignature, auth_token);
Debug.WriteLine("Valid : " + valid);
String from_number = Request.Query["From"];
String to_number = Request.Query["To"];
String text = Request.Query["Text"];
Debug.WriteLine("From : {0}, To : {1}, Text : {2}", from_number, to_number, text);
Console.ReadLine();
return "OK";
};
}
}
}
Was this code helpful
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
package main
import (
"fmt"
"net/http"
"github.com/plivo/plivo-go/v7"
)
func handler(w http.ResponseWriter, r *http.Request) {
originalurl := "https://" + r.Host + r.URL.Path
authToken := "<auth_token>"
signature := r.Header.Get("X-Plivo-Signature-V2")
nonce := r.Header.Get("X-Plivo-Signature-V2-Nonce")
fromnumber := r.FormValue("From")
tonumber := r.FormValue("To")
text := r.FormValue("Text")
response := plivo.ValidateSignatureV2(
originalurl,
nonce,
signature,
authToken,
)
fmt.Printf("Response: %#v\n", response)
print("Message Received - ", fromnumber, " ", tonumber, " ", text)
}
func main() {
http.HandleFunc("/receive_sms/", handler)
http.ListenAndServe(":8080", nil)
}
Was this code helpful
True
When your application gets initiated to send a message, Plivo makes an HTTP request to the message_url
, which is one of the mandatory parameters when sending a message.
message_url
should respond with an XML document that provides instructions to control the SMS.Content Type
of the response header, returned by the message_url
, must be set to text/xml
or application/xml
.The <Response>
element is the parent element of Plivo’s XML. All child elements must be nested within this element. Any other structure is considered invalid.
Child elements are proprietary Plivo elements and are case-sensitive. This means that using <message>
instead of <Message>
, for example, will result in an error. Attributes for the child elements are also case-sensitive and “camelCased.”
When Plivo receives an XML response, it executes the elements from top to bottom.
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message src="12023222222" dst="15671234567" type="sms" callbackUrl="http://foo.com/sms_status/" callbackMethod="POST">
Hi, Message from Plivo
</Message>
</Response>
Use the Message element to send a message during your call flow. For instance, if you want to send out an SMS notification when you receive an incoming call on your Plivo number, you can use the <Message>
element in your application.
To receive a message, you must set a message URL in your Plivo application via the API or in the Plivo console at Messaging > Applications.
Here are the attributes the Message element supports. You can modify the default behavior of each attribute by using the allowed values.
src string | Source number — for example, 12025550000. Must be a purchased, valid number. |
dst string | Destination number. Must be a valid number. To use bulk numbers, specify them separated by < — for example, 12025551111<12025552222. |
type string | Type of the message. Allowed values: sms |
callbackUrl string | A valid, reachable URL that Plivo notifies when a response is available and to which the response is sent. (Delivery reports) |
callbackMethod string | The method used to notify the callbackUrl. Allowed values: GET, POST |
1
2
3
4
5
6
7
8
9
10
11
12
from plivo import plivoxml
response = plivoxml.ResponseElement()
response.add(
plivoxml.MessageElement(
'Hi, this is a sample text',
src='+12025550000',
dst='+12025551111',
type='sms',
callback_url='https://<yourdomain>.com/sms_status/',
callback_method='POST'))
print(response.to_string())
Was this code helpful
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require rubygems
require plivo
include Plivo::XML
include Plivo::Exceptions
begin
response = Response.new
params = {
src: '+12025550000',
dst: '+12025551111',
type: 'sms',
callbackUrl: 'https://<yourdomain>.com/sms_status/',
callbackMethod: 'POST'
}
message_body = 'Hi, this is a sample text'
response.addMessage(message_body, params)
xml = PlivoXML.new(response)
puts xml.to_xml
rescue PlivoXMLError => e
puts 'Exception: ' + e.message
end
Was this code helpful
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var plivo = require('plivo');
var response = plivo.Response();
var params = {
'src': "+12025550000",
'dst': "+12025551111",
'type': "sms",
'callbackUrl': "https://<yourdomain>.com/sms_status/",
'callbackMethod': "POST"
};
var message_body = "Hi, this is a sample text";
response.addMessage(message_body, params);
console.log(response.toXML());
/*
Sample Output
<Response>
<Message src="12025550000" dst="12025551111" type="sms" callbackUrl="https://<yourdomain>.com/sms_status/" callbackMethod="POST">
Hi, this is a sample text
</Message>
</Response>
*/
Was this code helpful
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
<?php
require '../vendor/autoload.php';
use Plivo\XML\Response;
$response = new Response();
$params = array(
'src' => "+12025550000",
'dst' => "+12025551111",
'type' => "sms",
'callbackUrl' => "https://<yourdomain>.com/sms_status/",
'callbackMethod' => "POST"
);
$message_body = "Hi, this is a sample text";
$response->addMessage($message_body, $params);
Header('Content-type: text/xml');
echo($response->toXML());
/*
Sample Output
<Response>
<Message src="2025550000" dst="2025551111" type="sms" callbackUrl="https://<yourdomain>.com/sms_status/" callbackMethod="POST">
Hi, this is a sample text
</Message>
</Response>
*/
?>
Was this code helpful
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Example for xml - send an sms
package com.plivo.api.xml.samples.xml;
import com.plivo.api.exceptions.PlivoXmlException;
import com.plivo.api.xml.Message;
import com.plivo.api.xml.Response;
class SendAnSms {
public static void main(String[] args) throws PlivoXmlException {
Response response = new Response()
.children(
new Message("+12025550000", "+12025551111", "Hi, this is a sample text")
.callbackMethod("POST")
.callbackUrl("https://<yourdomain>.com/sms status/")
.type("sms")
);
System.out.println(response.toXmlString());
}
}
Was this code helpful
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
using System;
using System.Collections.Generic;
using Plivo.XML;
namespace Plivo
{
class MainClass
{
public static void Main(string[] args)
{
Plivo.XML.Response resp = new Plivo.XML.Response();
resp.AddMessage("Hi, this is a sample text",
new Dictionary<string, string>()
{
{"src", "+12025550000"},
{"dst", "+12025551111" } ,
{"type", "sms"},
{"callbackUrl", "https://<yourdomain>.com/sms_status/"},
{"callbackMethod", "POST"}
});
var output = resp.ToString();
Console.WriteLine(output);
}
}
}
//<Response>
// <Message src = "12025550000" dst="12025551111"
// type="sms" callbackUrl="https://<yourdomain>.com/sms_status/"
// callbackMethod="POST">
// Hi, this is a sample text
// </Message>
//</Response>
Was this code helpful
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Example for xml - message
package main
import "github.com/plivo/plivo-go/v7/xml"
func main() {
response := xml.ResponseElement{
Contents: []interface{}{
new(xml.MessageElement).
SetCallbackMethod("POST").
SetCallbackUrl("https://<yourdomain>.com/sms_status/").
SetDst("+12025551111").
SetSrc("+12025550000").
SetType("sms").
SetContents("Hi, this is a sample text"),
},
}
print(response.String())
}
Was this code helpful
This example XML document is used to send out an SMS message. Plivo sends a delivery report to the callback URL using the HTTP POST method.
<Response>
<Message src="12022220000" dst="12025551111" type="sms" callbackUrl="https://<yourdomain>.com/sms_status/" callbackMethod="POST">
Hi, this is a text message
</Message>
</Response>