Nexmo REST API client for PHP. API support for SMS, Voice, Text-to-Speech, Numbers, Verify (2FA) and more.

Overview

Client Library for PHP

Contributor Covenant Build Status Latest Stable Version MIT licensed codecov

Nexmo is now known as Vonage


Support Notice

This library and it's associated packages, nexmo/client and nexmo/client-core have transitioned into a "Maintenance Only" mode. For the next twelve (12) months, this library will only receive bug or security fixes. This library will officially be End of Life as of October 1st, 2021.

We recommend users begin migrating over to https://github.com/vonage/vonage-php-sdk-core and the vonage/client and vonage/client-core packages for their applications. The Vonage packages fully support the \Nexmo namespace and should be a drop-in replacement for the Nexmo packages.

If you have any questions, feel free to reach out to us at [email protected] or through our Community Slack at https://developer.nexmo.com/community/slack


This library requires a minimum PHP version of 7.2

This is the PHP client library for use Vonage's API. To use this, you'll need a Vonage account. Sign up for free at nexmo.com.

Migration

This package has officially moved to a "maintenance only" mode, and we highly suggest moving to vonage/client and vonage/client-core for all codebases. While we will be supporting this package with any needed bug or security fixes, no new features will be developed for this codebase, including new product releases. We are providing up to twelve (12) months of support to give users time to upgrade.

We have tried to make the upgrade as seamless as possible for all users.

Step 1 - Find out Current Versions

What we need:

  • Do you have nexmo/client or nexmo/client-core requested?
  • What version of nexmo/client-core is installed

The first thing we need to do is figure out what, and which versions, you have installed. The quickest way is to just open up composer.json and search for "nexmo/client" and "nexmo/client-core", and see which one you have. You should have either nexmo/client or nexmo/client-core requested in composer.json. Take note of which is in your composer.json file.

To find out what version of nexmo/client-core you have installed, you can run:

composer show nexmo/client-core

This should give you the following output, of which we care about the "versions" line:

name     : nexmo/client-core
descrip. : Deprecated PHP Client for using Vonage's API - please use vonage/client-core
keywords : 
versions : * 2.3.3
type     : library
license  : MIT License (MIT) (OSI approved) https://spdx.org/licenses/MIT.html#licenseText
homepage : 
source   : [git] https://github.com/Nexmo/nexmo-php.git bedc32d90871f8347b6a211602e919a1d4d45184
dist     : [zip] https://api.github.com/repos/Nexmo/nexmo-php/zipball/bedc32d90871f8347b6a211602e919a1d4d45184 bedc32d90871f8347b6a211602e919a1d4d45184
path     : /home/ctankersley/tmp/vrsions/vendor/nexmo/client-core
names    : nexmo/client-core

Take note of that version, as it will determine your next steps.

Step 2 - Change the Packages

I have nexmo/client in composer.json

Updating the new packages is fairly painless in most cases. We need to remove the nexmo/client package and replace it with the vonage/client package. This can be done using Composer, as it will handle modifying your composer.json and composer.lock files for you.

composer remove nexmo/client
composer require vonage/client:^2.3

Depending on the version of nexmo/client-core you have installed, you may need to do additional upgrade work. The new packages are designed to continue to work with the \Nexmo namespace, so all your existing code should continue to work. You can schedule a refactor at your leisure.

  • nexmo/client-core >= v2.3.3 - Congrats, you are already using the new code! We just need to change the requested packages. Start using the \Vonage namespace for new code, and refactor existing code at your leisure.
  • nexmo/client-core <= v2.2.3 but >= 2.0.0 - You are on the current major version, so the new packages are compatible with your current code. You should be able to safely upgrade to the newest Vonage packages without any changes to your code. Unless you have a specific reason for staying on an older version of 2.x, there should be no changes to your code. If you had a specific reason for holding back, you will have until October 1st, 2021, to make any necessary changes to your code and may want to schedule additional time for testing the upgrade.
  • nexmo/client-core is not installed - If you have nexmo/client defined but Composer shows that nexmo/client-core is not installed, this means you are on a much older version of the Nexmo library such as 1.x or an early Beta build. There may be significant changes to your codebase if you elect to switch to the Vonage packages, but keep in mind that even today your installation is not supported by the Nexmo packages. We support the currently released major version only, which is our 2.x release line. The 1.x and any earlier versions are not currently receiving any bug or security fixes, so we highly recommend you upgrade as soon as possible.

I have nexmo/client-core in composer.json

Updating the new packages is fairly painless in most cases. We need to remove the nexmo/client-core package and replace it with the vonage/client-core package. This can be done using Composer, as it will handle modifying your composer.json and composer.lock files for you.

composer remove nexmo/client-core
composer require vonage/client-core:^2.3

Depending on the version of nexmo/client-core you have installed, you may need to do additional upgrade work. The new packages are designed to continue to work with the \Nexmo namespace, so all your existing code should continue to work. You can schedule a refactor at your leisure.

We continue to support PSR-18 and HTTPlug-compatible HTTP clients, and if you are using a custom client these should continue to work.

  • nexmo/client-core >= v2.3.3 - Congrats, you are already using the new code! We just need to change the requested packages. Start using the \Vonage namespace for new code, and refactor existing code at your leisure.
  • nexmo/client-core <= v2.2.3 but >= 2.0.0 - You are on the current major version, so the new packages are compatible with your current code. You should be able to safely upgrade to the newest Vonage packages without any changes to your code. Unless you have a specific reason for staying on an older version of 2.x, there should be no changes to your code. If you had a specific reason for holding back, you will have until October 1st, 2021, to make any necessary changes to your code and may want to schedule additional time for testing the upgrade.

Installation

To use the client library you'll need to have created a Vonage account.

To install the PHP client library to your project, we recommend using Composer.

composer require vonage/client

You don't need to clone this repository to use this library in your own projects. Use Composer to install it from Packagist.

If you're new to Composer, here are some resources that you may find useful:

Usage

If you're using Composer, make sure the autoloader is included in your project's bootstrap file:

require_once "vendor/autoload.php";

