How To Voice Call From Web To Mobile In Angular Using C# .NET Core And Twilio

In this blog, We are going to learn How To Voice Call From Web To Mobile In Angular Using C# .NET Core.

First of all, We need Twilio credentials to move forward. Please get it from the Twilio console by yourself.

We need the below Keys to move forward.

  • Account SID
  • AUTH TOKEN
  • PHONE NUMBER (TWILLIO PHONE NUMBER)

12

We need twillio APIKey and APISecret to integrate the Call API, You can generate it from here.

Now you need to create a TwiML  App, which will help you to voice call.

Now you need to add REQUEST URL in TwiML app, so you need to create one public URL to move forward.(Note: Local URLs will not work) and then need to set in below format.

<your-ngrok-public-url>/<your-method-path>

Now, we have all the required keys, Let’s get start coding.

As I am using Angular, I need to create one API project to manage API stuff.

So, now I am creating a .NET Core API project.

   1) .NET Core API

Install the Twilio from the Package manager Console For Twilio Package

Install-Package Twilio

And Also, Twilio.AspNet.Core.

Install-Package Twilio.AspNet.Core -Version 5.37.2

Create a TokenController to get token:

using Microsoft.AspNetCore.Mvc;
using Twilio.Jwt.AccessToken;
using System.Collections.Generic;
using Twilio.AspNet.Core;

namespace Angular_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TokenController : TwilioController
    {
        
        [HttpGet("token")]
        public string GetTwilioToken()
        {

            var twilioAccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXX";
            var appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
            var twilioApiKey = "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
            var twilioApiSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxx";

            var grant = new VoiceGrant();
            grant.OutgoingApplicationSid = appSid;

            grant.IncomingAllow = true;

            var grants = new HashSet<IGrant>
            {
                { grant }
            };
            string role = "user"; //Default role

            var accessToken = new Token(
                twilioAccountSid,
                twilioApiKey,
                twilioApiSecret,
                role,
                grants: grants);

            return accessToken.ToJwt();
        }
    }
}

Now, Need to create one more method which is we provide to the TwiML App Request URL.

Syntex:

using Microsoft.AspNetCore.Mvc;
using Twilio.TwiML;
using Twilio.AspNet.Core;
using Twilio.TwiML.Voice;

namespace Angular_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CallController : TwilioController
    {
        // POST Call/Connect
        [HttpPost("Connect")]
        public TwiMLResult Connect()
        {
            string toNumber = Request.Form["phoneNumber"].ToString();
            const string PhoneNumber = "+11111111111";

            var response = new VoiceResponse();

            var dial = new Dial(callerId: PhoneNumber);

            dial.Number(toNumber);
            response.Append(dial);

            return TwiML(response);
        }
    }
}

Our API is ready to use.

Now let’s create the frontend (web page).

   2)  Angular App

Create an Angular app.

  1.  call.component.html file:
    <div class="row">
      <div class="col-md-6">
        <input
          type="email"
          id="phone"
          class="form-control form-control-alternative"
          name="message"
          [(ngModel)]="phoneNumber"
          required
          #fullname="ngModel"
          placeholder="Mobile Number"
       />
      </div>
      <div class="col-md-3" *ngIf="callHideShow === true">
        <button
          type="button"
          class="btn btn-primary my-4"
          (click)="callCustomer()" >
          Call
        </button>
      </div>
      <div class="col-md-3" *ngIf="stopHideShow === true">
        <button
          type="button"
          class="btn btn-dark my-4"
          (click)="Stop()">
            Stop
        </button>
      </div>
    </div>
  2.  call.component.ts file:
    import { HttpClient } from '@angular/common/http';
    import { Component, OnInit, ViewChild } from '@angular/core';
    import { NgForm } from '@angular/forms';
    declare const Twilio: any;
    
    @Component({
      selector: 'app-voicecall',
      templateUrl: './voicecall.component.html',
      styleUrls: ['./voicecall.component.css']
    })
    export class VoicecallComponent implements OnInit {
      phoneNumber: any;
      connection: any = null;
      device: any;
      callHideShow: any = true;
      stopHideShow: any = false;
    
      constructor(public http: HttpClient) { }
    
      ngOnInit(): void {
        this.http.get('https:/879875454.ngrok.io/api/Browser/token',  { responseType: 'text'}).subscribe((data)=>
       {
           console.log(data);
           this.device = Twilio.Device.setup(data);
           this.setupHandlers(this.device);
           console.log(this.device);
       });
      }
    
      setupHandlers(device) {
        device.on('ready', (_device) => {
            this.updateCallStatus("Ready to call");
        });
    
        device.on('error',  (error) => {
            this.updateCallStatus("ERROR: " + error.message);
        });
    
        device.on('connect', (connection) => {
            if ("phoneNumber" in connection.message) {
                this.updateCallStatus("In call with " + connection.message.phoneNumber);
                this.callHideShow = false;
                this.stopHideShow = true;
            } else {
                this.updateCallStatus("In call with support");
            }
        });
    
        device.on('disconnect',  (connection) => {
            this.updateCallStatus("Call End");
            this.stopHideShow = false;
            this.callHideShow = true;
        });
      }
    
      updateCallStatus(status: string): void {
        console.log("Status -> ",  this.callStatusList)
      }
    
      callCustomer(){
        if (!this.form.valid) {
          return;
        }
    
        this.updateCallStatus("Calling " + this.phoneNumber + "...");
    
        var params = { "phoneNumber": this.phoneNumber };
        this.device.connect(params);
        this.form.reset();
      }
    
      Stop(){
        this.device.disconnectAll();
        this.stopHideShow = false;
        this.callHideShow = true;
      }
    
    }
    

3. Index.html

  • Add Twilio Client CDN.
    <script type="text/javascript" src="https://sdk.twilio.com/js/client/v1.13/twilio.min.js"></script>

OUTPUT:

That’s It.

Let me know if you face any difficulties.

2 Comments

  1. ashish

    Hi
    where Controller api side callCustomer() Method call ??

    0
    0
    Reply
    1. Nayan Raval

      The API call invokes the URL which is set in Twilio’s TwiML.

      0
      0
      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories