Set Dynamic Caller ID

Caller IDs can be a powerful method of branding and ensuring that the receiver sees a phone number that is most relevant to them. For example, studies have shown that calls from local phone numbers provide a much higher answer rate than calls from toll-free phone numbers. With Plivo’s APIs and large phone number inventory, you can instantly and dynamically set your caller IDs to phone numbers that can receive phone calls locally and thus render a higher conversion rate. There is no need to wait for additional phone lines to be installed because Plivo phone numbers are instantly provisioned and ready for use.

By default, Plivo will show the current caller phone number as the caller ID. However, there are two ways to set the caller id.

  1. Set the CallerID attribute in Dial XML which will make the outbound call. Use this method if you have already initiated an outbound call with an API or are receiving an incoming call.
  2. Set the From parameter when making outcound calls using the Call API. Use this method if you intend to initiate an outbound call.

Both methods are explained below.

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 (optional).
  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.

Option 1: Using Dial XML

Let’s assume your web server is located at www.example.com. Below is a snippet to set up a route on your webserver.

  1. Copy the code below into a text file and save it as dial with the appropriate file extention for your code (e.g., .py for Python or .rb for Ruby, etc.).
  2. Now when we send an HTTP request to www.example.com/dial/ this route will be invoked.

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

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

app = Flask(__name__)

