Quantcast
Channel: ProgrammableWeb - Node.js
Viewing all articles
Browse latest Browse all 1601

Add Programmable Voice to Your Node.js Apps with Express

$
0
0
Primary Target Audience: 
Primary Channel: 
Primary category: 
Secondary category: 
Related Companies: 
Related APIs: 
Nexmo Voice
Nexmo SMS
Related Platform / Languages: 
Summary: 
In this tutorial, you will learn how to use the Nexmo Application and Voice APIs to create a text-to-speech outbound phone call securely and then how to receive inbound calls by implementing a Webhook. This tutorial assumes you are working with a Unix or Linux-based operating system.

This tutorial explains how to make and receive phone calls with Node.js and the Nexmo Voice API. With Nexmo's Voice API, you can build high-quality programmable voice applications in the cloud and handle tasks such as managing outbound and inbound calls in JSON, recording and storing calls, creating a conference call, sending text-to-speech messages in 23 languages, and so on.

In this tutorial, you will learn how to use the Application and Voice APIs to create a text-to-speech outbound phone call securely and then how to receive inbound calls by implementing a webhook. This tutorial assumes you are working with a Unix or Linux-based operating system such as Mac OS X or Ubuntu.

GitHub iconView the source code on GitHub

Securing Your Nexmo Application

Some of Nexmo's APIs use Nexmo applications, which contain the security and configuration information you need to connect to the Voice API endpoints.

An application:

Figure 1: Using the Nexmo Voice API to call your mobile phone

Figure 1: Using the Nexmo Voice API to call your mobile phone

Creating a Nexmo Application and Generating a Private Key

Your app needs to authenticate requests to the Voice API. In this section, you will generate a private key with the Application API, which allows you to create JSON Web Tokens (JWT) to make the requests.

Begin by creating an application with the Nexmo command-line interface (CLI) tool, which will set up the app and generate a private key for you.

Make sure Node.js 4.0 or above is installed on your machine, then install nexmo-cli from npm:

$ npm install nexmo-cli -g

When you initially signup at Nexmo.com, you will be presented with your Nexmo API key and secret. It will look something like this:

Initial signup at Nexmo.com

This information is also easily retrieved at any time by visiting the settings area of your Nexmo dashboard.

The settings area of the Nexmo dashboard

Next, set up the CLI with your Nexmo API key and secret:

$ nexmo setup API_KEY API_SECRET

For example:

$ nexmo setup aabb11cc fB1234567890abcdefabcde

This will locally save your credentials to a hidden file in your home directory: ~/.nexmorc.

Once configured, you are going to create an application in your working directory using the CLI.

Continued from page 1. 