Create a client with your API key and secret:

$client = new Vonage\Client(new Vonage\Client\Credentials\Basic(API_KEY, API_SECRET));     

For testing purposes you may want to change the URL that vonage/client makes requests to from api.nexmo.com to something else. You can do this by providing an array containing base_api_url as the second parameter when creating a Vonage\Client instance.

$client = new Vonage\Client(
    new Vonage\Client\Credentials\Basic(API_KEY, API_SECRET),
    [
        'base_api_url' => 'https://example.com'
    ]
);

For APIs that would usually hit rest.nexmo.com, supplying a base_rest_url as an option to the constructor will change those requests.

Examples

Sending a Message

To use Vonage's SMS API to send an SMS message, call the $client->sms()->send() method.

A message object is used to create the SMS messages. Each message type can be constructed with the required parameters, and a fluent interface provides access to optional parameters.

$text = new \Vonage\SMS\Message\SMS(VONAGE_TO, VONAGE_FROM, 'Test message using PHP client library');
$text->setClientRef('test-message');

The message object is passed to the send method:

$response = $client->sms()->send($text);

Once sent, the message object can be used to access the response data.

getTo() . ". Balance is now " . $data->getRemainingBalance() . PHP_EOL;">
$data = $response->current();
echo "Sent message to " . $data->getTo() . ". Balance is now " . $data->getRemainingBalance() . PHP_EOL;

Since each SMS message can be split into multiple messages, the response contains an object for each message that was generated. You can check to see how many messages were generated using the standard count() function in PHP. If you want to get the first message, you can use the current() method on the response.

$data = $response->current();
$data->getRemainingBalance();
foreach($response as $index => $data){
    $data->getRemainingBalance();
}

The send example also has full working examples.

Receiving a Message

Inbound messages are sent to your application as a webhook, and the client library provides a way to create an inbound message object from a webhook:

try {
    $inbound = \Vonage\SMS\Webhook\Factory::createFromGlobals();
    error_log($inbound->getText());
} catch (\InvalidArgumentException $e) {
    error_log('invalid message');
}

Signing a Message

You may also like to read the documentation about message signing.

The SMS API supports the ability to sign messages by generating and adding a signature using a "Signature Secret" rather than your API secret. The algorithms supported are:

  • md5hash1
  • md5
  • sha1
  • sha256
  • sha512

Both your application and Vonage need to agree on which algorithm is used. In the dashboard, visit your account settings page and under "API Settings" you can select the algorithm to use. This is also the location where you will find your "Signature Secret" (it's different from the API secret).

Create a client using these credentials, and the algorithm to use, for example:

$client = new Vonage\Client(new Vonage\Client\Credentials\SignatureSecret(API_KEY, SIGNATURE_SECRET, 'sha256'));

Using this client, your SMS API messages will be sent as signed messages.

Verifying an Incoming Message Signature

You may also like to read the documentation about message signing.

If you have message signing enabled for incoming messages, the SMS webhook will include the fields sig, nonce and timestamp. To verify the signature is from Vonage, you create a Signature object using the incoming data, your signature secret and the signature method. Then use the check() method with the actual signature that was received (usually _GET['sig']) to make sure, that it is correct.

$signature = new \Vonage\Client\Signature($_GET, SIGNATURE_SECRET, 'sha256');

// is it valid? Will be true or false
$isValid = $signature->check($_GET['sig']);

Using your signature secret and the other supplied parameters, the signature can be calculated and checked against the incoming signature value.

Starting a Verification

Vonage's Verify API makes it easy to prove that a user has provided their own phone number during signup, or implement second factor authentication during sign in.

You can start a verification process using code like this:

getRequestId();">
$request = new \Vonage\Verify\Request('14845551212', 'My App');
$response = $client->verify()->start($request);
echo "Started verification with an id of: " . $response->getRequestId();

Once the user inputs the pin code they received, call the /check endpoint with the request ID and the pin to confirm the pin is correct.

Controlling a Verification

To cancel an in-progress verification, or to trigger the next attempt to send the confirmation code, you can pass either an existing verification object to the client library, or simply use a request ID:

$client->verify()->trigger('00e6c3377e5348cdaf567e1417c707a5');
$client->verify()->cancel('00e6c3377e5348cdaf567e1417c707a5');

Checking a Verification

In the same way, checking a verification requires the code the user provided, and the request ID:

getStatus() . ")\n"; } catch (Exception $e) { echo "Verification failed with status " . $e->getCode() . " and error text \"" . $e->getMessage() . "\"\n"; }">
try {
    $client->verify()->check('00e6c3377e5348cdaf567e1417c707a5', '1234');
    echo "Verification was successful (status: " . $verification->getStatus() . ")\n";
} catch (Exception $e) {
    echo "Verification failed with status " . $e->getCode()
        . " and error text \"" . $e->getMessage() . "\"\n";
}

Searching For a Verification

You can check the status of a verification, or access the results of past verifications using a request ID. The verification object will then provide a rich interface:

getRequestId() . PHP_EOL; foreach($verification->getChecks() as $check){ echo $check->getDate()->format('d-m-y') . ' ' . $check->getStatus() . PHP_EOL; }">
$client->verify()->search('00e6c3377e5348cdaf567e1417c707a5');

echo "Codes checked for verification: " . $verification->getRequestId() . PHP_EOL;
foreach($verification->getChecks() as $check){
    echo $check->getDate()->format('d-m-y') . ' ' . $check->getStatus() . PHP_EOL;
}

Payment Verification

Vonage's Verify API has SCA (Secure Customer Authentication) support, required by the PSD2 (Payment Services Directive) and used by applications that need to get confirmation from customers for payments. It includes the payee and the amount in the message.

Start the verification for a payment like this:

$request = new \Vonage\Verify\RequestPSD2('14845551212', 'My App');
$response = $client->verify()->requestPSD2($request);
echo "Started verification with an id of: " . $response['request_id'];

Once the user inputs the pin code they received, call the /check endpoint with the request ID and the pin to confirm the pin is correct.

Making a Call

