Suivre les progrès du NCCO

Dans cet extrait de code, vous voyez comment suivre l'état d'avancement d'un NCCO pour un appelant en utilisant le notify action

Exemple

Conditions préalables

npm install express

Rédiger le code

Ajouter ce qui suit à track-ncco-progress.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 = (_, 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(port, () => {
  console.log(`Example app listening on port ${port}`);
});

Voir la source complète

Exécutez votre code

Enregistrez ce fichier sur votre machine et exécutez-le :

node track-ncco-progress.js

Conditions préalables

Ajouter ce qui suit à build.gradle:

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

Rédiger le code

Ajouter ce qui suit à la méthode main du fichier TrackNccoProgress:

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)

Voir la source complète

Exécutez votre code

Nous pouvons utiliser le plugin application pour Gradle afin de simplifier l'exécution de notre application. Mettez à jour votre build.gradle avec ce qui suit :

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

Lancez la commande suivante gradle pour exécuter votre application, en remplaçant com.vonage.quickstart.kt.voice par le paquet contenant TrackNccoProgress:

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

Conditions préalables

Ajouter ce qui suit à build.gradle:

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

Rédiger le code

Ajouter ce qui suit à la méthode main du fichier TrackNccoProgress:

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

Voir la source complète

Exécutez votre code

Nous pouvons utiliser le plugin application pour Gradle afin de simplifier l'exécution de notre application. Mettez à jour votre build.gradle avec ce qui suit :

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

Lancez la commande suivante gradle pour exécuter votre application, en remplaçant com.vonage.quickstart.voice par le paquet contenant TrackNccoProgress:

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

Conditions préalables

Install-Package Vonage

Rédiger le code

Ajouter ce qui suit à 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());
}

Voir la source complète

Conditions préalables

composer require slim/slim:^3.8 vonage/client

Rédiger le code

Ajouter ce qui suit à 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();

Voir la source complète

Exécutez votre code

Enregistrez ce fichier sur votre machine et exécutez-le :

php index.php

Conditions préalables

pip install vonage python-dotenv fastapi[standard]

Rédiger le code

Ajouter ce qui suit à track-ncco.py:

from fastapi import FastAPI, Request
from vonage_voice import NccoAction, Notify, Talk

app = FastAPI()


@app.get('/webhooks/answer')
async def inbound_call(request: Request):
    ncco: list[NccoAction] = [
        Talk(text=f'Thanks for calling the notification line.'),
        Notify(
            payload={"foo": "bar"},
            eventUrl=[str(request.base_url) + 'webhooks/notification'],
        ),
        Talk(text=f'You will never hear me as the notification URL will return an NCCO.'),
    ]

    return [action.model_dump(by_alias=True, exclude_none=True) for action in ncco]


@app.post('/webhooks/notification')
async def on_notification():
    return [
        Talk(text=f'Your notification has been received, loud and clear').model_dump(
            by_alias=True, exclude_none=True
        )
    ]

Voir la source complète

Exécutez votre code

Enregistrez ce fichier sur votre machine et exécutez-le :

fastapi dev voice/track-ncco.py

Conditions préalables

gem install sinatra sinatra-contrib rack-contrib

Rédiger le code

Ajouter ce qui suit à track-ncco-progress.rb:

# frozen_string_literal: true

require 'sinatra'
require 'sinatra/multi_route'
require 'rack/contrib'

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

Voir la source complète

Exécutez votre code

Enregistrez ce fichier sur votre machine et exécutez-le :

ruby track-ncco-progress.rb

Essayez-le

Lorsque vous appelez votre Numbers Vonage, vous entendrez un message de synthèse vocale et recevrez une demande d'accès à votre URL de notification