CPaaS Use Case: Hotline Call Between App and Phone

By Shyam Purkayastha

January 22, 2021

One of the most awesome use cases of CPaaS is the ability to initiate voice calls between an app and a phone. This blog post covers a detailed implementation of this use case using the Vonage communication APIs, to build a hotline call feature on a web app.  

More...

Introduction

A hotline service provides a direct telephone link between two parties. It is a hard-wired, point-to-point connection that does not require dialing. The governments and militaries have been using it for ages. You can mimic the proverbial hotline telephone with a "Click to call" feature on a web or mobile app in the Internet era.

Imagine this: you are the CEO of a company, and you want to have direct access to your immediate subordinates. How about an app that lists the names of all your direct reports? You just tap on one name, and the app establishes a voice call with the person.

Follow along with this post to understand how to develop this feature on a Angular web app using the Vonage CPaaS platform. Check out the highlighted boxes labelled "Hands On", to get your hands dirty with the demo code to try this app.

Prerequisites for Hotline App

We are going to build the hotline app as an Angular web application. Here is a glimpse of the app UI.

Hotline Call App

As you can see, this app has a name pad instead of the regular dial pad. It displays the names of the people whom the user can call. At the back, each name is associated with a Public Switched Telephone Network (PSTN) number to initiate a voice call.

To build this hotline app, you must be conversant with JavaScript and Node.js. Knowledge of Angular and TypeScript is an added advantage.

So stop dreaming being a CEO now and get into your coding mojos!

Before you start

You will need:
  • A Vonage account (You can sign up here if you don’t already have one)
  • A virtual phone number (This is the hotline phone number that identifies the caller. You can purchase a virtual number from your Vonage dashboard)

You must also ensure that you have sufficient balance in your Vonage account to bill the calls.

Get the code

Entire source code of this app is available on Github repository.

Hands On #1

Clone the hotline app's GitHub repository to your local computer and take a look at the README file. Do not get intimidated by the number of steps to set up the app. We will gradually break it down for you in the subsequent sections.

The code is split into two parts. There is a client component, which is a frontend hotline app running as an Angular web application. The server component is a Node.js server. This server acts as an intermediary between the app and Vonage services.

Getting Started

The hotline app leverages the Vonage Voice API to build a seamless, high-quality voice application over the Internet. With this API, you can call any landline or mobile number. You can also establish in-app calls with virtual numbers.

The architecture of the hotline app looks something like this.

Vonage Hotline App Arch

Vonage Hotline App Architecture

The Angular app interacts with the intermediary server and the Vonage CPaaS platform. It uses the Nexmo JavaScript SDK to initiate a call.

This app is configured to conduct a server-managed call.A server-managed call uses an intermediary server to handle call-related events fired by the Vonage CPaaS. This is done with webhooks. It also lends a finer control over the call using the Nexmo Call Control Objects (NCCO).

The intermediary server defines two webhooks for processing the answer and event callback. It also serves an API to return the JWT token to log on the user to the hotline app.

Hands On #2

As a first step to deploy the application and all the components shown in the architecture diagram, you must have the specific prerequisites to build and run the app on your computer.  To get started refer the prerequisites section of the README file and install:

  • Node.js and npm
  • Angular CLI
  • Ngrok
  • Nexmo CLI
  • Nexmo client SDK

Hotline Call Progress Sequence

The Nexmo client SDK is associated with a user. In the hotline app, we define a user named John, whose username is "john." John is our fictitious CEO who wants to use the app to keep a tab on his direct reports.

Let's see how John interacts with the app and, in turn, how the app handles the requests for conducting voice call sessions.

Vonage Hotline Call Sequence

Vonage Hotline Call Sequence

Phase 1: User login

The first phase of interaction is log in. John logs into the Angular app with his username. The app fetches John's JWT token from the intermediary server and connects to the Nexmo client SDK. This step is followed by authentication to the SDK using John's credentials for the Vonage CPaaS to identify the user. 

The login code is kept simple by hard coding the username as "john." Here is how the app and server process the login request:

Vonage-Hotline-App\client\src\app\login\login.component.ts

async login(){

    console.log(this.userName);

    if(this.userName === "john"){

      console.log("valid user name: "+this.userName);

      let loginUrl = 'http://localhost:3000/auth/'+this.userName;
      const response = await fetch(loginUrl);
      this.jwt = await response.json();
      console.log("Jwt: "+this.jwt);
      this.nexmoClient.setUser(this.userName);
      this.nexmoClient.setJwt(this.jwt);
    
      // navigate to home page
      this.router.navigate(['/home'], { skipLocationChange : false });

    } else {
 
      console.log("invalid username");
      alert("Username invalid")

    }

}

Vonage-Hotline-App\server\server.js

app.get('/auth/:userid', (req, res) => {
  let user_id = req.params.userid;
  console.log(`Authenticating ${req.params.userid}`)
  
  if ("john" === user_id) {
  
    return res.json(process.env.JWT_john);
  
  }
})