All $client->voice() methods require the client to be constructed with a Vonage\Client\Credentials\Keypair, or a Vonage\Client\Credentials\Container that includes the Keypair credentials:

$basic  = new \Vonage\Client\Credentials\Basic('key', 'secret');
$keypair = new \Vonage\Client\Credentials\Keypair(
    file_get_contents(VONAGE_APPLICATION_PRIVATE_KEY_PATH),
    VONAGE_APPLICATION_ID
);

$client = new \Vonage\Client(new \Vonage\Client\Credentials\Container($basic, $keypair));

You can start a call using an OutboundCall object:

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone('14843331234'),
    new \Vonage\Voice\Endpoint\Phone('14843335555')
);
$outboundCall
    ->setAnswerWebhook(
        new \Vonage\Voice\Webhook('https://example.com/answer')
    )
    ->setEventWebhook(
        new \Vonage\Voice\Webhook('https://example.com/event')
    )
;

$response = $client->voice()->createOutboundCall($outboundCall);

Building a call with NCCO Actions

Full parameter lists for NCCO Actions can be found in the Voice API Docs.

Each of these examples uses the following structure to add actions to a call:

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone('14843331234'),
    new \Vonage\Voice\Endpoint\Phone('14843335555')
);
$ncco = new NCCO();

//ADD ACTIONS TO THE NCCO OBJECT HERE

$outboundCall->setNCCO($ncco);

$response = $client->voice()->createOutboundCall($outboundCall);

Record a call

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone('14843331234'),
    new \Vonage\Voice\Endpoint\Phone('14843335555')
);

$ncco = new NCCO();
$ncco->addAction(\Vonage\Voice\NCCO\Action\Record::factory([
    'eventUrl' => 'https://webhook.url'
]);
$outboundCall->setNCCO($ncco);

$response = $client->voice()->createOutboundCall($outboundCall);

Your webhook url will receive a payload like this:

", "size": 27918, "recording_uuid": " ", "end_time": "2020-10-29T14:30:31Z", "conversation_uuid": " ", "timestamp": "2020-10-29T14:30:31.619Z" }">
{
  "start_time": "2020-10-29T14:30:24Z",
  "recording_url": "https://api.nexmo.com/v1/files/
      
       ",
  "size": 27918,
  "recording_uuid": "
       
        ",
  "end_time": "2020-10-29T14:30:31Z",
  "conversation_uuid": "
        
         ",
  "timestamp": "2020-10-29T14:30:31.619Z"
}

        
       
      

You can then fetch and store the recording like this:

$recordingId = '
   
    ';
$recordingUrl = 'https://api.nexmo.com/v1/files/' . $recordingId;
$data = $client->get($recordingUrl);
file_put_contents($recordingId.'.mp3', $data->getBody());

   

Send a text to voice call

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone('14843331234'),
    new \Vonage\Voice\Endpoint\Phone('14843335555')
);

$ncco = new NCCO();
$ncco->addAction(new \Vonage\Voice\NCCO\Action\Talk('This is a text to speech call from Vonage'));
$outboundCall->setNCCO($ncco);

$response = $client->voice()->createOutboundCall($outboundCall);

Stream an audio file on a call

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone('14843331234'),
    new \Vonage\Voice\Endpoint\Phone('14843335555')
);

$ncco = new NCCO();
$ncco->addAction(new \Vonage\Voice\NCCO\Action\Stream('https://my-mp3.url'));
$outboundCall->setNCCO($ncco);

$response = $client->voice()->createOutboundCall($outboundCall);

Collect user input from a call

Supports keypad entry as well as voice. NB. the input action must follow an action with bargeIn set to true

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone('14843331234'),
    new \Vonage\Voice\Endpoint\Phone('14843335555')
);

$ncco = new NCCO();

$ncco->addAction(\Vonage\Voice\NCCO\Action\Talk::factory('Please record your name.',[
  'bargeIn' => true,
]));

$ncco->addAction(\Vonage\Voice\NCCO\Action\Input::factory([
  'eventUrl' => 'https://webhook.url',
  'type' => [
    'speech',
  ],
  'speech' => [
    'endOnSilence' => true,
  ],
]));

$outboundCall->setNCCO($ncco);

$response = $client->voice()->createOutboundCall($outboundCall);

The webhook URL will receive a payload containing the input from the user with relative confidence ratings for speech input.

Send a notification to a webhook url

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone('14843331234'),
    new \Vonage\Voice\Endpoint\Phone('14843335555')
);

$ncco = new NCCO();    
$ncco->addAction(new \Vonage\Voice\NCCO\Action\Talk('We are just testing the notify function, you do not need to do anything.'));
$ncco->addAction(new \Vonage\Voice\NCCO\Action\Notify([
  'foo' => 'bar',
], new Vonage\Voice\Webhook('https://webhook.url')));
$outboundCall->setNCCO($ncco);

$response = $client->voice()->createOutboundCall($outboundCall);

The webhook URL will receive a payload as specified in the request.

Fetching a Call

You can fetch a call using a Vonage\Call\Call object, or the call's UUID as a string:

$call = $client->voice()->get('3fd4d839-493e-4485-b2a5-ace527aacff3');

echo $call->getDirection();

You can also search for calls using a Filter.

$filter = new \Vonage\Voice\Filter\VoiceFilter();
$filter->setStatus('completed');
foreach($client->search($filter) as $call){
    echo $call->getDirection();
}

Creating an Application

Application are configuration containers. You can create one using a simple array structure:

