Plivo PHP Helper Library

Overview

plivo-php

UnitTests

The Plivo PHP SDK makes it simpler to integrate communications into your PHP applications using the Plivo REST API. Using the SDK, you will be able to make voice calls, send SMS and generate Plivo XML to control your call flows.

Supported PHP Versions: This SDK works with PHP 7.1.0+.

Installation

To install Composer

Globally in Mac

  1. Download the latest version of Composer.

  2. Run the following command in Terminal:

     $ php ~/Downloads/composer.phar --version
    
  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 
    
  5. You can also check the version of Composer by running the following command:

     $ composer --version.       
    

Globally in Linux

  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
    
  3. Run the following command to make Composer globally available for all system users:

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

Windows 10

  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
    

Steps to install Plivo Package

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

      $ composer require plivo/plivo-php
    
  • To install a specific release, run the following command in the project directory:

      $ composer require plivo/plivo-php:4.14.0
    
  • To test the features in the beta release, run the following command in the project directory:

      $ composer require plivo/plivo-php:v4.2-beta1
    
  • 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'

Getting started

Authentication

To make the API requests, you need to create a RestClient and provide it with authentication credentials (which can be found at https://console.plivo.com/dashboard/).

We recommend that you store your credentials in the PLIVO_AUTH_ID and the PLIVO_AUTH_TOKEN environment variables, so as to avoid the possibility of accidentally committing them to source control. If you do this, you can initialise the client with no arguments and it will automatically fetch them from the environment variables:

<?php
require 'vendor/autoload.php';
use Plivo\RestClient;

$client = new RestClient();

Alternatively, you can specifiy the authentication credentials while initializing the RestClient.

<?php
require 'vendor/autoload.php';
use Plivo\RestClient;

$client = new RestClient("<auth_id>", "<auth_token>");

The Basics

The SDK uses consistent interfaces to create, retrieve, update, delete and list resources. The pattern followed is as follows:

<?php
$client->resources->create($params) # Create
$client->resources->get($id) # Get
$client->resources->update($id, $params) # Update
$client->resources->delete($id) # Delete
$client->resources->list() # List all resources, max 20 at a time

You can also use the resource directly to update and delete it. For example,

<?php
$resource = $client->resources->get($id)
$resource->update($params) # update the resource
$resource->delete() # Delete the resource

Also, using $client->resources->list() would list the first 20 resources by default (which is the first page, with limit as 20, and offset as 0). To get more, you will have to use limit and offset to get the second page of resources.

Examples

Send a message

<?php
require 'vendor/autoload.php';
use Plivo\RestClient;

$client = new RestClient();
$message_created = $client->messages->create([ 
        "src" => "+14156667778", 
        "dst" => "+14156667777", 
        "text"  =>"Hello, this is a sample text from Plivo"
]);

Make a call

<?php
require 'vendor/autoload.php';
use Plivo\RestClient;

$client = new RestClient();
$call_made = $client->calls->create(
    '+14156667778',
    ['+14156667777'],
    'https://answer.url'
);

Lookup a number

<?php
require 'vendor/autoload.php';
use Plivo\RestClient;

$client = new RestClient("<auth_id>", "<auth_token>");
$response = $client->lookup->get("<number-goes-here>");

Generate Plivo XML

<?php
require 'vendor/autoload.php';
use Plivo\XML\Response;

$response = new Response();
$response->addSpeak('Hello, world!');
echo($response->toXML());

This generates the following XML:

<?xml version="1.0" encoding="utf-8"?>
<Response>
  <Speak>Hello, world!</Speak>
</Response>

Run a PHLO

<?php
/**
 * Example for API Request
 */
require 'vendor/autoload.php';
use Plivo\Resources\PHLO\PhloRestClient;
use Plivo\Exceptions\PlivoRestException;
$client = new PhloRestClient("<auth_id>", "<auth_token>");
$phlo = $client->phlo->get("<phlo_id>");
try {
    $response = $phlo->run(["field1" => "value1", "field2" => "value2"]); // These are the fields entered in the PHLO console
    print_r($response);
} catch (PlivoRestException $ex) {
    print_r($ex);
}
?>

More examples

More examples are available here. Also refer to the guides for configuring the PHP laravel to run various scenarios & use it to test out your integration in under 5 minutes.

Reporting issues

Report any feedback or problems with this version by opening an issue on Github.

Comments
  • Client Error Response while sending SMS

    Client Error Response while sending SMS

    I get the following error while trying to make a POST request to send message:

    Client error response [status code] 400 [reason phrase] BAD REQUEST [url] https://api.plivo.com/v1/Account/{AUTH ID}/Message/
    

    When you look at the trace, there's an exception being thrown by Guzzle. But there's no way to know what may be wrong with the request being made by Plivo.

    Any idea how to solve this?

    opened by manthan787 22
  • Make plivo installable via Composer

    Make plivo installable via Composer

    Would be great if I could install this via Composer.

    Note; If anyone wants to submit a PR to do this, the http_request2 lib is alreday available on packagist https://packagist.org/packages/pear/http_request2

    opened by deplorableword 16
  • Notice: Undefined index: invalid_number in C:\xampp\htdocs\alooviv2\vendor\plivo\plivo-php\src\Plivo\Resources\Message\MessageInterface.php on line 184

    Notice: Undefined index: invalid_number in C:\xampp\htdocs\alooviv2\vendor\plivo\plivo-php\src\Plivo\Resources\Message\MessageInterface.php on line 184

    I am using plivo version 4.3 with php 7.1 I get the sms but i also get the notice.

    Notice: Undefined index: invalid_number in C:\xampp\htdocs\alooviv2\vendor\plivo\plivo-php\src\Plivo\Resources\Message\MessageInterface.php on line 184

    opened by kiranbhattarai 13
  • Don't catch the Guzzle Exceptions

    Don't catch the Guzzle Exceptions

    Before the use statement for the ClientException was missing. But also catching the error and just echoing something is not good practice as we can't catch the error anymore.

    opened by thomaschaaf 7
  • PHP Error[8]: Undefined index: from_number

    PHP Error[8]: Undefined index: from_number

    PHP 7.0 Plivo PHP SDK: v4.4.1

    $client = new \Plivo\RestClient('KEY', 'SECRET');
    $response = $client->messages->get('SOME_ID');
    
    PHP Error[8]: Undefined index: from_number
        in file /var/www/html/protected/vendor/plivo/php-sdk/src/Plivo/Resources/Message/Message.php at line 38
    #0 /var/www/html/protected/vendor/plivo/php-sdk/src/Plivo/Resources/Message/MessageInterface.php(53): Plivo\Resources\Message\Message->__construct()
    #1 /var/www/html/protected/models/Test.php(3873): Plivo\Resources\Message\MessageInterface->get()
    

    The Error is on line 38 in vendor/plivo/php-sdk/src/Plivo/Resources/Message/Message.php

    public function __construct(
            BaseClient $client, $response, $authId)
        {
            parent::__construct($client);
    
            $this->properties = [
                'from' => $response['from_number'],
                'to' => $response['to_number'],
                'messageDirection' => $response['message_direction'],
                'messageState' => $response['message_state'],
                'messageTime' => $response['message_time'],
                'messageType' => $response['message_type'],
                'messageUuid' => $response['message_uuid'],
                'resourceUri' => $response['resource_uri'],
                'totalAmount' => $response['total_amount'],
                'totalRate' => $response['total_rate'],
                'units' => $response['units']
            ];
    
            $this->pathParams = [
                'authId' => $authId,
                'messageUuid' => $response['message_uuid']
            ];
    
            $this->id = $response['message_uuid'];
        }
    
    opened by kangaroodev 6
  • Not pulling sms numbers

    Not pulling sms numbers

    When attempting to pull sms numbers with the latest, nothing comes back.

        $plivo_sms = new RestClient($plivo['auth_id'], $plivo['auth_token']);
    
        // returns 0 results
        $r = $plivo_sms->getPhoneNumbers()->getList('GB', array(
             "type" => "mobile",
             "limit" => 10,
             "offset" => 0
        ));
    
        // returns 0 results
        $r = $plivo_sms->getPhoneNumbers()->getList('GB', array(
             "services" => "sms",
             "limit" => 10,
             "offset" => 0
        ));
    
         // returns 0 results
        $r = $plivo_sms->getPhoneNumbers()->getList('GB', array(
             "type" => "mobile",
             "services" => "sms",
             "limit" => 10,
             "offset" => 0
        ));
    
        // returns 10 results all 800 numbers with smsEnabled: false
        $r = $plivo_sms->getPhoneNumbers()->getList('GB', array(
             "limit" => 10,
             "offset" => 0
        ));
    

    This is on top of the error described in #128.

    I have tried multiple locales to make sure it wasn't a number availability issue. GB, US, CA, MX, and others are all returning 0 items. Perhaps the error is causing this though, I am unsure.

    opened by victoriafrench 6
  • Undefined index: added_on in Number.php construct

    Undefined index: added_on in Number.php construct

    v4.9 Out of nowhere without changing anything I started getting this when using $client->numbers->get('1234131234'):

    function __construct(BaseClient $client, array $response, $authId)
        {
            parent::__construct($client);
     
            $this->properties = [
               'addedOn' => $response['added_on'],
                'alias' => $response['alias'],
                'application' => $response['application'],
                'carrier' => $response['carrier'],
    

    Actually there are others also having trouble now, I haven't updated the API (I've been using 4.9). But I just tried removing that call and the next error I got was Undefined index: answer_time in vendor/plivo/plivo-php/src/Plivo/Resources/Call/Call.php when calling $client->calls->get($phoneUsage->messageUID)->properties

    So lots of things failing. I did run a composer update shortly before this which upgraded the following (maybe there is a conflict): Package operations: 5 installs, 7 updates, 5 removals

    • Removing symfony/polyfill-util (v1.17.1)
    • Removing symfony/polyfill-php56 (v1.17.1)
    • Removing phpoffice/phpexcel (1.8.2)
    • Removing kylekatarnls/update-helper (1.2.1)
    • Removing jeremeamia/superclosure (2.4.0)
    • Updating nesbot/carbon (1.39.1 => 2.35.0): Loading from cache
    • Updating fideloper/proxy (4.3.0 => 4.4.0): Downloading (100%)
    • Installing markbaker/matrix (1.2.0): Loading from cache
    • Installing markbaker/complex (1.4.8): Loading from cache
    • Installing myclabs/php-enum (1.7.6): Loading from cache
    • Updating phpdocumentor/reflection-common (2.1.0 => 2.2.0): Downloading (100%)
    • Updating phpdocumentor/type-resolver (1.2.0 => 1.3.0): Downloading (100%)
    • Installing maennchen/zipstream-php (2.1.0): Loading from cache
    • Installing phpoffice/phpspreadsheet (1.13.0): Loading from cache
    • Updating maatwebsite/excel (2.1.30 => 3.1.19): Loading from cache
    • Updating composer/composer (1.10.7 => 1.10.8): Downloading (100%)
    • Updating myclabs/deep-copy (1.9.5 => 1.10.1): Downloading (100%) Discovered Package: arrilot/laravel-widgets Discovered Package: barryvdh/laravel-debugbar Discovered Package: beyondcode/laravel-dump-server Discovered Package: consoletvs/charts Discovered Package: fideloper/proxy Discovered Package: gruz/voyager-bread-generator Discovered Package: intervention/image Discovered Package: larapack/doctrine-support Discovered Package: larapack/voyager-hooks Discovered Package: laravel/tinker Discovered Package: laravelcollective/html Discovered Package: maatwebsite/excel Discovered Package: nesbot/carbon Discovered Package: nunomaduro/collision Package manifest generated successfully.
    opened by ceswebmaster 5
  • Undefined Index 'restriction' v4.3.3

    Undefined Index 'restriction' v4.3.3

    
    $plivo_sms = new RestClient($plivo['auth_id'], $plivo['auth_token']);
    
    $r = $plivo_sms->phonenumbers->list('GB');
    
    

    This example taken directly from docs.

    Undefined index: restriction in /vendor/plivo/plivo-php/src/Plivo/Resources/PhoneNumber/PhoneNumber.php on line 51

    Undefined index: restriction_text in /vendor/plivo/plivo-php/src/Plivo/Resources/PhoneNumber/PhoneNumber.php on line 52

    opened by placeposition 5
  • Plivo\Exceptions\PlivoResponseException text parameter not present

    Plivo\Exceptions\PlivoResponseException text parameter not present

    Plivo\Exceptions\PlivoResponseException text parameter not present
    
    Plivo\Resources\Message\MessageInterface::create :201
    ...\vendor\plivo\plivo-php\src\Plivo\Resources\Message\MessageInterface.php:201
    

    Error occurs when attempting to send an SMS using the example provided here - https://github.com/plivo/plivo-php#send-a-message

    Occurs on v4.3.8 (latest at the time of writing). It does not occur on 4.3.7.

    opened by qas1 4
  • undefined index restriction

    undefined index restriction

    Here's the snippet from Plivo\Resources\PhoneNumber\PhoneNumber::__construct: image

    The problem is that there is no restriction and restrictionText in response: image

    opened by mkhrystunov 4
  • Problem with plivo/php-sdk 4.1.0

    Problem with plivo/php-sdk 4.1.0

    Hello, I installed the last version of plivo php-sdk from composer (4.1.0).

    When I run the example I receive this error: PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Plivo\Resources\Call\CallInterface::create(), 3 passed in [...] on line 17 and at least 4 expected in [...]/vendor/plivo/php-sdk/src/Plivo/Resources/Call/CallInterface.php:70

    $client = new \Plivo\RestClient($id, $token);
    
    try {
        $response = $client->calls->create(
            $cellular_from,
            ["+39XXXXXXXX"],
            "sms test"
        );
    }
    catch (\Exception $e) {
        \print_r($e);
    }
    

    If I downgrade to 4.0.0-beta1 this code works correctly. Anyone can help me?

    Thanks Alex

    opened by asterixcapri 4
Releases(v4.38.0)
PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule for validation Japanese string only full-width or only half-width.

Japanese String Helpers PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule f

Deha 54 Mar 22, 2022
Simple opinionated framework agnostic PHP 8.1 enum helper

Enum Helper A simple and opinionated collections of PHP 8.1 enum helpers inspired by archtechx/enums and BenSampo/laravel-enum. This package is framew

Datomatic 52 Jan 1, 2023
A lightweight mulit-process helper base on PHP.

workbunny/process ?? A lightweight multi-process helper base on PHP. ?? 简介 这是一个基于ext-pcntl和ext-posix拓展的PHP多进程助手,用于更方便的调用使用。 快速开始 composer require work

workbunny 10 Dec 14, 2022
Simple opinionated PHP 8.1 enum helper for Laravel

Laravel Enum Helper This is an extension of the datomatic/enum-helper package based on Laravel Framework. The package consists on a LaravelEnumHelper

Datomatic 17 Jan 1, 2023
:passport_control: Helper for Google's new noCAPTCHA (reCAPTCHA v2 & v3)

noCAPTCHA (new reCAPTCHA) By ARCANEDEV© What is reCAPTCHA? reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced r

ARCANEDEV 342 Dec 30, 2022
A simple helper to generate and display pagination navigation links

Intro to CHocoCode Paginator Friendly PHP paginator to paginate everything This package introduces a different way of pagination handling. You can rea

faso-dev 3 Aug 24, 2021
Helper to automatically load various Kirby extensions in a plugin

Autoloader for Kirby Helper to automatically load various Kirby extensions in a plugin Commerical Usage This package is free but if you use it in a co

Bruno Meilick 13 Nov 9, 2022
MODX Helper for Tailwind

TailwindHelper MODX Helper for Tailwind Features This MODX Extra adds a Tailwind helper to the MODX installation: Write a safelist.json on base on chu

Thomas Jakobi 3 Jan 10, 2022
🪃 Zero-dependency global `kirbylog()` helper for any content

Kirbylog The most simple, Kirby-esque way to log content to file. Most of the time, I just want to log some string or array to a file. That's what thi

Johann Schopplich 11 Nov 9, 2022
Helper for countries laravel package

Countries helper Helper for countries laravel package Installation You can install the package via composer: composer require eliseekn/countries-helpe

Kouadio Elisée N'GUESSAN 1 Oct 15, 2021
AlphaID Helper - Basic, Simple and Lightweight

AlphaID Helper - Basic, Simple and Lightweight

Hung Nguyen 1 Oct 18, 2021
Traits used primarily in the v6 package but also available as a helper package for applications

Phalcon Traits This package contains traits with methods that are used for Phalcon v6 onward. It can also be useful to others that want short snippets

The Phalcon PHP Framework 5 Oct 7, 2022
Immutable value object for IPv4 and IPv6 addresses, including helper methods and Doctrine support.

IP is an immutable value object for (both version 4 and 6) IP addresses. Several helper methods are provided for ranges, broadcast and network address

Darsyn 224 Dec 28, 2022
Laravel-hours-helper - Creates a Collection of times with a given interval.

Laravel Hours Helper With laravel-hours-helper you can create a collection of dates and/of times with a specific interval (in minutes) for a specific

Label84 220 Dec 29, 2022
Magento-bulk - Bulk Import/Export helper scripts and CLI utilities for Magento Commerce

Magento Bulk Bulk operations for Magento. Configuration Copy config.php.sample to config.php and edit it. Product Attribute Management List All Attrib

Bippo Indonesia 23 Dec 20, 2022
Magento 2 Debug Helper Module for easy debugging with Xdebug and PHPStorm or any other IDE

Magento 2 Debug Helper Information and Usage Magento 2 Debug Helper Module usage with PHPStorm and Xdebug Installation To install the Magento 2 Debug

Dmitry Shkoliar 13 May 24, 2022
Helper script to aid upgrading magento 2 websites by detecting overrides. Now supports third party module detections

ampersand-magento2-upgrade-patch-helper Helper scripts to aid upgrading magento 2 websites, or when upgrading a magento module This tool looks for fil

Ampersand 242 Dec 18, 2022
Helper plugin to install SilverStripe recipes

SilverStripe recipe-plugin Introduction This plugin enhances composer and allows for the installation of "silverstripe-recipe" packages. These recipes

Silverstripe CMS 10 Oct 4, 2022
An opinionated extension package for Laravel Orchid to extend its table handling capabilities, and some further useful helper methods.

OrchidTables An opinionated extension package for Laravel Orchid to extend its table handling capabilities, and some further useful helper methods. In

null 25 Dec 22, 2022