@app.route('/dial/', methods=['GET','POST'])
def dial_id():
    clid = request.values.get('CLID')
    to_number = "2222222222"
    # Set the caller ID using Dial XML
    params = {
        'callerId': clid
    }

    r = plivoxml.Response()
    d = r.addDial(**params)
    d.addNumber(to_number)
    print r.to_xml()
    return Response(str(r), mimetype='text/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
require 'rubygems'
require 'sinatra'
require 'plivo'
include Plivo

# Set te caller ID using Dial XML

get '/dial/' do
    clid = params[:CLID]
    number = '2222222222'
    r = Response.new()
    params = {
        'callerId' => clid
    }
    d = r.addDial(params)
    d.addNumber(number)

    puts r.to_xml()
    content_type 'text/xml'
    return r.to_s()
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
var plivo = require('plivo');
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('/dial/', function(request, response) {
  var clid = request.query.CLID || request.body.CLID;
  var to_number = "2222222222";
  var params = {
    callerId: clid
  };

  var r = plivo.Response();
  var d = r.addDial(params);
  d.addNumber(to_number);
  console.log (r.toXML());
  response.set({'Content-Type': 'text/xml'});
  response.send(r.toXML());
});

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
<?php
    require 'vendor/autoload.php';
    use Plivo\Response;

    $clid = $_REQUEST["CLID"];
    $number = '2222222222';
    # Set the caller ID using Dial XML
    $params = array(
        'callerId' => $clid # Caller ID
    );

    $r = new Response();
    $d = $r->addDial($params);
    $d->addNumber($number);
    Header('Content-type: text/xml');
    echo($r->toXML());
?>
 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
package plivoexample;

import java.io.IOException;

import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.Dial;
import com.plivo.helper.xml.elements.Number;
import com.plivo.helper.xml.elements.PlivoResponse;

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 dialId extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        PlivoResponse response = new PlivoResponse();
        Dial dial = new Dial();
        String clid = req.getParameter("CLID");
        dial.setCallerId(clid);
        Number num = new Number("2222222222");

        try {
            dial.append(num);
            response.append(dial);
            System.out.println(response.toXML());
            resp.addHeader("Content-Type", "text/xml");
            resp.getWriter().print(response.toXML());;
        } catch (PlivoException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String port = System.getenv("PORT");
        if(port==null)
            port ="8000";
        Server server = new Server(Integer.valueOf(port));
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        context.addServlet(new ServletHolder(new dialId()),"/dial/");
        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
28
29
30
31
32
33
34
35
using System;
using System.Collections.Generic;
using System.Diagnostics;
using RestSharp;
using Plivo.XML;
using Nancy;

// Set the caller ID using Dial XML

namespace dial_id
{
    public class Program : NancyModule
    {
        public Program()
        {
            Get["/dial/"] = x =>
            {
                Plivo.XML.Response resp = new Plivo.XML.Response();
                String clid = Request.Form["CLID"];
                // Generate Dial XML
                Plivo.XML.Dial dial = new Plivo.XML.Dial(new Dictionary<string, string>() {
                    { "callerId", clid }
                });
                dial.AddNumber("2222222222", new Dictionary<string, string>() {});
                resp.Add(dial);
                Debug.WriteLine(resp.ToString());

                var output = resp.ToString();
                var res = (Nancy.Response)output;
                res.ContentType = "text/xml";
                return res;
            };
        }
    }
}

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 Dynamic Dial.
  3. Enter your server URL with your caller ID appended (e.g., http://www.example.com/dial/?CLID=14152223333) in the Answer URL and Hangup URL fields.
  4. Set both methods as POST.
  5. Click on Create to save your application.

    Advanced Hack: you can also create, edit, and delete Plivo Applications through the Application API.

Create Dynamic Caller ID 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 Dynamic Dial (name of the app) from the Plivo App dropdown list.
  3. Click on ‘Update’ to save.

Create Dynamic Caller ID Application

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

Phone Number Search

Option 2: Using Call API

  1. Copy the relevant code below into a text file and save it with the appropriate file extention for your code (e.g., .py for Python or .rb for Ruby, etc.).
  2. Replace Your_AUTH_ID and Your_AUTH_TOKEN with the Auth ID and Auth Token found on your Plivo dashboard.
  3. Add your from (source) phone number. This will show up as your Caller ID. Be sure that all phone numbers include country code, area code, and phone number without spaces or dashes (e.g., 14153336666).
  4. Add your to (destination) phone numbers. These are the phone numbers you wish to call to. To place calls in bulk, separate your destination phone numbers with the “<” character (e.g., 14156667777<14157778888<14158889999). Be sure that all phone numbers include country code, area code, and phone number without spaces or dashes (e.g., 14153336666).

    Note: If you are using a trial account, your destination number needs to be verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

  5. Edit the answer_url field with a URL to be requested by Plivo when the call is answered which tells Plivo what to do with the call.
  6. Edit the answer_method field with either GET or POST.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import plivo

# Set the caller ID using Call API

auth_id = "Your_AUTH_ID"
auth_token = "Your_AUTH_TOKEN"
p = plivo.RestAPI(auth_id, auth_token)

params = {
    'to': '2222222222', # The phone numer to which the call will be placed
    'from' : '1111111111', # The phone number to be used as the caller id
    'answer_url' : "http://static.plivo.com/answer.xml", # The URL invoked by Plivo when the outbound call is answered
    'answer_method' : "GET", # The method used to request the answer_url
}

response = p.make_call(params)
print str(response)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
require 'plivo'
include Plivo

# Set the caller ID using Call API

AUTH_ID = "Your_AUTH_ID"
AUTH_TOKEN = "Your_AUTH_TOKEN"
p = RestAPI.new(AUTH_ID, AUTH_TOKEN)

params = {
    'to' => '2222222222', # The phone number to which the call will be placed
    'from' => '1111111111', # The phone number to be used as the caller id
    'answer_url' => 'http://static.plivo.com/answer.xml', # The URL invoked by Plivo when the outbound call is answered
    'answer_method' => 'GET', # The method used to request the answer_url
}

response = p.make_call(params)
print response
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var plivo = require('plivo');
var p = plivo.RestAPI({
    "authId": "Your_AUTH_ID",
    "authToken": "Your_AUTH_TOKEN",
});
var params = {
    'to': '2222222222', // The phone numer to which the call will be placed
    'from' : '1111111111', // The phone number to be used as the caller id
    'answer_url' : "http://static.plivo.com/answer.xml", // The URL invoked by Plivo when the outbound call is answered
    'answer_method' : "GET", // The method used to request the answer_url
};

p.make_call(params, function (status, response) {
    console.log('Status: ', status);
    console.log('API Response:\n', response);
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php
    require 'vendor/autoload.php';
    use Plivo\RestAPI;
    # Set the caller ID using Call API
    $auth_id = "Your_AUTH_ID";
    $auth_token = "Your_AUTH_TOKEN";
    $p = new RestAPI($auth_id, $auth_token);
    $params = array(
        'to' => '2222222222', # The phone numer to which the all has to be placed
        'from' => '1111111111', # The phone number to be used as the caller id
        'answer_url' => "http://static.plivo.com/answer.xml", # The URL invoked by Plivo when the outbound call is answered
        'answer_method' => "GET", # The method used to call the answer_url
    );
    $response = $p->make_call($params);
    print_r ($response);
?>
 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
package com.plivo.test;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;
import com.plivo.helper.api.client.*;
import com.plivo.helper.api.response.call.Call;
import com.plivo.helper.exception.PlivoException;

public class App {
    public static void main(String[] args) throws IllegalAccessException {
        String auth_id = "Your_AUTH_ID";
        String auth_token = "Your_AUTH_TOKEN";
        RestAPI api = new RestAPI(auth_id, auth_token, "v1");

        LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
        parameters.put("to","2222222222"); // The phone numer to which the all has to be placed
        parameters.put("from","1111111111"); // The phone number to be used as the caller id
        parameters.put("answer_url","http://static.plivo.com/answer.xml"); // The URL invoked by Plivo when the outbound call is answered
        parameters.put("answer_method","GET"); // method to invoke the answer_url

        try {
           Call resp = api.makeCall(parameters);
           System.out.println(resp);
        } catch (PlivoException e) {
           System.out.println(e.getLocalizedMessage());
        }
    }
}
 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
// Set the caller ID using Call API

using System;
using System.Collections.Generic;
using RestSharp;
using Plivo.API;

namespace make_calls
{
    class Program
    {
        static void Main(string[] args)
        {
            RestAPI plivo = new RestAPI("Your_AUTH_ID", "Your_AUTH_TOKEN");

            // Make a call
            IRestResponse<Call> resp = plivo.make_call(new Dictionary<string, string>()
            {
                { "from", "1111111111" }, // The phone number to which the call has to be placed
                { "to", "2222222222" }, // The phone number to be used as the caller Id
                { "answer_url", "http://static.plivo.com/answer.xml" }, // The URL invoked by Plivo when the outbound call is answered
                { "answer_method","GET"} // The method used to invoke the answer_url
            });

            //Prints the response
            Console.Write(resp.Content);

            Console.ReadLine();
        }
    }
}

Sample Response

Using Dial XML the response will be:

<Response>
    <Dial callerId="1111111111">
        <Number>2222222222</Number>
    </Dial>
</Response>

Using the Call Api, the response will be:

(201, {
       u'message': u'call fired', 
       u'request_uuid': u'85b1d45d-bc12-47f5-89c7-ae4a2c5d5713', 
       u'api_id': u'ad0e27a8-9008-11e4-b932-22000ac50fac'
   }
)

Next Step

Learn how to Detect Answering Machines.

  1. Make an Outbound Call
  2. Play a Text-to-speech Message
  3. Connect Call to a Second Person
  4. Greet Caller by Name
  5. Play MP3/WAV Audio to Caller
  6. Hangup Using API
  7. Receive Incoming Call
  8. Forward Incoming Call
  9. Record Using API
  10. Screen Incoming Call
  11. Reject incoming call
  12. Get Details of all Calls
  13. Get Details of a single Call
  14. Get Details of Live Calls
  15. Build an IVR Phone Menu
  16. Conference Call
  17. Call Forward
  18. SIP Endpoint (Direct-Dial)
  19. Inbound Trunk
  20. Outbound Trunk