$application = new \Vonage\Application\Application();
$application->fromArray([
 'name' => 'test application',
 'keys' => [
     'public_key' => '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCA\nKOxjsU4pf/sMFi9N0jqcSLcjxu33G\nd/vynKnlw9SENi+UZR44GdjGdmfm1\ntL1eA7IBh2HNnkYXnAwYzKJoa4eO3\n0kYWekeIZawIwe/g9faFgkev+1xsO\nOUNhPx2LhuLmgwWSRS4L5W851Xe3f\nUQIDAQAB\n-----END PUBLIC KEY-----\n'
 ],
 'capabilities' => [
     'voice' => [
         'webhooks' => [
             'answer_url' => [
                 'address' => 'https://example.com/answer',
                 'http_method' => 'GET',
             ],
             'event_url' => [
                 'address' => 'https://example.com/event',
                 'http_method' => 'POST',
             ],
         ]
     ],
     'messages' => [
         'webhooks' => [
             'inbound_url' => [
                 'address' => 'https://example.com/inbound',
                 'http_method' => 'POST'

             ],
             'status_url' => [
                 'address' => 'https://example.com/status',
                 'http_method' => 'POST'
             ]
         ]
     ],
     'rtc' => [
         'webhooks' => [
             'event_url' => [
                 'address' => 'https://example.com/event',
                 'http_method' => 'POST',
             ],
         ]
     ],
     'vbc' => []
 ]
]);

$client->applications()->create($application);

You can also pass the client an application object:

$a = new Vonage\Application\Application;

$a->setName('PHP Client Example');
$a->getVoiceConfig()->setWebhook('answer_url', 'https://example.com/answer', 'GET');
$a->getVoiceConfig()->setWebhook('event_url', 'https://example.com/event', 'POST');
$a->getMessagesConfig()->setWebhook('status_url', 'https://example.com/status', 'POST');
$a->getMessagesConfig()->setWebhook('inbound_url', 'https://example.com/inbound', 'POST');
$a->getRtcConfig()->setWebhook('event_url', 'https://example.com/event', 'POST');
$a->disableVbc();

$client->applications()->create($a);

Fetching Applications

You can iterate over all your applications:

foreach($client->applications()->getAll() as $application){
    echo $application->getName() . PHP_EOL;
}

Or you can fetch an application using a string UUID, or an application object.

$application = $client->applications()->get('1a20a124-1775-412b-b623-e6985f4aace0');

Updating an Application

Once you have an application object, you can modify and save it.

$application = $client->applications()->get('1a20a124-1775-412b-b623-e6985f4aace0');

$application->setName('Updated Application');
$client->applications()->update($application);

List Your Numbers

You can list the numbers owned by your account and optionally include filtering:

search_pattern:

  • 0 - the number begins with pattern
  • 1 - the number includes pattern
  • 2 - the number ends with pattern
$filter = new \Vonage\Numbers\Filter\OwnedNumbers();
$filter
    ->setPattern(234)
    ->setSearchPattern(\Vonage\Numbers\Filter\OwnedNumbers::SEARCH_PATTERN_CONTAINS)
;
$response = $client->numbers()->searchOwned($filter);

has_application:

  • true - The number is attached to an application
  • false - The number is not attached to an application
$filter = new \Vonage\Numbers\Filter\OwnedNumbers();
$filter->setHasApplication(true);
$response = $client->numbers()->searchOwned($filter);

application_id:

  • Supply an application ID to get all the numbers associated with the requesting application
numbers()->searchOwned($filter);">
$filter = new \Vonage\Numbers\Filter\OwnedNumbers();
$filter->setApplicationId("66c04cea-68b2-45e4-9061-3fd847d627b8");
$response = $client->numbers()->searchOwned($filter);

Search Available Numbers

You can search for numbers available to purchase in a specific country:

$numbers = $client->numbers()->searchAvailable('US');

By default, this will only return the first 10 results. You can add an additional \Vonage\Numbers\Filter\AvailableNumbers filter to narrow down your search.

Purchase a Number

To purchase a number, you can pass in a value returned from number search:

$numbers = $client->numbers()->searchAvailable('US');
$number = $numbers->current();
$client->numbers()->purchase($number->getMsisdn(), $number->getCountry());

Or you can specify the number and country manually:

$client->numbers()->purchase('14155550100', 'US');

Update a Number

To update a number, use numbers()->update and pass in the configuration options you want to change. To clear a setting, pass in an empty value.

$number = $client->numbers()->get(VONAGE_NUMBER);
$number
    ->setAppId('1a20a124-1775-412b-b623-e6985f4aace0')
    ->setVoiceDestination('447700900002', 'tel')
    ->setWebhook(
        \Vonage\Number\Number::WEBHOOK_VOICE_STATUS,
        'https://example.com/webhooks/status'
    )
    ->setWebhook(
        \Vonage\Number\Number::WEBHOOK_MESSAGE,
        'https://example.com/webhooks/inbound-sms'
    )
;
$client->numbers()->update($number);
echo "Number updated" . PHP_EOL;

Cancel a Number

To cancel a number, provide the msisdn:

$client->numbers()->cancel('447700900002');

Managing Secrets

An API is provided to allow you to rotate your API secrets. You can create a new secret (up to a maximum of two secrets) and delete the existing one once all applications have been updated.

To get a list of the secrets:

getId() . " (created " . $secret->getCreatedAt() .")\n"; }">
$secretsCollection = $client->account()->listSecrets(API_KEY);
/** @var \Vonage\Account\Secret $secret */
foreach($secretsCollection->getSecrets() as $secret) {
    echo "ID: " . $secret->getId() . " (created " . $secret->getCreatedAt() .")\n";
}

You can create a new secret (the created dates will help you know which is which):

$client->account()->createSecret(API_KEY, 'awes0meNewSekret!!;');

And delete the old secret (any application still using these credentials will stop working):

try {
    $response = $client->account()->deleteSecret(API_KEY, 'd0f40c7e-91f2-4fe0-8bc6-8942587b622c');
} catch(\Vonage\Client\Exception\Request $e) {
    echo $e->getMessage();
}

Pricing

Prefix Pricing

If you know the prefix of a country you want to call, you can use the prefix-pricing endpoint to find out costs to call that number. Each prefix can return multiple countries (e.g. 1 returns US, CA and UM):

$results = $client->account()->getPrefixPricing('1');
foreach ($results as $price) {
    echo $price->getCountryCode().PHP_EOL;
    echo $price->getCountryName().PHP_EOL;
    foreach ($price->getNetworks() as $network) {
        echo $network->getName() .' :: '.$network->getCode().' :: '.$network->getPrefixPrice().PHP_EOL;
    }
    echo "----------------".PHP_EOL;
}

