Reject an incoming call

When you receive a call on your Plivo number, you can reject it using Plivo XML. In this example, when an incoming call is received, we will check if that number has been blacklist. If yes, we will hangup immediatly using the Hangup XML on the call and if no, we will return a Speak XML

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 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 example.com. Below is a snippet to set up a route on your webserver. Lets call it, reject_caller. Now when we send an HTTP request to example.com/reject_caller this route will be invoked. You will now have to configure this URL in your Plivo application.

Note: For PHP, the route will be example.com/reject_caller.php.
  1. Copy the relevant code below into a text file and save it. Lets call it, reject_caller.
  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
from flask import Flask, Response
import plivo, plivoxml

app = Flask(__name__)

@app.route("/reject_call/", methods=['GET','POST'])
def hangup():
    # Generate a Hangup XML to reject an incoming call.
    params = {
        'reason': 'rejected', # Specify the reason for hangup
    }
    response = plivoxml.Response()
    response.addHangup(**params)
    print response.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
require 'rubygems'
require 'sinatra'
require 'plivo'
include Plivo

# Set te caller ID using Dial XML

get '/reject_call/' do
    r = Response.new()
    params = {
        'reason' => 'rejected', # Specify the reason for hangup
    }    
    r.addHangup(params)    
    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
var express = require('express');
var plivo = require('plivo');
var fs = require('fs');
var app = express();

app.get('/reject_call/', function(req, res){
    console.log('GET /');

    // Generate a Hangup XML to reject an incoming call.

    var response = plivo.Response();

    var hangup_params = {
        'reason': 'rejected'
    };

    response.addHangup(hangup_params);

    res.writeHead(200, {'Content-Type': 'text/xml'});
    res.end(response.toXML());
});

var port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port);
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php
    require 'vendor/autoload.php';
    use Plivo\Response;
    $r = new Response();
    // Generate a Hangup XML
    $params = array(
            'reason' => 'rejected', # Specify the reason for hangup
        );

    $r->addHangup($params);
    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
package plivoexample;

import java.io.IOException;

import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.Hangup;
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;

public class hangup extends HttpServlet {
    private static final long serialVersionUID = 1L;    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        PlivoResponse response = new PlivoResponse();
        Hangup hang = new Hangup();
        hang.setReason("rejected");
        
        try {
            response.append(hang);
            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 hangup()),"/reject_call/");
        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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using RestSharp;
using Plivo.XML;
using Nancy;

namespace hangup
{
    public class Program : NancyModule
    {
        public Program()
        {
            Get["/reject_call/"] = x =>
            {
                Plivo.XML.Response resp = new Plivo.XML.Response();
                // Add Hangup XML Tag
                resp.AddHangup(new Dictionary<string, string>() 
                {
                    {"reason","rejected"}, // Specify the reason for hangup
                });    

                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 Reject Call. Enter your server URL (e.g., http://example.com/reject_caller 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.

Create Text to Speech 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.

SMS Phone Number Search

Test it out

Sample XML

Sample output when From number is in blacklist

<Response>
    <Hangup reason="rejected"/>
</Response>

Next Step

Learn how to Get Details of All Calls

  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