Track NCCO progress
In this code snippet you see how to track how far through an NCCO a caller gets using the notify action
Prerequisites
Create an Application
You can install the CLI with the following command:
Before you can start working with your apps, you need to register your configuration: API Key and Secret. You can find them via the Dashboard, in API Settings. Once set, initialize your account using the following command:
As soon as the CLI is both installed and configured, use it to create a Vonage application using the following command:
The command starts an interactive prompt to ask for the application name, and the capabilities you want to enable - make sure to enable Voice.
When finished, it creates the vonage_app.json file in the current directory containing the Application ID, Application name and private key. It also creates a second file with the private key name app_name.key.
Go to the Application's page on the Dashboard, and define a Name for your Application.

Make sure to click on the Generate public and private key button, and keep the file private.key around.
Then, enable the Voice capability. For the moment, leave everything by default.

Finally, click Save at the bottom of the page.
Rent a Number
You can rent a number using the Vonage CLI. The following command purchases an available number in the United States:
Specify an alternative two-character country code to purchase a number in another country.
In the Dashboard, go to the Buy Numbers page. Make sure to tick Voice in the search filter, and select the country you want to buy a number in.

You can then click the Buy button next to the number you want, and validate your purchase.
Congratulations! Your virtual number is now listed in Your Numbers
Link a Number
Now that you have both an application and a number, you need to link them together.
Replace YOUR_VONAGE_NUMBER with the number you bought and APPLICATION_ID with your application id, then run the following command:
Now that you have both an application and a number, you need to link them together.
Go to the Application page, and click on the application you created earlier.