Check your Balance

Check how much credit remains on your account:

$response = $client->account()->getBalance();
echo round($response->getBalance(), 2) . " EUR\n";

View and Change Account Configuration

Inspect the current settings on the account:

$response = $client->account()->getConfig();
print_r($response->toArray());

Update the default callback URLs for incoming SMS messages and delivery receipts:

"http://example.com/webhooks/incoming-sms", "dr_callback_url" => "http://example.com/webhooks/delivery-receipt" ]); print_r($response->toArray());">
$response = $client->account()->updateConfig([
    "sms_callback_url" => "http://example.com/webhooks/incoming-sms",
    "dr_callback_url" => "http://example.com/webhooks/delivery-receipt"
]);
print_r($response->toArray());

Get Information About a Number

The Number Insights API allows a user to check that a number is valid and to find out more about how to use it.

Basic and Standard Usage

You can use either the basic() or standard() methods (an advanced() method is available, but it is recommended to use the async option to get advanced info), like this:

try {
  $insights = $client->insights()->basic(PHONE_NUMBER);

  echo $insights->getNationalFormatNumber();
} catch (Exception $e) {
  // for the Vonage-specific exceptions, try the `getEntity()` method for more diagnostic information
}

The data is returned in the $insights variable in the example above.

Advanced Usage

To get advanced insights, use the async feature and supply a URL for the webhook to be sent to:

try {
  $client->insights()->advancedAsync(PHONE_NUMBER, 'http://example.com/webhooks/number-insights');
} catch (Exception $e) {
  // for the Vonage-specific exceptions, try the `getEntity()` method for more diagnostic information
}

Check out the documentation for what to expect in the incoming webhook containing the data you requested.

Supported APIs

API API Release Status Supported?
Account API General Availability
Alerts API General Availability
Application API General Availability
Audit API Beta
Conversation API Beta
Dispatch API Beta
External Accounts API Beta
Media API Beta
Messages API Beta
Number Insight API General Availability
Number Management API General Availability
Pricing API General Availability
Redact API General Availability
Reports API Beta
SMS API General Availability
Verify API General Availability
Voice API General Availability

Troubleshooting

Checking for Deprecated Features

Over time, the Vonage APIs evolve and add new features, change how existing features work, and deprecate and remove older methods and features. To help developers know when deprecation changes are being made, the SDK will trigger an E_USER_DEPRECATION warning. These warnings will not stop the execution of code, but can be an annoyance in production environments.

To help with this, by default these notices are suppressed. In development, you can enable these warnings by passing an additional configuration option to the \Vonage\Client constructor, called show_deprecations. Enabling this option will show all deprecation notices.

$client = new Vonage\Client(
    new Vonage\Client\Credentials\Basic(API_KEY, API_SECRET),
    [
        'show_deprecations' => true
    ]
);

If you notice an excessive amount of deprecation notices in production environments, make sure the configuration option is absent, or at least set to false.

unable to get local issuer certificate

Some users have issues making requests due to the following error:

Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)'

This is due to some PHP installations not shipping with a list of trusted CA certificates. This is a system configuration problem, and not specific to either cURL or Vonage.

IMPORTANT: In the next paragraph we provide a link to a CA certificate bundle. Vonage do not guarantee the safety of this bundle, and you should review it yourself before installing any CA bundle on your machine.

To resolve this issue, download a list of trusted CA certificates (e.g. the curl bundle) and copy it on to your machine. Once this is done, edit php.ini and set the curl.cainfo parameter:

# Linux/MacOS
curl.cainfo = "/etc/pki/tls/cacert.pem"
# Windows
curl.cainfo = "C:\php\extras\ssl\cacert.pem"

Pass custom HTTP client

We allow use of any HTTPlug adapter or PSR-18 compatible HTTP client, so you can create a client with alternative configuration if you need it, for example to take account of a local proxy, or deal with something else specific to your setup.

Here's an example that reduces the default timeout to 5 seconds to avoid long delays if you have no route to our servers:

$adapter_client = new Http\Adapter\Guzzle6\Client(new GuzzleHttp\Client(['timeout' => 5]));
$vonage_client = new Vonage\Client(new Vonage\Client\Credentials\Basic($api_key, $api_secret), [], $adapter_client);

Accessing Response Data

When things go wrong, you'll receive an Exception. The Vonage exception classes Vonage\Client\Exception\Request and Vonage\Client\Exception\Server support an additional getEntity() method which you can use in addition to getCode() and getMessage() to find out more about what went wrong. The entity returned will typically be an object related to the operation, or the response object from the API call.

Composer installation fails due to Guzzle Adapter

If you have a conflicting package installation that cannot co-exist with our recommended guzzlehttp/guzzle package, then you may install the package vonage/client-core along with any package satisfying the php-http/client-implementation requirement.

See the Packagist page for client-implementation for options.

Enabling Request/Response Logging

Our client library has support for logging the request and response for debugging via PSR-3 compatible logging mechanisms. If the debug option is passed into the client and a PSR-3 compatible logger is set in our client's service factory, we will use the logger for debugging purposes.

$client = new \Vonage\Client(new \Vonage\Client\Credentials\Basic('abcd1234', 's3cr3tk3y'), ['debug' => true]);
$logger = new \Monolog\Logger('test');
$logger->pushHandler(new \Monolog\Handler\StreamHandler(__DIR__ . '/log.txt', \Monolog\Logger::DEBUG));
$client->getFactory()->set(\PSR\Log\LoggerInterface::class, $logger);

ENABLING DEBUGING LOGGING HAS THE POTENTIAL FOR LOGGING SENSITIVE INFORMATION, DO NOT ENABLE IN PRODUCTION

Contributing

This library is actively developed, and we love to hear from you! Please feel free to create an issue or open a pull request with your questions, comments, suggestions and feedback.

You might also like...
Instantly connects the Subtext text messaging service with Paid Memberships Pro.

INSTANTLY CONNECTS AND INTEGRATES THE SUBTEXT TEXT MESSAGING SERVICE WITH PAID MEMBERSHIPS PRO. This plugin instantly and easily connects, and integra

