Laravel OpenTok Integration

What is Open Tok API?

Opentok is a leading WebRTC platform for embedding live video, voice & messaging into your web & mobile apps. It includes client libraries for web, ios and android.

There are two main components of this API:

  • The Client Side - javascript
  • The Server Side - php or similar languages

To get started with opentok API register for developer account and get API credentials for our laravel application. Below is the link to signup for opentok:

Sign up for OpenTok Developer Account

Next, we have to create a new laravel project to get started with. If you do not know how to setup laravel project read installation instructions for Settting Laravel Framework.

Add .env configurations

Let's create two new constants for our open tok api in .env file as shown below:

OPENTOK_API_KEY=
OPENTOK_API_SECRET=​

Next, we have to install opentok php library through composer. Go to your project root folder and run following command in your terminal window:

composer require opentok/opentok​

How opentok API work?

Before we start coding things it is very important to learn about how our app would work in general. Below are the steps which our app would follow:

  • Your client pays for video/audio service
  • After payment you create a token for your client
  • Client logs in and open a video chat and creates a session
  • Client shares the same session to other client
  • Both clients are connected with same session key
  • They can allow browser to share video or audio

Video chat demo using opentok API

For demo purpose we will do following things:

  • we will create a chat page
  • when user lands on chat page we will create video token
  • user will be connected with session
  • user will share the link of chat page to other user
  • other user will join our primary user
  • both shares their screen or video or audio

Create video chat page

For demo purpose we will create a page that begins with /chat url. First of all define a new route for our chat page in routes/web.php file:

Route::get('/', 'HomeController@chat');​

Next, create a HomeController using artisan command line utility. Go to your laravel project root and in terminal window run following command to create our HomeController

php artisan make:controller HomeController​

Above command will create a file in app/Http/Controllers/HomeController.php let's modify this file and add chat method in the controller.

namespace App\Http\Controllers\Client;

use OpenTok\OpenTok;
use OpenTok\MediaMode;
use App\Http\Controllers\Controller;

class HomeController extends Controller
{
     public function chat(Request $request) 
     {
           // initialze api using api key/secret
           $openTokAPI = new OpenTok(env('OPENTOK_API_KEY'), env('OPENTOK_API_SECRET'));

           // let's cache the session for an hour i.e. 60 mins
           $session_token = \Cache::remember('open_tok_session_key', 60, function () use ($openTokAPI) {             
                return $openTokAPI->createSession(['mediaMode' => MediaMode::ROUTED]);
           });

           // now, that we have session token we generate opentok token
           $opentok_token = $openTokAPI->generateToken($session->session_id, [
                'exerciseireTime' => time()+60,
                'data'       => "Some sample metadata to pass"
           ]);

           return view('chat', [
              'session_token' => $session_token,
              'opentok_token' => $opentok_token
           ]);
     }
}

Let's understand what we are doing in our chat controller method:

  • Initialising OpenTok object
  • using OpenTok object we generate a new session
  • we cache the session token for an hour so that our users can chat for an our
  • we generate opentok token with session token and pass both to our chat view page

Next, we will create blade template file for our chat page. Go to resources/views/chat.blade.php

<html>
<head>
    <title> OpenTok Getting Started </title>
    <script src="https://static.opentok.com/v2/js/opentok.js"></script>
</head>
<body>

    <div>SessionKey: {{ $session_token }}</div>
    <div id="videos">
        <div id="subscriber"></div>
        <div id="publisher"></div>
    </div>

    <script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
    <script type="text/javascript">

    var token = '{{ $opentok_token }}';
    var session_key = '{{ $session_token }}';
    var api_key = '{{ env('OPENTOK_API_KEY') }}';

    // connect to open tok api using client side library
    var session = OT.initSession(api_key, session_key);

    // when other user is connected we want to show them
    // in subscriber div element
    session.on('streamCreated', function(event) {
        session.subscribe(event.stream, 'subscriber', {
            insertMode: 'append',
            width: '100%',
            height: '100%'
        }, handleError);
    });

    // when first user loads this page we want him to
    // be shown in publisher div element
    var publisher = OT.initPublisher('publisher', {
        insertMode: 'append',
        width: '100%',
        height: '150px'
    }, handleError);

    // if we have any connection error let's put an alert box
    session.connect(token, function(error) {
        if (error) {
            alert(error.message);
        } else {
            session.publish(publisher, handleError);
        }
    });

    </script>
</body>
</html>

We are doing following things in our view:

  • we load javascript client library
  • we create a stream for our user
  • we publish our stream to other users if they are on the same page

How to organize our app for video chat

We simply demonstrated about how we create a session  and token for our video chat. In real world if you are providing any paid subscription for your users you need to keep following things in mind:

  • Your user pays for subscription
  • you generate a new session for your paid user and store this session key in the table
  • later when you want to connect this user with other user you have to use this session to create video token
  • using this video token you talk to client side library and publish the stream to other user
  • other user securly connects with your paid user and does a video communication
  • you have to make sure that no one else can see this page as it is paid by your user

I hope this tutorial will be helpful to those who seek for video communication using laravel framework.