Connect an inbound call

In this code snippet you see how to connect an inbound call to another person by making an outbound call.

Example

Replace the following variables in the example code:

KeyDescription
VONAGE_VIRTUAL_NUMBER

Your Vonage Number. E.g. 447700900000

VOICE_TO_NUMBER

The recipient number to call, e.g. 447700900002.

Prerequisites

npm install express

Write the code

Add the following to connect-an-inbound-call.js:

const Express = require('express');

const app = new Express();

const onInboundCall = (_, response) => {
  const ncco = [
    {
      action: 'connect',
      from: VONAGE_VIRTUAL_NUMBER,
      endpoint: [
        {
          type: 'phone',
          number: VOICE_TO_NUMBER,
        },
      ],
    },
  ];

  response.json(ncco);
};

app.get('/webhooks/answer', onInboundCall);

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

View full source

Run your code

Save this file to your machine and run it:

node connect-an-inbound-call.js

Prerequisites

Add the following to build.gradle:

implementation 'com.vonage:server-sdk-kotlin:2.1.1'
implementation 'io.ktor:ktor-server-netty'
implementation 'io.ktor:ktor-serialization-jackson'

Write the code

Add the following to the main method of the ConnectInboundCall file:

embeddedServer(Netty, port = 8000) {
    routing {
        route("/webhooks/answer") {
            handle {
                call.response.header("Content-Type", "application/json")
                call.respond(
                    Ncco(
                        connectToPstn(VOICE_TO_NUMBER) {
                            from(VONAGE_VIRTUAL_NUMBER)
                        }
                    ).toJson()
                )
            }
        }
    }
}.start(wait = true)

View full source

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.vonage.quickstart.kt.voice with the package containing ConnectInboundCall:

gradle run -Pmain=com.vonage.quickstart.kt.voice.ConnectInboundCall

Prerequisites

Add the following to build.gradle:

implementation 'com.vonage:server-sdk:9.3.1'
implementation 'com.sparkjava:spark-core:2.9.4'

Write the code

Add the following to the main method of the ConnectInboundCall file:

/*
 * Route to answer incoming calls with an NCCO response.
 */
Route answerRoute = (req, res) -> {
    ConnectAction connect = ConnectAction.builder()
            .endpoint(PhoneEndpoint.builder(VOICE_TO_NUMBER).build())
            .from(VONAGE_VIRTUAL_NUMBER)
            .build();

    res.type("application/json");

    return new Ncco(connect).toJson();
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/answer", answerRoute);

View full source

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.vonage.quickstart.voice with the package containing ConnectInboundCall:

gradle run -Pmain=com.vonage.quickstart.voice.ConnectInboundCall

Prerequisites

Install-Package Vonage

Write the code

Add the following to ConnectInboundCallController.cs:

[Route("webhooks/answer")]
public string Answer()
{
    var VOICE_TO_NUMBER = Environment.GetEnvironmentVariable("VOICE_TO_NUMBER") ?? "VOICE_TO_NUMBER";
    var VONAGE_VIRTUAL_NUMBER = Environment.GetEnvironmentVariable("VONAGE_VIRTUAL_NUMBER") ?? "VONAGE_VIRTUAL_NUMBER";

    var talkAction = new TalkAction()
    {
        Text = "Thank you for calling",
        Language = "en-gb",
        Style = 2
    };

    var secondNumberEndpoint = new PhoneEndpoint() { Number=VOICE_TO_NUMBER};            
    var connectAction = new ConnectAction() { From=VONAGE_VIRTUAL_NUMBER, Endpoint= new[] { secondNumberEndpoint } };
    
    var ncco = new Ncco(talkAction,connectAction);
    return ncco.ToString();
}

View full source

Prerequisites

composer require slim/slim:^3.8 vonage/client

Write the code

Add the following to index.php:

require 'vendor/autoload.php';

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

define('VOICE_TO_NUMBER', getenv('VOICE_TO_NUMBER'));
define('VONAGE_VIRTUAL_NUMBER', getenv('VONAGE_VIRTUAL_NUMBER'));

$app = new \Slim\App();

$app->get('/webhooks/answer', function (Request $request, Response $response) {
    $numberToConnect = new \Vonage\Voice\Endpoint\Phone(VOICE_TO_NUMBER);

    $action = new \Vonage\Voice\NCCO\Action\Connect($numberToConnect);
    $action->setFrom(VONAGE_VIRTUAL_NUMBER);

    $ncco = new \Vonage\Voice\NCCO\NCCO();
    $ncco->addAction($action);

    return new JsonResponse($ncco->toArray());
});

$app->run();

View full source

Run your code

Save this file to your machine and run it:

php -S localhost:3000 -t .

Prerequisites

pip install vonage python-dotenv fastapi[standard]

Write the code

Add the following to connect-an-inbound-call.py:

import os
from os.path import dirname, join

from dotenv import load_dotenv
from fastapi import FastAPI
from vonage_voice import Connect, PhoneEndpoint

dotenv_path = join(dirname(__file__), '../.env')
load_dotenv(dotenv_path)

VONAGE_VIRTUAL_NUMBER = os.environ.get('VONAGE_VIRTUAL_NUMBER')
VOICE_TO_NUMBER = os.environ.get('VOICE_TO_NUMBER')

app = FastAPI()


@app.get('/webhooks/answer')
async def inbound_call():
    ncco = [
        Connect(
            endpoint=[PhoneEndpoint(number=VOICE_TO_NUMBER)],
            from_=VONAGE_VIRTUAL_NUMBER,
        ).model_dump(by_alias=True, exclude_none=True)
    ]

    return ncco

View full source

Run your code

Save this file to your machine and run it:

fastapi dev voice/connect-an-inbound-call.py

Prerequisites

gem install sinatra sinatra-contrib

Write the code

Add the following to connect_an_inbound_call.rb:

require 'sinatra'
require 'sinatra/multi_route'
require 'json'

VOICE_TO_NUMBER = ENV['VOICE_TO_NUMBER']
VONAGE_VIRTUAL_NUMBER = ENV['VONAGE_VIRTUAL_NUMBER']

before do
  content_type :json
end

route :get, :post, '/webhooks/answer' do
  [{
    action: 'connect',
    from: VONAGE_VIRTUAL_NUMBER,
    endpoint: [{
      type: 'phone',
      number: VOICE_TO_NUMBER
    }]
  }].to_json
end

set :port, 3000

View full source

Run your code

Save this file to your machine and run it:

ruby connect_an_inbound_call.rb

Try it out

You'll need to expose your server to the open internet. During development, you can use a tool like Ngrok to do that.

When you call your Vonage Number you will automatically be connected to the number you specified in place of VOICE_TO_NUMBER.

Further Reading

  • Interactive Voice Response (IVR) - Build an automated phone system for users to input information with the keypad and hear a spoken response.
  • Voice Bot with Google Dialogflow - This guide will help you to start with an example Dialogflow bot and interact with it from phone calls using provided sample reference codes using Vonage Voice API.
  • Masked Calling - Enable users to call each other, keeping their real numbers private.
  • Conference Calling - This guide explains the two concepts Vonage associates with a call, a leg and a conversation.
  • Call Tracking - Keep track of which campaigns are working well by using different numbers for each one and tracking the incoming calls. This guide shows you how to handle incoming calls, connect them to another number, and track the phone numbers that called each of your Vonage numbers.