Twitter REST API for PHP 5.3+

README The Wid'op Twitter REST library is a modern PHP 5.3+ API allowing you to easily interact with Twitter 1.1. In order to sign your request with t

Interacting with Mastodon's REST API for Kirby v3

Kirby3 Mastodon This plugin provides access to your Mastodon statuses, called 'toots'. Getting started Use one of the following methods to install & u

This library is for integration with Salesforce via REST API.

xsolve-pl/salesforce-client Introduction This library is for integration with Salesforce via REST API. Licence This library is under the MIT license.

This package help you build your REST API documentation.

Laravel API Doc This package help you build your REST API documentation. Installation You can install the package via composer: composer require axeld

A Laravel package to help integrate Shopware PHP SDK much more easier

Shopware 6 Laravel SDK A Laravel package to help integrate Shopware PHP SDK much more easier Installation Install with Composer composer require sas/s

DigitalOcean API v2 client for Symfony and API Platform

DigitalOcean Bundle for Symfony and API Platform DunglasDigitalOceanBundle allows using the DigitalOcean API from your Symfony and API Platform projec

API client for ThePay - payment gate API
API client for ThePay - payment gate API

This is the official highly compatible public package of The Pay SDK which interacts with The Pay's REST API. To get started see examples below.

A simple PHP GitHub API client, Object Oriented, tested and documented.

PHP GitHub API A simple Object Oriented wrapper for GitHub API, written with PHP. Uses GitHub API v3 & supports GitHub API v4. The object API (v3) is

Comments
  • Added migration notes for moving to vonage packages

    Added migration notes for moving to vonage packages

    Description

    This adds a notice that this repo is officially in maintenance mode and points users to https://github.com/vonage/vonage-php-sdk-core. It also adds migration instructions to help users upgrade.

    Motivation and Context

    As we move forward with the rebrand, we need to help customers update. This provides notes and instructions. Looking for copy editing and notes on this for clarity.

    How Has This Been Tested?

    It's a textual change

    Types of changes

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [ ] My code follows the code style of this project.
    • [ ] My change requires a change to the documentation.
    • [x] I have updated the documentation accordingly.
    • [x] I have read the CONTRIBUTING document.
    • [ ] I have added tests to cover my changes.
    • [ ] All new and existing tests passed.
    opened by dragonmantank 1
  • Fix Connect action eventUrl

    Fix Connect action eventUrl

    eventUrl should be an array, not string

    Description

    Motivation and Context

    Bug fix

    How Has This Been Tested?

    Example Output or Screenshots (if appropriate):

    Types of changes

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [x] My code follows the code style of this project.
    • [ ] My change requires a change to the documentation.
    • [ ] I have updated the documentation accordingly.
    • [ ] I have read the CONTRIBUTING document.
    • [ ] I have added tests to cover my changes.
    • [ ] All new and existing tests passed.
    opened by abelzx 1
