这份文档还在翻译中,预期年底前完成。欢迎您提供宝贵的意见及建议。

Track NCCO progress

In this code snippet you see how to track how far through an NCCO a caller gets using the notify action

Example

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "Track NCCO Progress Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

npm install express

Write the code

Add the following to notify-a-call.js:

const app = require('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)

View full source

Run your code

Save this file to your machine and run it:

node notify-a-call.js

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "Track NCCO Progress Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

Add the following to `build.gradle`:

compile 'com.vonage:client:6.2.0'
compile 'com.sparkjava:spark-core:2.7.2'

Write the code

Add the following to the main method of the TrackNccoProgress class:

port(3000);

/*
 * 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();
});

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 TrackNccoProgress:

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

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "Track NCCO Progress Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

Install-Package Vonage

Create a file named TrackNccoController.cs and add the following code:

using Vonage.Utility;
using Vonage.Voice.EventWebhooks;
using Vonage.Voice.Nccos;

View full source

Write 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());
}

View full source

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "Track NCCO Progress Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

composer require slim/slim:^3.8 vonage/client

Create a file named index.php and add the following code:

use Laminas\Diactoros\Response\JsonResponse;
use \Psr\Http\Message\ResponseInterface as Response;
use \Psr\Http\Message\ServerRequestInterface as Request;

View full source

Add the following to index.php:

require 'vendor/autoload.php';

$app = new \Slim\App();

View full source

Write the code

Add the following to index.php:

$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();

View full source

Run your code

Save this file to your machine and run it:

php index.php

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "Track NCCO Progress Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

pip install 'flask>=1.0'

Create a file named track-ncco.py and add the following code:

from flask import Flask, request, jsonify

app = Flask(__name__)

View full source

Write the code

Add the following to track-ncco.py:

@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"

if __name__ == '__main__':
    app.run(host="localhost", port=3000)

View full source

Run your code

Save this file to your machine and run it:

python3 track-ncco.py

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "Track NCCO Progress Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

gem install sinatra sinatra-contrib rack-contrib

Create a file named track-ncco-progress.rb and add the following code:

use Rack::PostBodyContentTypeParser

before do
  content_type :json
end

View full source

Write the code

Add the following to track-ncco-progress.rb:

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

View full source

Run your code

Save this file to your machine and run it:

ruby track-ncco-progress.rb

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