This library requires a minimum PHP version of 7.4
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.
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
Note that this actually points to a wrapper library that includes an HTTP client -and- this core library. You can install this library directly from Composer if you wish, with the ability to choose the HTTP client your project uses.
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:
- Composer's Getting Started page from Composer project's documentation.
- A Beginner's Guide to Composer from the good people at ScotchBox.
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.
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.
$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.
Inbound messages are sent to your application as a webhook. 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');
}
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.
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.
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:
$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.
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');
In the same way, checking a verification requires the code the user provided, and the request ID:
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";
}
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:
$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;
}
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.
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);
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);
$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:
{
"start_time": "2020-10-29T14:30:24Z",
"recording_url": "https://api.nexmo.com/v1/files/<recording-id>",
"size": 27918,
"recording_uuid": "<recording-id>",
"end_time": "2020-10-29T14:30:31Z",
"conversation_uuid": "<conversation-id>",
"timestamp": "2020-10-29T14:30:31.619Z"
}
You can then fetch and store the recording like this:
$recordingId = '<recording-id>';
$recordingUrl = 'https://api.nexmo.com/v1/files/' . $recordingId;
$data = $client->get($recordingUrl);
file_put_contents($recordingId.'.mp3', $data->getBody());
$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);
$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);
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.
$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.
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();
}
Application are configuration containers. You can create one using an 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);
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');
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);
You can list the numbers owned by your account and optionally include filtering:
search_pattern
:
0
- the number begins withpattern
1
- the number includespattern
2
- the number ends withpattern
$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 applicationfalse
- 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
$filter = new \Vonage\Numbers\Filter\OwnedNumbers();
$filter->setApplicationId("66c04cea-68b2-45e4-9061-3fd847d627b8");
$response = $client->numbers()->searchOwned($filter);
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.
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');
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;
To cancel a number, provide the msisdn
:
$client->numbers()->cancel('447700900002');
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:
$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();
}
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 how much credit remains on your account:
$response = $client->account()->getBalance();
echo round($response->getBalance(), 2) . " EUR\n";
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:
$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());
The Number Insights API allows a user to check that a number is valid and to find out more about how to use it.
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.
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.
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 | ✅ |
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
.
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"
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);
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.
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.
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
This library has a full test suite designed to be run with PHPUnit.
To run, use composer:
composer test
Please note: this test suite is large, and may require a considerable amount of memory to run. If you encounter the "too many files open" error in MacOS or Linux, there is a hack to increase the amount of file pointers permitted. Increase the amount of files that can be open by entering the following on the command line (10240 is the maximum amount of pointers MacOS will open currently):
ulimit -n 10240
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.