In the first tutorial found here, we worked on setting up the backend for this functionality. In this tutorial, we work on the frontend part using ReactJs. Beginner level knowledge of React is required.

Overview

To make calls from the browser, we need a realtime communication mechanism. Realtime communication from the browser implements web-sockets that keep connections alive. For web-based realtime communication, I prefer using WebRTC protocol.

WebRTC refers to Web Real-Time Communication. It entails standards, protocols and JavaScript APIs. It is used for P2P (Peer to Peer) transfer of data, video and audio between browsers. You can read more about WebRTC here

Setting Up React

In this tutorial, I use the basic create-react-app command to set up a react project. You’ll need to have Node >= 8.10 and npm >= 5.6 on your machine. To set up a new react project, from your terminal, input the following commands.

npx create-react-app calls-app
cd calls-app
npm start

Your react app should now be up and running locally.

Setting Up Dependencies

As discussed previously, we use the WebRTC protocol to make the browser calls. Luckily, AT already has developed a package that you can easily plugin without having to write your own WebRTC implementation.

Download this package into your react project using the command npm install --save africastalking-client. I will be working from the app.js file (in the src folder) of the React project. In your app.js file, import the africa's talking client using.

import Africastalking from 'africastalking-client'

After importing the package, we need to create a simple UI now to make the call. We will add a call button and a hangup button for this simple project. Before we do that, however, AT requires a token to be able to make calls. This token is referred to as a capability token. It is generated by making an API POST request from to https://webrtc.africastalking.com/capability-token/request
Since we are using python, the simple code block before will get you the capability token. However, in a production environment, you will need to have your custom API endpoint that you can always make a request to retrieve the token.

import requests
import json

url = 'https://webrtc.africastalking.com/capability-token/request'
payload = {
    'phoneNumber':'+254711223344',
    'clientName': 'yourBrowserClientUniqueIdentifier',
    'username': 'yourAppUsername'
}

headers = {
    'Content-Type': 'application/json',
    'apikey': 'yourATAppKey'
}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.json())

To explain the terms in the code above,

  • username - Your Africa’s Talking application username
  • clientName - Your unique name used to identify and call your browser client(without special characters. To be on the safe side use only alphanumerical for the client name)
  • phoneNumber - Your Africa’s Talking phone number (in international format, i.e. +254XXXYYY)

If the request is successful, you should get a response that looks like.

{
    "clientName": "yourBrowserClientName",
    "incoming": true,
    "lifeTimeSec": "86400",
    "outgoing": true,
    "token": "ATCAPtkn_206675b68efaff83d1ac2d027dd5bff18fd7cb64fgjhd5d0bdcsac44a883678afe7"
}

You can then retrieve the token from the response. This is our capability token.

App Component

In our App.js file, we had already imported the AT client. As we had said earlier, we will create a simple UI with call and cancel buttons. Your file should look like this

import React from 'react';
import Africastalking from 'africastalking-client'
import './App.css';


const App = () =>{
 
  return (
    <div className="App">
      <h1>Calls</h1>
      <button>
        Call
      </button>
      <button>
        Cancel
      </button>
    </div>
  )
}

Next, we need to initialize the AT client.

const token = "yourCapabilityToken";
const client = new Africastalking.Client(token);

After initializing the client then add functions that are called whenever we click the buttons. The AT client package has several methods. Our call and cancel functions would look like.

const call = () => {
   client.call("+254700123456");
}
  
const hangup = () => {
   client.hangup();
}

In the call function, we are calling a user with phone number +254700123456. Next, we add the functions to our buttons to listen to the button click event. Your App.js file should now look like below

import React from 'react';
import Africastalking from 'africastalking-client'
import './App.css';


const App = () =>{
  const token = "yourCapabilityToken";
  const client = new Africastalking.Client(token);
  
  const call = () => {
     client.call("+254700123456");
  }

  const hangup = () => {
     client.hangup();
  }

  return (
    <div className="App">
      <h1>Calls</h1>
      <button onClick={call}>
        Call
      </button>
      <button onClick={hangup}>
        Cancel
      </button>
    </div>
  )
}

And that's it. If you've followed the tutorial from part 1, then you should be able to get it up and running. I have worked with this and tested it on a live app. However, to make sandbox tests using the AT voice API, you need to download the AT sandbox app here.

The AT client also comes with events capabilities. If you'd love to listen to events, there are several methods you can use e.g.

  client.on('hangup', function (hangupCause) {
    alert(`Call hung up (${hangupCause.code} - ${hangupCause.reason})`)
  }, false);

  client.on('incomingcall', function (params) {
    alert(`${params.from} is calling you`)
  }, false);

  client.on('ready', function () {
    alert(`Ready`)
  }, false);

  client.on('notready', function () {
    alert(`Not Ready`)
  }, false);

  client.on('calling', function () {
    alert(`calling`)
  }, false);

  client.on('offline', function () {
    alert(`offline`)
  }, false);

  client.on('callaccepted', function () {
    alert(`call accepted`)
  }, false);

To read more on the AT client package, you can check their NPM documentation here . Feel free to email me in case you get stuck and need help.

Happy Coding :-)

You've successfully subscribed to Decoded For Devs
Welcome back! You've successfully signed in.
Great! You've successfully signed up.
Your link has expired
Success! Your account is fully activated, you now have access to all content.