Releases(2.9.2)
  • 2.9.2(Apr 30, 2021)

  • 2.9.1(Apr 26, 2021)

    2.9.1

    Fixed

    • #282 - SMS Throttling response is now handled as milliseconds instead of seconds
    • #282 - Fixed regex to not consume API rate limiting error and basically time out PHP scripts
    Source code(tar.gz)
    Source code(zip)
  • 2.9.0(Apr 22, 2021)

  • 2.8.1(Apr 16, 2021)

    2.8.1

    Fixed

    • #278 - Fixed issue retrieving Conversations and Users clients where the service locator didn't know what to do

    Changed

    • #283 - Moved auth logic to individual handlers, to better prepare for a fix where Containers do not allow Signature and Token auth
    Source code(tar.gz)
    Source code(zip)
  • 2.8.0(Mar 1, 2021)

    Added

    • #272 - Added support for PSR-3 compatible logging solutions and a new debug feature to log requests/responses
    • #274 - Added support for the detail field on some new Voice API incoming events (https://developer.nexmo.com/voice/voice-api/webhook-reference#event-webhook)
    • #273 - Added new content-id and entity-id fields to support regional SMS requirements, and a shortcut for enabling DLT on Indian-based SMS
    Source code(tar.gz)
    Source code(zip)
  • 2.7.1(Jan 21, 2021)

  • v2.7.0(Nov 30, 2020)

  • v2.6.0(Nov 18, 2020)

    2.6.0

    Don't be scared off by this large release! Most of it is under-the-hood syntax cleanup. Thank you to everyone during Hacktoberfest for the cleanup and help with the SDK!

    The big addition was we added support for VAPI Language and Style (https://developer.nexmo.com/voice/voice-api/guides/text-to-speech), and fixed a bug when manually setting the Verify code length.

    As a reminder, this library has entered maintenance support, so please begin your migration to vonage/client or vonage/client-core as soon as possible.

    Added

    • Added support for Language and Style for NCCO Talk action

    Changed

    • Dropped support for PHPUnit 7
    • Added missing PHPDoc blocks
    • Added missing return type hints
    • Replaced qualifiers with imports
    • Updated and optimized examples
    • Applied multiple code optimizations (especially for PHP 7.2+) and simplified some logic
    • Updated code styling to match PSR standards
    • Re-ordered imports where necessary
    • Updated tests to get rid of deprecation messages
    • Fixed namespace declarations in tests
    • Updated code style to PSR-12
    • Updated phpunit.xml.dist
    • Added Roave Security Advisories as dev-requirement to prevent usage of packages with known security vulnerabilities
    • Replaced estahn/phpunit-json-assertions with martin-helmich/phpunit-json-assert due do compatibility issues with PHPUnit
    • Removed test build for PHP 7.1 in .travis.yml
    • Added missing punctuation in CONTRIBUTING.md
    • Updated contact email address in CODE_OF_CONDUCT.md

    Deprecated

    • Deprecated use of VoiceName for NCCO Talk action

    Fixed

    • Fixed namespaces (Zend => Laminas, Nexmo => Vonage)
    • Fixed condition in Verify\Request::setCodeLength
    • Fixed typos and some wording in README.md

    Removed

    • Removed examples/ directory as the code snippets repo is much more up-to-date
    Source code(tar.gz)
    Source code(zip)
  • 2.5.0(Oct 28, 2020)

  • 2.4.1(Oct 2, 2020)

    2.4.1

    Changed

    • #256 - Added support for PHPUnit 8

    Fixed

    • #253, #254 - Fixed some typos in the README
    • #255 - \Vonage\Numbers\Client::searchAvailable() now correctly handles filters using FilterInterface
    Source code(tar.gz)
    Source code(zip)
  • 2.4.0(Sep 10, 2020)

    This release includes a minimum version bump to PHP 7.2, as 7.1 is nearing full EOL. This also better allows us to support Guzzle 7 out of the box.

    Changed

    • #250 - Bumped minimum PHP version to 7.0
    • #250 - Now supports Guzzle 7 automatically, and swaps to Guzzle 7 as a dev dependency
    Source code(tar.gz)
    Source code(zip)
  • 2.3.3(Sep 10, 2020)

    Nothing related to async, sorry.

    This release contains two major milestones!

    The first is where all the code is now under the \Vonage namespace! Do not worry though, any existing code using the \Nexmo namespace will still continue to work thanks to a new vonage/nexmo-bridge package which will translate between the two namespaces. The next time you update your Nexmo client to this or any subsequent 2.x releases, your code will continue to work with no changes.

    It is recommended to start using the \Vonage namespace in any new code you create, but even new features added (like our PSD2 feature in this release) will work under either namespace. Developers will be able to update at their own pace.

    The second is that we have complete parity between this repository and the Vonage repo, and this repo and package is now going into bug/security-fix-only mode. For the next 12 months, nexmo/client and nexmo/client-core will be only receiving bug or security fixes. The good news is that this release can allow you, today, to use the \Vonage and \Nexmo namespaces at the same time. Your old code will continue to function without any changes, and you can work the namespace change right away with new code. Upgrading should be as easy as replacing \Vonage with \Nexmo (your mileage may vary).

    We recommend that developers switch to vonage/client or vonage/client-core as soon as they can, but any bugs or security fixes will still be ported to the Nexmo packages.

    Added

    • Support for the PSD2 Verify endpoints for EU customers
    • vonage/nexmo-bridge as a dependency so \Nexmo namespaced code works with the new \Vonage namespace
    • Calls using \Vonage\Client\APIResource can now specify headers for individual requests
    • #247 - Fixed missing fields on Standard/Advanced number insight getters
    • #248 - Added \Vonage\Client\MapFactory::make() to always instatiate new objects

    Changed

    • Namespace changed from \Nexmo to \Vonage for all classes, interfaces, and traits

    Fixed

    • Base URL overrides were not being pushed up properly
    • JSON payload for transferring via NCCO or URL was malformed
    • #246 - Fixed badge URLs in README
    • #248 - Fixed type in URL for Account Client Factory
    • #252 - Connect action's eventUrl was being set as a string, changed to single element array of strings
    Source code(tar.gz)
    Source code(zip)
  • 2.2.3(Aug 21, 2020)

  • 2.2.2(Aug 21, 2020)

  • 2.2.1(Aug 21, 2020)

    Minor bugfix release based on feedback:

    Added

    • Allow Conversations NCCO to set event URL information
    • Added missing Notify webhook and new ASR code

    Changed

    • NCCOs now set let default options

    Removed

    • Redundant comments in client for sms() and verify() clients
    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Aug 21, 2020)

    2.2.0

    This release focuses on deprecation of dead and old code, and preps many internal changes in regards to v3.0.0. Where possible upcoming v3.0.0 changes were backported where backward-compatibility could be maintained.

    Added

    • New Voice and SMS interfaces, accessible through $client->voice() and $client->sms(), respectively
    • Added user deprecation warnings, which can be turned on and off via the Nexmo\Client "show_deprecations" config option. This can help devs update in preparation in v3.0.0, and will be utilized in the future as things are deprecated.
    • Many objects now have a toArray() serialization method, to discourage direct use of jsonSerialize()
    • Many objects now support a fromArray() hydration method
    • Better incoming webhook support for SMS and Voice events
    • NCCO builder for Voice

    Changed

    • API handling code has been conglomerated in Nexmo\Client\APIResource and Nexmo\Entity\IterableAPICollection
    • All APIs ported over to the new API handling layer
    • Internal Service Locator Nexmo\Client\Factory\MapFactory is now PSR-11 compliant, and can use factories
    • Most Verify methods in the client now prefer string Request IDs
    • Verify now prefers Nexmo\Verify\Request for starting new Verification requests

    Deprecated

    For a detailed list of things that may impact an application, enable the show_deprecations Nexmo\Client option to see deprecation notices for specific code flows.

    • Most forms of array access are now deprecated
    • Using service layers like $client->messages($filter) to search has been deprecated in favor of bespoke search methods
    • Requests/Responses on exceptions and entities are deprecated, and now exist in the service layer or collection
    • Most methods that took raw arrays now prefer objects
    • Nexmo\Verify\Verification objects full functionality has been deprecated, and will be used only as a value object for search requests in the future
    • Nexmo\Conversations and Nexmo\User have been deprecated and will be removed in the future as the feature is in Beta status and has diverged from this implementation
    • Nexmo\Voice\Call and Nexmo\Voice\Message have been deprecated and will be removed in the future as the TTS API is deprecated
    • SMS searching has been deprecated and will be removed in a future update

    Removed

    • No features or classes have been removed in this update, it is functionally compatible with v2.1.0 other than deprecation notices and new features.

    Fixed

    • No direct bugs have been fixed as this release was designed to be as compatible with v2.1.0 as possible, however:
      • #177 should be better handled by a centralized Nexmo\Client\Exception\ThrottleException and has been implemented in SMS and the Numbers API
      • #219 is implicitly fixed in Nexmo\SMS\Client::send() as it now returns a fully hydrated collection object as a response, however this needs to be updated in Laravel itself via an update to nexmo/laravel and laravel/nexmo-notification-channel
      • #221 is implicitly fixed in Nexmo\SMS\Client::send() as it now returns a fully hydrated collection object that is much more up-front it is not a single object
      • #227 is implicitly fixed in Nexmo\SMS\Webhook\InboundSMS

    Security

    • There were no known security vulnerabilities reported
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Aug 21, 2020)

    This release contains a few quality of life changes for the SDK. We have added support for sending a Workflow ID to our Verify API, as well as the ability to search your existing numbers for ones that are attached to an application or not, or for all the numbers attached to a specific application.

    Added

    • Added support for Workflow ID for Verify
    • Added support for searching for numbers via has_application and application_id

    Changed

    • No functional changes were added

    Deprecated

    • No new deprecations were added

    Fixed

    • No additional fixes were added

    Removed

    • No functionality has been removed

    Security

    • No new security fixes were added
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(Aug 21, 2020)

    This release contains a few under-the-hood changes. The largest is the bump to PHP 7.1, which may affect some customers. If you are on an older version of PHP, you will be limited to SDK v1.8.1 or lower.

    We have also renamed this package into nexmo/client-core and added a new wrapper package to replace nexmo/client. For most customers this process should be seamless, and composer should automatically handle the change. This change is made to remove a collision between our package and others that may supply Guzzle themselves.

    If you use the SDK to search for numbers, please be advised that we did change the response for when no numbers are found. It will now return an empty array instead of throwing an exception. Other searches are not affected and will continue to throw their original exceptions.

    Exceptions will now support an additional getEntity() method that returns additional information about what happened. In many cases this is the response from the server, to make it easier to understand the API error message. Exceptions continue to return error codes and messages like before, but the getEntity() method can be used for better context during error handling.

    Please check the rest of the changelog for a full list of changes.

    Added

    • Now grab the version of the SDK from composer.json for the User Agent
    • Exceptions now support a getEntity() method to get more information during errors

    Changed

    • Changed minimum version to PHP 7.1
    • Renamed package to nexmo/client-core
    • Bumped to PHPUnit 7.4
    • Now return an empty array when searching for numbers and none are found. This no longer throws an exception.

    Deprecated

    • No new deprecations were added

    Fixed

    • Improved error handling for Number Insights

    Removed

    • Removed direct Guzzle dependency, and moved it to nexmo/client

    Security

    • No new security fixes were added
    Source code(tar.gz)
    Source code(zip)
  • 1.8.1(Aug 21, 2020)

  • 1.8.0(Aug 21, 2020)

  • 1.7.0(Aug 21, 2020)

    • Add support for supplying an NCCO inline when placing a call
    $call = new Call();
    $call->setTo('TO_NUMBER')
         ->setFrom('FROM_NUMBER')
         ->setNcco([
            [
                'action' => 'talk',
                'text' => 'This is a text to speech call from Nexmo'
            ]
          ]);
    $client->calls()->create($call);
    
    Source code(tar.gz)
    Source code(zip)
  • 1.6.3(Aug 21, 2020)

  • 1.6.2(Aug 21, 2020)

  • 1.6.1(Aug 21, 2020)

  • 1.6.0(Aug 21, 2020)

  • 1.5.2(Aug 21, 2020)

  • 1.5.1(Aug 21, 2020)

  • 1.5.0(Aug 21, 2020)

  • 1.4.0(Aug 21, 2020)

    • Add support for the Redact API, which allows you to redact information about your SMS, Voice, Verify (and more!) requests on the Nexmo platform
    Source code(tar.gz)
    Source code(zip)
  • 1.3.2(Aug 21, 2020)