In the Voice section, click on the Link button next to the number you want to link.
Example
Prerequisites
npm install expressWrite the code
Add the following to notify-a-call.js:
const Express = require('express');
const app = new Express();
const onInboundCall = (request, response) => {
const ncco = [
{
'action': 'talk',
'text': 'Thanks for calling the notification line',
},
{
'action': 'notify',
'payload': {
'foo': 'bar',
},
'eventUrl': [`${request.protocol}://${request.get('host')}/webhooks/notification`],
},
{
'action': 'talk',
'text': 'You will never hear me as the notification URL will return an NCCO ',
},
];
response.json(ncco);
};
const onNotification = (request, response) => {
const ncco = [
{
'action': 'talk',
'text': 'Your notification has been received, loud and clear',
},
];
response.json(ncco);
};
app
.get('/webhooks/answer', onInboundCall)
.post('/webhooks/notification', onNotification);
app.listen(3000);Run your code
Save this file to your machine and run it:
Prerequisites
Add the following to build.gradle:
implementation 'com.vonage:server-sdk-kotlin:1.1.2'
implementation 'io.ktor:ktor-server-netty'
implementation 'io.ktor:ktor-serialization-jackson'Write the code
Add the following to the main method of the TrackNccoProgress file:
embeddedServer(Netty, port = 8000) {
routing {
get("/webhooks/answer") {
call.response.header("Content-Type", "application/json")
call.respond(
Ncco(
talkAction("Thanks for calling the notification line."),
notifyAction(
call.request.path().replace("answer", "notification"),
mapOf("foo" to "bar")
),
talkAction("You will never hear me as the notification URL will return an NCCO")
).toJson()
)
}
post("/webhooks/notification") {
val event = EventWebhook.fromJson(call.receive())
call.response.header("Content-Type", "application/json")
call.respond(
Ncco(
talkAction("Your notification has been received, loud and clear."),
).toJson()
)
}
}
}.start(wait = true)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 TrackNccoProgress:
Prerequisites
Add the following to build.gradle:
implementation 'com.vonage:server-sdk:8.15.1'
implementation 'com.sparkjava:spark-core:2.9.4'Write the code
Add the following to the main method of the TrackNccoProgress file:
/*
* Answer Route
*/
get("/webhooks/answer", (req, res) -> {
String notifyUrl = String.format("%s://%s/webhooks/notification", req.scheme(), req.host());
TalkAction intro = TalkAction.builder("Thanks for calling the notification line.")
.build();
Map<String, String> payload = new HashMap<>();
payload.put("foo", "bar");
NotifyAction notify = NotifyAction.builder(payload)
.eventUrl(notifyUrl)
.build();
TalkAction unheard = TalkAction.builder("You will never hear me as the notification URL will return an NCCO")
.build();
res.type("application/json");
return new Ncco(intro, notify, unheard).toJson();
});
/*
* Notification Route
*/
post("/webhooks/notification", (req, res) -> {
res.type("application/json");
return new Ncco(
TalkAction.builder("Your notification has been received, loud and clear.")
.build()
).toJson();
});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 TrackNccoProgress:
Prerequisites
Install-Package VonageWrite the code
Add the following to TrackNccoController.cs:
[HttpGet("[controller]/webhooks/answer")]
public IActionResult Answer()
{
var host = Request.Host.ToString();
//Uncomment the next line if using ngrok with --host-header option
//host = Request.Headers["X-Original-Host"];
var eventUrl = $"{Request.Scheme}://{host}/webhooks/notification";
var talkAction = new TalkAction() { Text = "Thanks for calling the notification line" };
var notifyAction = new NotifyAction()
{
EventUrl = new[] { eventUrl },
Payload = new FooBar() { Foo = "bar" }
};
var talkAction2 = new TalkAction() { Text = "You will never hear me as the notification URL will return an NCCO" };
var ncco = new Ncco(talkAction, notifyAction, talkAction2);
return Ok(ncco.ToString());
}
[HttpPost("webhooks/notification")]
public async Task<IActionResult> Notify()
{
var notification = await WebhookParser.ParseWebhookAsync<Notification<FooBar>>(Request.Body, Request.ContentType);
Console.WriteLine($"Notification received payload's foo = {notification.Payload.Foo}");
var talkAction = new TalkAction() { Text = "Your notification has been received, loud and clear" };
var ncco = new Ncco(talkAction);
return Ok(ncco.ToString());
}Prerequisites
composer require slim/slim:^3.8 vonage/clientWrite the code
Add the following to index.php:
require 'vendor/autoload.php';
$app = new \Slim\App();
$app->get('/webhooks/answer', function (Request $request, Response $response) {
//Get our public URL for this route
$uri = $request->getUri();
$url = $uri->getScheme() . '://'.$uri->getHost() . ($uri->getPort() ? ':'.$uri->getPort() : '') . '/webhooks/notification';
$notify = new \Vonage\Voice\NCCO\Action\Notify(
['foo' => 'bar'],
new \Vonage\Voice\Webhook($url, 'GET')
);
$ncco = new \Vonage\Voice\NCCO\NCCO();
$ncco
->addAction(
new \Vonage\Voice\NCCO\Action\Talk('Thanks for calling the notification line')
)
->addAction($notify)
->addAction(
new \Vonage\Voice\NCCO\Action\Talk('You will never hear me as the notification URL will return an NCCO')
)
;
return new JsonResponse($ncco);
});
$app->map(['GET', 'POST'], '/webhooks/notification', function (Request $request, Response $response) {
/** @var \Vonage\Voice\Webhook\Event */
$event = \Vonage\Voice\Webhook\Factory::createFromRequest($request);
error_log(print_r($event, true));
$ncco = new \Vonage\Voice\NCCO\NCCO();
$ncco->addAction(
new \Vonage\Voice\NCCO\Action\Talk('Your notification has been received, loud and clear')
);
return new JsonResponse($ncco);
});
$app->map(['GET', 'POST'], '/webhooks/event', function (Request $request, Response $response) {
/** @var \Vonage\Voice\Webhook\Event */
$event = \Vonage\Voice\Webhook\Factory::createFromRequest($request);
error_log(print_r($event, true));
return $response->withStatus(204);
});
$app->run();Run your code
Save this file to your machine and run it:
Prerequisites
pip install 'flask>=1.0'Write the code
Add the following to track-ncco.py:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/webhooks/answer")
def answer_call():
ncco = [{
"action": "talk",
"text": "Thanks for calling the notification line"
},
{
"action": "notify",
"payload": {
"foo": "bar"
},
"eventUrl": [
"{url_root}webhooks/notification".format(url_root=request.url_root)
]
},
{
"action": "talk",
"text": "You will never hear me as the notification URL will return an NCCO "
}]
return jsonify(ncco)
@app.route("/webhooks/notification", methods=['POST'])
def notification():
ncco = [{
"action": "talk",
"text": "Your notification has been received, loud and clear"
}]
return jsonify(ncco)
@app.route("/webhooks/event", methods=['POST'])
def event():
return "OK"Run your code
Save this file to your machine and run it:
Prerequisites
gem install sinatra sinatra-contrib rack-contribWrite the code
Add the following to track-ncco-progress.rb:
use Rack::PostBodyContentTypeParser
before do
content_type :json
end
route :get, :post, '/webhooks/answer' do
[
{
'action' => 'talk',
'text' => 'Thanks for calling the notification line'
},
{
'action' => 'notify',
'payload' => {'foo' => 'bar'},
'eventUrl' => ["#{request.base_url}/webhooks/notification"]
},
{
'action' => 'talk',
'text' => 'You will never hear me as the notification URL will return an NCCO'
}
].to_json
end
route :get, :post, '/webhooks/notification' do
puts params
[
{
'action' => 'talk',
'text' => 'Your notification has been received, loud and clear'
}
].to_json
end
route :get, :post, '/webhooks/event' do
puts params
halt 204
end
set :port, 3000
Run your code
Save this file to your machine and run it:
Try it out
When you call your Vonage Number you will hear a text-to-speech message and receive a request to your notification URL