Number Insight Advanced Async API

You use Number Insight Advanced Async API to retrieve roaming information about phone number. Number Insight Advanced Async API also returns the same information as Number Insight Standard API.

Number Insight Advanced API is an asynchronous, easy-to-use web service. For any phone number you can:

  • Retrieve the international and local format.
  • Know the country it is registered in.
  • See if it is for a mobile phone, landline, virtual number (Google Voice, Skype etc.) or a Premium/Toll-Free number.
  • Identify the mobile country code and mobile network code (MNCMCC) for a mobile phone number for routing outbound communication.
  • Find out if it is ported.
  • Learn if the phone number is reachable.
  • Discover which network phone number is using when roaming.
  • Confirm that your user's IP address is in the same location as their mobile phone.

Note: check the legislation in your country and validate that you can save user information about roaming locally.

The workflow for Number Insight Advanced Async API API is:

workflow_number_insight_advanced_api
  1. Request information about a phone number.
  2. Receive a response and see status of your request.
  3. Handle the return parameters that contain the information you requested.

Implementing the Number Insight Advanced Async API workflow

To use Nexmo Number Insight Advanced Async API:

  1. Ask for information about a phone number using the request.
    <?php
    $url = 'https://api.nexmo.com/ni/advanced/async/json?' . http_build_query([
            'api_key' => 'API_KEY',
            'api_secret' => 'API_SECRET',
            'number' => '441632960960',
            'callback' => 'URL_TO_YOUR_WEBHOOK'
        ]);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    
    import urllib
    import urllib2
    
    params = {
        'api_key': 'API_KEY',
        'api_secret': 'API_SECRET',
        'number' : '441632960960',
        'callback' : 'URL_TO_YOUR_WEBHOOK'
    }
    
    url = 'https://api.nexmo.com/ni/advanced/async/json?' + urllib.urlencode(params)
    
    request = urllib2.Request(url)
    request.add_header('Accept', 'application/json')
    response = urllib2.urlopen(request)
    
    require "net/http"
    require "uri"
    
    uri = URI.parse("https://api.nexmo.com/ni/advanced/async/json")
    params = {
      'api_key' => 'API_KEY',
      'api_secret' => 'API_SECRET',
      'number' => '441632960960',
      'callback' => 'URL_TO_YOUR_WEBHOOK'
      }
    
    response = Net::HTTP.post_form(uri, params)
    
    puts response.body
    
    var https = require('https');
    
    var data = JSON.stringify({
     api_key: 'API_KEY',
     api_secret: 'API_SECRET',
     number: '441632960960',
     callback: 'URL_TO_YOUR_WEBHOOK'
    });
    
    var options = {
      host: 'api.nexmo.com',
      path: '/ni/advanced/async/json',
      port: 443,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(data)
      }
    };
    
    var req = https.request(options);
    
    req.write(data);
    req.end();
    
    var responseData = '';
    req.on('response', function(res){
     res.on('data', function(chunk){
       responseData += chunk;
     });
    
     res.on('end', function(){
       console.log(JSON.parse(responseData));
     });
    });
    
  2. Receive a response and check the response codes to ensure that you sent the request to Nexmo correctly.
    <?php
    //Decode the json object you retrieved when you ran the request.
    $decoded_response = json_decode($response, true);
    
    if ($decoded_response['status'] == '0') {
      error_log("Success " . $decoded_response['request_id']);
    } else {
      error_log("Error {$decoded_response['status']} {$decoded_response['error_text']}");
    }
    
    import json
    
    #Using the response object from the request
    if response.code == 200 :
        data = response.read()
        #Decode JSON response from UTF-8
        decoded_response = json.loads(data.decode('utf-8'))
        # Check if your messages are succesful
        if decoded_response["status"] == '0':
            print "Success " + decoded_response['request_id']
        else:
            print "Error " + decoded_response["status"] + ': ' + decodedResponse['error_text']
    else :
        #Check the errors
        print "unexpected http {code} response from nexmo api". response.code
    
    require 'json'
    
    #Decode the json object from the response object you retrieved from the request.
    if response.kind_of? Net::HTTPOK
      decoded_response = JSON.parse(response.body )
    
      if decoded_response["status"] == '0'
        p "Success: " + decoded_response["request_id"]
      else
        p "message has error " + decoded_response["status"].to_s  \
          + " " + decoded_response["error_text"]
      end
    else
      puts response.code + " error sending message"
    end
    
    //Decode the json object you retrieved when you ran the request.
    
    var decoded_response = JSON.parse(responseData);
    
    if (decoded_response.status === '0') {
      console.log('Success ' + decoded_response.request_id );
    }
    else {
      console.log('Error ' + responseData);
    }
    
  3. Receive the return parameters at your webhook endpoint with the results of your Number Insight API request.
    <?php
    
    $decoded_response = json_decode(file_get_contents('php://input'), true);
    
    if ($decoded_response['status'] == 0) {
        error_log("Success " . $decoded_response['request_id']);
        error_log( $decoded_response['international_format_number']
                . ' is using ' . $decoded_response['current_carrier']['name'] );
        error_log( 'Their home networks is: '
                . $decoded_response['original_carrier']['name'] );
    } else {
        error_log("Error {$decoded_response['status']} {$decoded_response['error_text']}");
    }
    
    header("Status: 200");
    
    ?>
    
    #To run this code, replace the MyHandler in
    #https://wiki.python.org/moin/BaseHttpServer With the following code,
    from urlparse import urlparse, parse_qs
    import json
    class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
        def do_POST(s):
            """Parse parameters in the POST request"""
            content_len = int(s.headers.getheader('content-length', 0))
            post_body = s.rfile.read(content_len)
            decoded_response = json.loads(post_body.decode('utf-8'))
            # Check if your messages are succesful
            if decoded_response["status"] == 0:
                    print "Success for: " + decoded_response['request_id']
    
            """Tell Nexmo that you have recieved the GET request."""
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
        def do_Get(s):
            """Tell Nexmo that you have recieved the GET request."""
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
    
    require 'socket'
    require 'uri'
    require 'json'
    
    def handle_delivery_receipt(request_body)
    #Parse the parameters and check if the message was delivered
      decoded_response = JSON.parse(request_body )
    
      if decoded_response["status"] == 0
        p "Success" + decoded_response["request_id"] + "\n"
        p decoded_response['international_format_number'] + ' is in ' \
          + decoded_response['country_name']
        p decoded_response['international_format_number'] + ' is using ' \
          + decoded_response['current_carrier']['name']
        p 'Their home networks is: ' + decoded_response['original_carrier']['name']
      else
        p "message has error " + decoded_response["status"].to_s + " " + decoded_response["error_text"]
      end
    end
    
    # Initialize a TCPServer
    server = TCPServer.new('', 9999)
    
    # Wait for connections
    loop do
      # Wait until a client connects
      socket = server.accept
    
      method, path = socket.gets.split
      headers = {}
      while line = socket.gets.split(' ', 2)              # Collect HTTP headers
        break if line[0] == ""                            # Blank line means no more headers
        headers[line[0].chop] = line[1].strip             # Hash headers by type
      end
      data = socket.read(headers["Content-Length"].to_i)
    
      handle_delivery_receipt(data)
    
      # Return the 200 so Nexmo does not send the DLR to you repeatedly
      resp = "Thank you"
      headers = ["HTTP/1.1 200 OK",
                 "Content-Type: text/html; charset=iso-8859-1",
                 "Content-Length: #{resp.length}\r\n\r\n"].join("\r\n")
      socket.puts headers
      socket.puts resp
      # Close the socket, terminating the connection
      socket.close
    end
    
    var http = require('http') // http module
    var url = require("url")
    
    // create the http server
    http.createServer(function (request, response) {
      //Handle a POST request from Number Insight Advanced
      if(request.method=='POST') {
          //Parse the return parameters
           var returnParameters = '';
    
          request.on('data', function (data) {
              returnParameters += data;
          });
    
          request.on('end', function () {
               var decoded_response = JSON.parse(returnParameters);
    
               if (decoded_response.status === 0) {
                 console.log('Success ' + decoded_response.request_id );
                 console.log( decoded_response.international_format_number + ' is using '
                   + decoded_response.current_carrier.name );
                 console.log( 'Their home networks is: '
                   + decoded_response.original_carrier.name );
               }
               else {
                 console.log('Error ' + decoded_response.status  + ': ' +  decoded_response.error_text );
               }
          });
      }
      else if(request.method=='GET') {
          //Do something for a GET request
      }
      //Send the 200 ok to Nexmo so you don't get sent the DLR again.
      response.writeHead(200, {"Content-Type": "text/html"});
      response.end();
    
    }).listen(8888);
    

Note: remember to send return 200 ok when you receive the Number Insight API Return Parameters.

Previous   Next