Record Calls using PHP

    Overview

    Conversation with your customers is a crucial piece of information. Call recording is essential in businesses where reviews can help improve customer experience and business processes. You can record any outgoing or incoming calls from/to the Plivo Voice Platform using the various APIs and XML elements provided for different scenarios. Plivo Voice Platform allows you to record, store, retrieve, and delete recordings on the cloud.

    This guide will help you learn about initiating call recordings for outbound API calls, dial XML-connected calls, conference calls, recording features, and aspects of managing call recordings.

    Set Up Your PHP Dev Environment

    Operating SystemInstructions
    macOSYou can install PHP using the official installer. You can also install it from here.
    LinuxTo install PHP on Linux you can find the instructions here.
    WindowsTo install PHP on Windows you can use the official installer.

    Install Composer

    Composer is a dependency manager for PHP that is used in all modern PHP frameworks, such as Symfony and Laravel. We highly recommend using Composer as the package manager for your web project.

    1. Download the latest version of Composer.
    2. Run the following command in Terminal in order to run the composer:

       $ php ~/Downloads/composer.phar --version
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make it executable:

       $ cp ~/Downloads/composer.phar /usr/local/bin/composer
       $ sudo chmod +x /usr/local/bin/composer
       $ Make sure you move the file to bin directory.
      
    4. To check if the path has /usr/local/bin, use

       $ echo $PATH
      

      If the path is different, use the following command to update the $PATH:

       $ export PATH = $PATH:/usr/local/bin
       $ source ~/.bash_profile
      

      Note: If your PATH doesn’t include /usr/local/bin directory, we recommend adding it so that you can access it globally.

    5. You can also check the version of Composer by running the following command:

       $ composer --version.       
      

    1. Run the following command:

       $ curl -sS https://getcomposer.org/installer | php
      
    2. Run the following command to make the composer.phar file as executable:

       $ chmod +x composer.phar
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make Composer globally available for all system users:

       $ mv composer.phar /usr/local/bin/composer
      

    1. Download and run the Windows Installer for Composer.

      Note: Make sure to allow Windows Installer for Composer to make changes to your php.ini file.

    2. If you have any terminal windows open, close all instances and open a fresh terminal instance.
    3. Run the Composer command.

       $ composer -V
      

    Install Laravel & Create a Laravel Project

    • Use the below command to install Laravel:

      $ composer require laravel/installer
      

    As we have Laravel and its dependencies installed, we can use them to create a new Laravel project. As the initial step, using Laravel we can auto-generate code in the Laravel folder structure.

    • Change the directory to our project directory in the command line:

      $ cd mylaravelapp
      
    • Use the below command to start your Laravel project:

      $ composer create-project laravel/laravel quickstart --prefer-dist
      
    • To install the stable release, run the following command in the project directory:

      $ composer require plivo/plivo-php
      

    This will create a quickstart directory with the necessary folders & files for development.

    Install Plivo

    • To install a specific release, run the following command in the project directory:

      $ composer require plivo/plivo-php:4.15.0
      
    • Alternatively, you can download this source and run

      $ composer install
      

    This generates the autoload files, which you can include using the following line in your PHP source code to start using the SDK.

    <?php
    require 'vendor/autoload.php'
    

    Initiate a Call Recording

    There are several ways to start recording a call. You can start a call recording as per your use-case and business requirements. For example, if you want to record a complete call session, you can use Dial XML and enable the complete call session to be recorded (this will be explained further in this guide). You can find all possible ways to record a call in detail in the sections below.

    Record a call using API

    You can start and stop voice recordings for outbound API calls, dial XML-connected calls, and conference calls using the Record calls & Record conference APIs. Recording a call using the API will be done in use-cases when you want to record a specific portion of a call. It will also be helpful in use-cases where you want to make multiple recordings on the same call.

    Record a Call API

    To start voice recording using the record calls API, you need to use the callUUID of the particular call that you want to record.

    Retrieve CallUUID You can get the callUUID of a call connected via the Outbound API & Dial XML from:

    • ring_url: Plivo sends a webhook callback to ring url used in the Outbound Call API request as soon as the destination number starts ringing.
    • answer_url: Plivo sends a webhook callback to answer url when the destination number answers the call.
    • fallback_url: If you have defined the fallback url argument in the API request or the application attached to the Plivo number, and if your application server defined in the answer url is unavailable, then Plivo will try to retrieve the XML document from fallback url to process the call, and during that time Plivo will send a webhook callback to the fallback url.
    • callback_url: If you have used the callback_url param in the dial XML, Plivo will send a callback to your web server configured in callback_url once the number specified in the dial XML answers the call.

    Start Recording If you have the callUUID you want to record, you can start the record call API by specifying the callUUID in the payload. You can stop recording a call in the same way by using the CallUUID if you want to stop recording halfway or if you want to record different sections of the same call.

    For example, if you want to record an outbound API call, you can follow the implementation below to record the call once the destination number answers the call, and the recording will stop automatically once the call is completed.

    Callbacks You can use the callback_url param and set the URL of your application server. Plivo will post the call recording information to the callback url with recording_url, recording_duration, and recording_id.

    Create a Laravel Controller to Record a Call using API

    Change the directory to our newly created project directory, i.e, quickstart directory and run the below command to create a Laravel controller.

    $ php artisan make:controller RecordcallController
    

    This will generate a controller named RecordcallController in the app/http/controllers/ directory. Now, You have to open the app/http/controllers/RecordcallController.php file and add the following code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    <?php
    namespace App\Http\Controllers;
    require '../../vendor/autoload.php';
    use Plivo\RestClient;
    use Plivo\XML\Response;
    use Illuminate\Http\Request;
    
    class RecordcallController extends Controller
    {
        // GetInput XML to handle the incoming call
        public function recordCall()
        {
            $r = new Response();
    
            $getinput_action_url = "https://example.com/recordaction/";
            $get_input = $r->addGetInput(['action' => $getinput_action_url, 'method' => "POST", 'digitEndTimeout' => "5", 'inputType' => "dtmf", 'redirect' => "true", ]);
            $get_input->addSpeak("Press 1 to record this call");
            Header('Content-type: text/xml');
            echo $response->toXML();
        }
    
        // Action URL block for DTMF
        public function recordAction(Request $request)
        {
            $digit = $request->query('Digits');
            $uuid = $request->query('CallUUID');
            $response = new Response();
            $auth_id = "Your AUTH_ID";
            $auth_token = "Your AUTH_TOKEN";
            $client = new RestClient("<auth_id>","<auth_token>");
            if ($digit == "1")
            {
                $response = $client
                    ->calls
                    ->startRecording($uuid);
                print ("URL : {$response['response']['url']}");
                print ("Recording ID : {$response['response']['recording_id']}");
                print ("API ID : {$response['response']['api_id']}");
                print ("Message : {$response['response']['message']}");
            }
            else
            {
                print ("Wrong Input");
            }
        }
    }
    

    Record Conference API

    To start recording conference calls using the Record Conference API, you should use the “Conference Name” of the particular conference you want to record. For example, If you want to start recording a conference call once the participant has entered the conference room, you can follow the implementation below.

    Callbacks You can use the callback_url param and set the URL of your application server. Plivo will post the call recording information to the callback url with recording_url, recording_duration, and recording_id.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    <?php
    /**
     * Example for Conference record create
     */
    require 'vendor/autoload.php';
    use Plivo\RestClient;
    use Plivo\Exceptions\PlivoRestException;
    $client = new RestClient("<auth_id>","<auth_token>");
    try
    {
        $response = $client
            ->conferences
            ->startRecording('My conference');
        print_r($response);
    }
    catch(PlivoRestException $ex)
    {
        print_r($ex);
    }
    

    Record a call using XML

    You can record calls using XML in many ways. You can record a complete call session using record XML in conjunction with dial XML. Recording a call using XML will be helpful in use-cases where you want to record the complete call session for voice or conference calls. It will also be useful in applications such as virtual voicemail boxes, automated speech surveys, etc.

    Record a Voice Call

    You can record the complete session of a dial XML-connected call by using a Dial XML response like below:

    <Response>
      <Record action="http://foo.com/get_recording/" startOnDialAnswer="true" redirect="false" maxLength="3600" />
      <Dial>
        <Number>15551234567</Number>
      </Dial>
    </Response>
    

    The call connected via XML above will record the complete call session once the number specified in the dial XML answers the call. Recording details will be sent to the action URL as soon as the recording starts. You can use the various attributes available in the record XML to control the recording behavior.

    Callbacks You can either use the action or callback_url attribute of the record XML to receive HTTP callbacks related to the call recording on your application server. Plivo will send details such as RecordUrl, RecordingDuration, RecordingDurationMs, RecordingStartMs, RecordingEndMs, RecordingID in the HTTP callback.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    <?php
    require '../vendor/autoload.php';
    use Plivo\XML\Response;
    
    $response = new Response();
    
    $params = array(
        'action' => "https://www.foo.com/get_recording/",
        'startOnDialAnswer' => "true",
        'redirect' => "false"
    );
    
    $response->addRecord($params);
    
    $dial = $response->addDial();
    $number = "14156667777";
    $dial->addNumber($number);
    
    Header('Content-type: text/xml');
    echo ($response->toXML());
    

    Record a Conference Call

    You can record a conference call initiated using a Conference XML by using an XML response like below:

    <Response>
        <Conference callbackUrl="https://www.foo.com/confevents/" callbackMethod="POST" record="true" recordFileFormat="wav">My Room</Conference>
    </Response>
    

    The audio of the conference members connected via XML above will get recorded. Recording details will be sent to the action URL, callback URL as soon as the recording starts. You will also get an event to the callback URL, i.e, ConferenceAction as “record” when the recording starts.

    You can use the recordFileFormat attribute available in the conference XML to record the conference call in wav or mp3 format as you wish.

    Callbacks You can either use the action or callback_url attribute of the conference XML to receive HTTP callbacks related to the conference recording on your application server. Plivo will send details such as RecordUrl, RecordingDuration, RecordingDurationMs, RecordingStartMs, RecordingEndMs, RecordingID in the HTTP callback.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    <?php
    require '../vendor/autoload.php';
    use Plivo\XML\Response;
    
    $response = new Response();
    
    $params = array(
        'record' => "true",
        'callbackUrl' => "https://www.foo.com/confevents/",
        'callbackMethod' => "POST",
        'waitSound' => "https://www.foo.com/waitmusic/"
    );
    
    $conference_name = "My Room";
    $response->addConference($conference_name, $params);
    
    Header('Content-type: text/xml');
    echo ($response->toXML());
    ?>
    

    Recording Features

    In this section, we will walk you through the features associated with recording on the Plivo Voice Platform:

    • File formats: You can choose the file format as per your wish. We recommend using the attributes such as “file_format” for Record a Call API & Record a Conference API, and “recordFileFormat” for Conference XML & “fileFormat” for Record XML.
    • Channel: Plivo records the conference calls in the Mono channel and normal calls in the Stereo channel.
    • Recording length: You can set the maximum duration of recording using the respective arguments & attributes such as “time_limit” for Record a Call API and “maxLength” for Record XML.

    Manage recordings

    • Downloading Recordings: You can store and retrieve the recording details of the voice calls and conference calls using the HTTP callbacks received on the action and callback URLs. Also, you can fetch the recording details from your Plivo Console.
    • Deleting Recordings: You can delete the recordings using the Delete a Recording API. To delete a specific recording using this API, you need the recordingID. You can retrieve the same from the HTTP callback details stored on your database. Also, you can delete the recordings from your Plivo Console.

    Authentication for Recordings

    Recordings hosted on Plivo servers are only accessible via unique, hard to guess, long URLs. These URLs are shared with you in Recording callbacks and API responses. By default, authentication is not enforced on GET recording media requests. This allows for easier implementation of use cases that involve playing recordings on a web/mobile frontend.

    For enhanced security, we recommend enabling Plivo Auth Id and Token-based Basic Auth on Retrieve Recording Media requests made for recordings in your Plivo account. You can enable Basic Auth for Recording URLs from your Other Voice Settings section of the Plivo console.

    Note: Please note that only account admins (users with the role Admin) have the required privileges to update recording auth preference.