Along with the app:create command, you need to register an application name (let's call it "My Voice App") and two webhook endpoints. You don't need to specify the actual answer and event URLs for making calls. So use some placeholder values for now and leave the optional field blank:

 $ nexmo app:create "My Voice App" http://example.com/answer http://example.com/event --keyfile private.key

One word of caution: If there is an existing file called "private.key" in your home directory (perhaps one that you created for some other purpose), this command will overwrite it. In such a case, you may want to pick a different name for outputting the private key file. When the application is successfully created, the CLI returns something like this:

Application created: c6b78717-db0c-4b8b-9723-ee91400137cf
Private Key saved to: private.key

These are your application ID and private key (in this case, the private.key file is generated in the same directory). You will need both the App ID and the private key to make a phone call using the Voice API.
You can edit the app info with the nexmo app:update command later as needed. To learn more about the CLI, read the documentation on the GitHub repo.

Making a Call with the Nexmo Voice API

Now you are going to use the Voice API to make a call with the Nexmo Node.js client library. If you have not done so already, make sure Node.js is installed on your machine and install the Nexmo Node.js library via npm:

$ npm install nexmo --save

Using a text editor like Sublime or Atom, create a .js file (let's call it voice-call.js) and initialize Nexmo with your API credentials, as well as the application ID and the private key you just created. The value for the privateKey has to be read from the saved file, not the path of the file:

const privateKey = require('fs').readFileSync(privateKeyFile);
const Nexmo = require('nexmo')
const nexmo = new Nexmo({
 apiKey: NEXMO_API_KEY,
 apiSecret: NEXMO_API_SECRET,
 applicationId: appId,
 privateKey: privateKey
});

Now, make a call with the calls.create function:

nexmo.calls.create({
 to: [{
   type: 'phone',
   number: process.argv[2] // take a phone number from command line argument
 }],
 from: {
   type: 'phone',
   number: FROM_NUMBER // your virtual number
 },
 answer_url: ['https://nexmo-community.github.io/ncco-examples/first_call_talk.json']
}, (err, res) => {
 if(err) { console.error(err); }
 else { console.log(res); }
});

For the purposes of testing, the above source code takes the phone number to call as a command line argument. So when you run this code, run it with a number (like the number for your mobile phone). The FROM_NUMBER should be your virtual number, which you can find in your dashboard.

The synthesized voice will read the text from your webhook endpoint at answer_url, which contains an NCCO in JSON. You can use the example hosted on Nexmo's Community GitHub repo, or create your own and host it on a server (or even on GitHub Gist) that the Nexmo API can reach.

For example, here is an NCCO in JSON called My-greeting.json that you could host on your own server:

[
 {"action": "talk","voiceName": "Chipmunk","text": "Yo, this is Chipmunk. I am created with Nexmo Voice API!"
 }
]

You can customize the audio with optional params such as voiceName. You can choose from a variety of voices by language, gender and accent. Or you can use an audio file:

My-greeting-audio.json:

[
 {"action": "stream","streamUrl": ["https://example.com/audio_file.mp3"]
 }
]

Now, let's run the app to make a call to your phone. Use a phone number starting with a country code ("1" for the US, for example) as an argument when running the node code:

$ node voice-call.js 15105551234

When the code is successful, it retrieves the NCCO from your webhook, executes the actions, and terminates the call. You may observe some latency depending on the phone carrier. It can take some time for your phone to ring after the code is executed.
 

Continued from page 2. 

In this exercise, the phone number is taken from a command line but, of course, you can take the request from the web via POST.

How to Handle Inbound Phone Calls with Node.js

Now that you know how to make a call, let's dive into how you can receive inbound calls by implementing a webhook. You will update the application that you created to receive a voice call with webhook endpoint URLs.

GitHub iconView the source code on GitHub

When a user calls the Nexmo virtual phone number associated with your voice application, Nexmo retrieves the NCCO from your answer_url webhook endpoint, and answers the call with a synthesized voice that reads the text you have specified in the NCCO.

Figure 2: Using the Voice API to receive a call to your Nexmo virtual number

Figure 2: Using the Voice API to receive a call to your Nexmo virtual number

Nexmo also sends status information to another webhook endpoint defined by event_url. The event is triggered when the user's handset is ringing (ringing), when the call is answered (answered), etc. You can find all the events in the API Reference documentation.

Defining Webhook Endpoints

In order to accept an incoming call to your Nexmo virtual phone number, you need to associate your voice application with webhook endpoint URLs.
Let's use ngrok to expose your webhook endpoint on your local machine as a public URL.

Using ngrok

First, download ngrok from https://ngrok.com. Once installed, run ngrok on your terminal for port 3000:

$ ngrok http 3000
Run ngrok on your terminal for port 3000

Your local server (localhost:3000) now has a ngrok URL, https://71f03962.ngrok.io that can be used as your webhook endpoint during development

Writing WebHook Endpoints with Express

Let's handle the POST requests with Express. You will also need to install body-parser.

 $ npm install express body-parser --save

Create a .js file, instantiate Express, and listen to the server to port 3000. Because you have set your ngrok to expose Alternatively you can try localhost:3000, you must stick with the same port.

'use strict'
const app = require('express')();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const server = app.listen(process.env.PORT || 3000, () => {
 console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
});

Let's define the endpoint for the Answer URL as Alternatively you can try /answer and the Event URL as Alternatively you can try /event.
Create an HTTP GET route to handle the requests for Alternatively you can try /answer to retrieve your NCCO:

app.get('/answer', function (req, res) {
const ncco = [
{
action: 'talk',
voiceName: 'Jennifer',
text: 'Hello, thank you for calling. This is Jennifer from Nexmo. Ciao.'
}
];
res.json(ncco);
});

Define your text to be read by a synthesized voice in JSON (or JavaScript object, in this case). You can customize the audio with optional params, such as Alternatively you can try voiceName.

The endpoint for the Alternatively you can try event_url needs to be POST, so let's define Alternatively you can try /event:

app.post('/event', function (req, res) {
 console.log(req.body);
 res.status(204).end();
});

You don't need to actually return anything if you just want to monitor the status in a terminal.

Updating the Nexmo Application with WebHook URLs

Nexmo applications contain configuration information you need to connect to the Voice API endpoints. Previously, we used placeholders for both the Answer URL and the Event URL. Now you are going to use the Nexmo CLI to update the application information with the webhook endpoints you just defined.

You need the application ID to update the information. You can get it from the make-call.js or use the app:list command:

$ nexmo app:list

The CLI should return a list of each app ID and an app name. Now, use the correct app ID to update the application with the webhook URLs:

$ nexmo app:update c6b78717-db0c-4b8b-9723-ee91400137cf "My Voice App" https://71f03962.ngrok.io/answer https://71f03962.ngrok.io/event

Associating the Info with Your Virtual Number

Finally, you need to associate your application with the virtual number you rent from Nexmo. Let's use the Nexmo CLI again. Use the command nexmo link:app followed by the phone number, which again must start with a country code and then the app ID. So, the command should look like this:

$ nexmo link:app 12015556649 c6b78717-db0c-4b8b-9723-ee91400137cf

When the linking is successful, the CLI returns with the message, "Number updated."

Testing Your Voice Application

Let's make a phone call to see if your application works! Call your virtual number from your physical phone. If everything works, you should hear the message you have defined in your NCCO.

Also, you should see your terminal to check the status of your call.

Content type group: 
Articles
Top Match Search Text: 
Add Programmable Voice to Your Node.js Apps with Express

Viewing all articles
Browse latest Browse all 1601

Trending Articles