Forward Incoming Calls

    Call forwading can be very useful in any business work flow. For example, incoming calls can be dynamically routed to available agents, extensions, or departments that cater to the caller’s needs. In this tutorial, you will learn how to forward a received call to another phone number.

    Warning:  This tutorial requires understanding of  receiving an incoming call.

    Prerequisites

    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 calls. You can buy a Plivo phone number in over 20+ countries through the Buy Numbers tab on your Plivo account UI. Check the Voice 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.

    Set up a Web Server

    Let’s assume your web server is located at myvoiceapp.com. Below is a snippet to set up a route on your webserver. Let’s call it forward. Now when we send an HTTP request to myvoiceapp.com/forward this route will be invoked. You will now have to configure this URL in your Plivo application.

    Note: For PHP, the route will be `myvoiceapp.com/forward.php`
    1. Copy the relevant code below into a text file and save it. Let’s call it, forward.
      Note: Make sure to use the appropriate file extention for your code (e.g., forward.py for Python).
    2. Now that you have the code, you will need to expose your server to the public Internet. This way Plivo will know where to find your app when a particular phone number is dialed. Moving forward, we will assume that your app is available at myvoiceapp.com.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    from flask import Flask, request, Response
    from plivo import plivoxml
    
    app = Flask(__name__)
    
    @app.route("/forward/", methods=['GET','POST'])
    def forward():
        from_number = request.values.get('From')
        response = plivoxml.ResponseElement()
        response.add(
            plivoxml.DialElement(caller_id=from_number)
            .add(plivoxml.NumberElement('+15671234567')))
        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
    
    require "sinatra"
    require 'plivo'
    
    include Plivo
    include Plivo::XML
    
    get "/forward_call" do
    	from_number = params[:From]
    	response = Response.new
    	params = {
          'callerId' => from_number
    	}
    	dial = response.addDial(params)
    	first_number = "+15671234567"
    
    	dial.addNumber(first_number)
    	xml = PlivoXML.new(response)
    	content_type "application/xml"
    	return xml.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
    
    var plivo = require('plivo');
    var express = require('express');
    var app = express();
    
    app.set('port', (process.env.PORT || 5000));
    
    app.all('/forward_calls/', function(request, response) {
        var from_number = request.body.From || request.query.From;
        var r = plivo.Response(); 
        var params = {
            'callerId': from_number
        };
        var dial = r.addDial(params);
        var number = "+15671234567";
        dial.addNumber(number);
        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\XML\Response;
    
        $from_number = $_REQUEST["From"];
        $response = new Response(); 
        $params = array(
            'callerId'=> $from_number
        );
        $dial = $response->addDial($params);
        $number = "+15671234567";
        
        $dial->addNumber($number);
    
        Header('Content-type: text/xml');
        echo($response->toXML());
    ?>
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    import static spark.Spark.*;
    import com.plivo.api.xml.Dial;
    import com.plivo.api.xml.Number;
    import com.plivo.api.xml.Response;
    
    public class forwardcall {
        public static void main(String[] args) {
            get("/forward", (request, response) -> {
                String from_number = request.queryParams("From");
                response.type("application/xml");
                Response res = new Response()
                        .children(
                        new Dial()
                                .callerId(from_number)
                                .children(
                                        new Number("+15671234567")
                                )
                        );
                // 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
    
    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")
    		//send the details to generate an XML
    		response := xml.ResponseElement{
    			Contents: []interface{}{
    
    				new(xml.DialElement).
    					SetCallerId(fromnumber).
    					SetContents([]interface{}{
    						new(xml.NumberElement).
    							SetContents("+15671234567"),
    					}),
    			},
    		}
    		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
    
    using System;
    using Plivo.XML;
    using System.Collections.Generic;
    using Microsoft.AspNetCore.Mvc;
    
    namespace Forwardcall
    {
        public class ForwardcallController : Controller
        {
            public IActionResult Index()
            {
                String from_number = Request.Query["From"];
                Plivo.XML.Response resp = new Plivo.XML.Response();
                Plivo.XML.Dial dial = new Plivo.XML.Dial(new
                    Dictionary<string, string>(){
                    {"callerId",from_number}
                });
    
                dial.AddNumber("+15551234567",
                    new Dictionary<string, string>() { });
                resp.Add(dial);
    
                var output = resp.ToString();
                Console.WriteLine(output);
    
                return this.Content(output, "text/xml");
            }
        }
    }
    

    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. Let’s call it Forward Call. Enter your server URL (e.g., http://myvoiceapp.com/forward) in the Answer 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.

    Plivo 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 Forward Call (name of the app) from the Plivo App dropdown list.
    3. Click on Update to save.

    Create Text to Speech Application

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

    Voice Phone Number Search

    Test and validate

    When you make a call to your Plivo number, the call will be forwarded to the number specified in your code.

    Forward incoming calls to a Plivo SIP Endpoint

    In this section, We’ll walk you through setting up a call forwarding app to forward the incoming call to a Plivo number to a Plivo SIP Endpoint. If you are new to Plivo SIP Endpoints, you should read more about it here.

    To get started, below are the prequisities:

    Create an endpoint

    • Create an endpoint on Plivo with a username and a password. Create Endpoint
    • Make sure you attach the built-in direct_dial application.
    • Plivo will append random numbers to your endpoint username. Make a note of your endpoint username.

    Host your XML

    You need to host a static URL which returns a Dial XML when Plivo requests the URL.

    • Create a file with the following contents. Append phone.plivo.com to your endpoint username and change the SIP URI “sip:yoda12312312@phone.plivo.com” in the below example to your endpoint’s SIP URI. Make sure your URI starts with “sip:”
    <Response>
    <Dial callerId="18004321321">
        <User>sip:yoda12312312@phone.plivo.com</User>
    </Dial>
    </Response>
    • Host your file on github or Dropbox
    • Create a Plivo Application and set the Answer URL as the URL of your static file. Create Application
    • Open the numbers page and click on the number to link the application you created in the above step
    • Choose the application from the dropdown and click on Update Number Edit
    • If you don’t have a number, go to the Buy Number page to purchase a Plivo phone number. Voice Phone Number Search

    Register your endpoint

    Register your endpoint using a softphone, hardware phone, Browser SDK or mobile SDK.

    Test and validate

    When you make a call to your Plivo number, the call will be forwarded to the Plivo endpoint specified in your code.

    Sample XML

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