Upon redirection to the name pad display page, the app authenticates the JWT token with the Vonage CPaaS via the client SDK.

Vonage-Hotline-App\client\src\app\home/home.component.ts

async initialize(){
    
    ...

    // create application instance and authenticate with cloud usign jwt
    this.application = await this.nexmoClient.client.login(this.jwt);
    console.log("logged in as "+this.application.me.name);
    this.loggedIn = true; 

    ...
    ...
    ...

  }

Phase 2: Call Initiation

In the second phase, John clicks on the name pad to initiate a call. The Angular app triggers the call via intermediary server. The server is triggered with the answer webhook. It returns an NCCO object that specifies the actions to be taken to answer the call. 

Upon receiving the answer response, the Vonage CPaaS sends a voice message to John saying, "Transferring your call now." Subsequently, it connects to the callee phone.

When the callee picks up the phone, a media session is established between the app and the callee's phone. There is also a media session created initially for sending the voice prompt and call progress tones. But this flow is not shown in the above illustration.

Here is the code for placing the call on the app.

Vonage-Hotline-App\client\src\app\home/home.component.ts

makeCall(id){
    
    this.currentNumber = this.contacts[id];
    this.currentName = id;

    console.log("called number:"+ this.currentNumber);

    this.toggleButtonColor("#FF8C00");
    this.callState = "call-initiated";
    this.application.callServer(this.currentNumber);

}

Vonage CPaaS triggers the answer webhook on the server to retrieve the NCCO object for processing the call. The answer callback is defined as follows:

Vonage-Hotline-App\server\server.js

app.get('/webhooks/answer', (req, res) => {
  console.log("ANSWER:")

  console.log(req.query)
  let  toNumber = req.query.to;
  
  console.log(toNumber);
  var ncco;
  
  const text = "Transferring your call now.";
    ncco = [
      {
        "action": "talk",
        "text": text
      },
      {
        "action": "connect",
        "from": process.env.NEXMO_NUMBER,
        "endpoint": [{
          "type": "phone",
          "number": toNumber
        }]
      }]
  
  res.json(ncco);
});

Phase 3: Call Termination

In the third phase, the callee disconnects the call. In return, this triggers a call completion event to Vonage. This event is further propagated to the app to indicate hang up.  The media session is terminated internally.

Vonage-Hotline-App\client\src\app\home/home.component.ts

handleCallHangup(member,event) {

    this.resetDefaults();
    console.log("call hangup")

}

async handleCall(member,call) {

    ...
    ...

    
    this.call = call;
    this.conversation = call.conversation;
    this.conversation.on("member:left", (member, event) => {
      this.handleCallHangup(member,event);
    });

}

resetDefaults() {

    this.toggleButtonColor("#CC0000");
    this.currentName="";
    this.currentNumber="";
    
    this.callState = "idle";
    
}

Setting Up and Running the Hotline App

Now you understand the architecture and the main sequence of events in the app. It's time to try the app yourself.

Hands On #3

Refer to the setup section in the README. Follow all the steps to install, configure, and generate all artifacts that will be required for running the app later. 

At the end of Hands On #3, do a double-check to ensure that you:

  • Prepare the .env file and add the JWT token information correctly.
  • Update the callee contact information file with the correct phone numbers that you want to test.
  • Keep the speaker volume high.

At this point, the stage is set to test the app.

Hands On #4

Follow the steps under Run the app section of README to deploy the app.

Launching the app through browser will prompt you for the username. 

Hotline App Login

Login as John (with the username 'john')  and then you can see the hotline app UI with name pad displaying buttons for initiating direct calls with pre-defined callees.

Click on the button representing "Bob." You should see the button color change from red to amber and then to green as the call initialization proceeds. Wait for a few seconds and you should get a call on the phone number that you configured for Bob.

Hotline App UI Call Sequence

Once the callee phone is picked up, you can have a conversation just like a regular phone call. The app UI will change the button color to indicate call progress.

The sequence of a color change indicates red (idle), amber (call in progress), and green ( on call), followed by red again, after the call is disconnected.

What's Next?

This app supports only outgoing calls. As a next iteration, you can try enhancing this app to receive calls. Refer the Vonage documentation to learn how to receive incoming calls using the SDK.

Here are a few additional resources to help you understand the more in-depth features of Vonage Voice APIs.

CPaaS Providers

Looking for more CPaaS platform options to build your next app?

Check out our comparison post on

Most Popular CPaaS Providers

Shyam Purkayastha

About the author

Shyam is the Creator-in-Chief at RadioStudio. He is a technology buff and is passionate about bringing forth emerging technologies to showcase their true potential to the world. Shyam guides the team at RadioStudio, a bunch of technoholiks, to imagine, conceptualize and build ideas around emerging trends in information and communication technologies.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
TechForCXO Weekly Newsletter
TechForCXO Weekly Newsletter

TechForCXO - Our Newsletter Delivering Technology Use Case Insights Every Two Weeks

>