Angular 6: Voice Calls using Twilio Javascirpt Client

Following process will explain how to implement the Web based calls using Twilio in an Angular application with .NET Core. For implementing a browser based call, we need to implement the following
  • Create an API which returns the TwiML.
  • Create a TwiML Client App in Twilio
  • Create an APIUto return the capability token
  • Configure the Twilio Javascript SDK in Anguar application

Create an API which returns the TwiML

We need to create an api method which return handle the request sent from the TwiML app and initiates the call using Dial Verb as follows
var response = new VoiceResponse();
var dial = new Dial(callerId: fromNumber
 , action: actionUrl
 , method: Twilio.Http.HttpMethod.Post
 , timeout: 60);
dial.Number(phoneNumber: To);
response.Append(dial);
return response.ToString();
Here, we specified the from number, actionUrl, actionUrl method and timeout for the dial verb. The to number should be in the Number attribute under dial verb. If you want to use call recording, then the above code will be as 
var response = new VoiceResponse();
var dial = new Dial(callerId: fromNumber
 , action: actionUrl
 , method: Twilio.Http.HttpMethod.Post
 , timeout: 60
 , record: RecordEnum.RecordFromRinging);
dial.Number(phoneNumber: To
 , url: recordingUrl
 , method: Twilio.Http.HttpMethod.Post);
response.Append(dial);
return response.ToString();
once the API created, we need to host it in a public URL to call it from TwiML app. (Or else you can use the advantage of Twilio Function to create your TwiML app)

Create a TwiML Client App in Twilio

For creating a TwiML app,
Login to Twilio 
-> Navigate to Programmable Voice 
-> TwiML 
-> TwiML Apps 
-> Click on Create TwiML app button ( or the plus symbol).

Give the Friendly name for the TwiML app and Voice Request URL (the one we created in the above step) and click on Create button.


Now if you open the app you created, it will show the SID for the TwiML app.


Create an API to return the capability token

Once we created the TwiML app, we need to write an API to generate the capability token for Twilio Javascirpt library. Following is the API code to generate the capability token.
// Put your Twilio API credentials here
const string accountSid = "ACexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const string authToken = "95xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

// Put your TwiML App Id here
const string appSid = "APxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

var scopes = new HashSet<IScope>
{
 new OutgoingClientScope(appSid)
};
var capability = new ClientCapability(accountSid, authToken, scopes: scopes);

return capability.ToJwt();
Following is the complete code of my API methods  created in Steps 1 and 3
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using Twilio.Jwt;
using Twilio.Jwt.Client;
using Twilio.TwiML;
using Twilio.TwiML.Voice;
using static Twilio.TwiML.Voice.Dial;

namespace Twilio.API.Controllers
{
    [Route("api/[controller]")]
    [EnableCors("CorsPolicy")]
    [ApiController]
    public class TwilioController : ControllerBase
    {
        // GET api/twilio/token
        [HttpGet("token")]
        public string GetToken()
        {
            // Put your Twilio API credentials here
            const string accountSid = "ACexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const string authToken = "95xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// Put your Twilio Application SID here const string appSid = "APxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var scopes = new HashSet<IScope> { new OutgoingClientScope(appSid) }; var capability = new ClientCapability(accountSid, authToken, scopes: scopes); return capability.ToJwt(); } // POST api/twilio/call [HttpPost("call")] public string StartCall(string To, bool IsRecord) { string fromNumber = "xxx-xxx-xxx"; var actionUrl = new Uri("http://localhost/api/statuscallback"); // Here I am giving the sample url, but it should be a public url to allow Twilio to post data var response = new VoiceResponse(); var dial = new Dial(callerId: fromNumber , action: actionUrl , method: Twilio.Http.HttpMethod.Post , timeout: 60, record: RecordEnum.RecordFromRinging); // If recording required if (IsRecord) { dial.Record = RecordEnum.RecordFromRinging; var recordingUrl = new Uri("http://localhost/api/record"); // Here I am giving the sample url, but it should be a public url to allow Twilio to post data dial.Number(phoneNumber: To , url: recordingUrl , method: Twilio.Http.HttpMethod.Post); } else dial.Number(phoneNumber: To); response.Append(dial); return response.ToString(); } } }

Configure the Twilio Javascript SDK in Anguar application

a) Add twilio client sdk in the header section of the index.html file .You can find the latest version from here
<script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.7/twilio.min.js"></script>
b) In the component typescirpt file where you want to use Twilio add the below line under imports.
 declare const Twilio: any;
 
c) In the ngOnInit method, call the token api and initiate the Twilio
 ngOnInit() {
    
    this.http.get('https://localhost:44346/api/twilio/token',  { responseType: 'text'}).subscribe((data)=>
    {
        Twilio.Device.setup(data);
    });
    
  }
d) Add call button in the UI
 Phone number: <input type="text" placeholder="Enter Phone number" [(ngModel)]="phoneNumber"/>
 <button (click)="Phonecall()">Call</button>
e) Add the belwo Phone call method in the typescript file
Phonecall()
{
  if(this.connection==null)
  {
 console.log('connection is null. Initiating the call');
 var params = { "To": this.phoneNumber, "IsRecord":true};
 this.connection = Twilio.Device.connect(params);
  }
  else {
 this.connection = null;
 Twilio.Device.disconnectAll();
  }
}

Happy Coding  😊!!

Reference:
1) Twilio Client Javascript Quickstart
2) Twiml

Gopikrishna

    Blogger Comment
    Facebook Comment

4 comments:

  1. Hello, You any git repo for this blog?

    ReplyDelete
  2. But, when call api debugger and run not calling my mobile phone

    ReplyDelete
  3. after StartCall funcation call not dial in my phone and how can both are commination each other?

    ReplyDelete