playSMS is a web interface for SMS gateways and bulk SMS services

README Latest development release is playSMS version 1.4.4-beta4 Latest stable release is playSMS version 1.4.3 Official project website: https://play

playSMS 655 Sep 22, 2022
Search music with voice

Configuration: Open the index.php file and paste the bot token: define('API_KEY', 'TOKEN'); Login to Ahangify and create an account Open the login.php

#[A]ref 1 Jul 21, 2022
A simple Object Oriented PHP Client for Termii SMS API

Termii Client A simple Object Oriented PHP Client for Termii SMS API. Uses Termii API. Requirements PHP >= 7.2 Guzzlehttp ~6|~7 Installation Via Compo

Ilesanmi Olawale Adedotun 5 Feb 24, 2022
oursms.app client library that allows you to send SMS

Oursms laravel client https://oursms.app client library that allows you to send SMS Installation Install oursms client with composer composer requir

Khalid Mohammad 11 Aug 27, 2022
Xendit REST API Client for PHP - Card, Virtual Account, Invoice, Disbursement, Recurring Payments, Payout, EWallet, Balance, Retail Outlets Services

Xendit REST API Client for PHP - Card, Virtual Account, Invoice, Disbursement, Recurring Payments, Payout, EWallet, Balance, Retail Outlets Services

Xendit 88 Sep 18, 2022
یک پکیج لاراول برای ارسال ، دریافت و... پیامک (SMS)

پکیج لاراول SMS با استفاده از این پکیج می توانید به پنل خود در وب سایت sms.ir متصل شوید و یک سیستم ارسال و دریافت SMS ایرانی در لاراول داشته باشید. به

Ali Zeinodin 16 May 14, 2022
Google-api-php-client - A PHP client library for accessing Google APIs

Google APIs Client Library for PHP Reference Docs https://googleapis.github.io/google-api-php-client/main/ License Apache 2.0 The Google API Client Li

Google APIs 8.3k Sep 27, 2022
PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

Sergey Bykov 63 Feb 14, 2022
A PHP library for communicating with the Twilio REST API and generating TwiML.

twilio-php The default branch name for this repository has been changed to main as of 07/27/2020. Documentation The documentation for the Twilio API c

Twilio 1.4k Sep 28, 2022
PHP library to use IOTA REST API to help node management and tangle queries

iota.php About PHP library to use IOTA REST API to help node management and tangle queries. Please be aware that this library is in an early developme

IOTA Community 44 Aug 17, 2022