PHP code example of vonage / client-core

1. Go to this page and download the library: Download vonage/client-core library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

vonage / client-core example snippets




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

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


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

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

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

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

$sms = new \Vonage\SMS\Message\SMS('123', '456', 'is this gsm7?');

if (Vonage\SMS\Message\SMS::isGsm7($text)) {
    $sms->setType('text');
} else {
    $sms->setType('unicode');
}

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

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

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

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

$whatsAppText = new Vonage\Messages\Channel\WhatsApp\WhatsAppText(
    FROM_NUMBER,
    TO_NUMBER,
    'this is a WA text from vonage'
);

$client->messages()->send($whatsAppText);

$imageObject = Vonage\Messages\MessageObjects\ImageObject(
    'https://picsum.photos/200/300',
    'image caption'
);

$viberImage = new Vonage\Messages\Channel\Viber\ViberImage(
    FROM_NUMBER,
    TO_NUMBER,
    $imageObject
);

$client->messages()->send($viberImage);

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

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

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";
}

$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;
}

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

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

$smsRequest = new \Vonage\Verify2\Request\SMSRequest('TO_NUMBER');
$client->verify2()->startVerification($smsRequest);

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

$smsRequest = new \Vonage\Verify2\Request\SMSRequest('TO_NUMBER', 'my-verification');
$voiceWorkflow = new \Vonage\Verify2\VerifyObjects\VerificationWorkflow(\Vonage\Verify2\VerifyObjects\VerificationWorkflow::WORKFLOW_VOICE, 'TO_NUMBER');
$smsRequest->addWorkflow($voiceWorkflow);
$client->verify2()->startVerification($smsRequest);

$code = '1234';
try {
    $client->verify2()->check($code);
} catch (\Exception $e) {
    var_dump($e->getMessage())
}

// From a request object
$verificationEvent = \Vonage\Verify2\Webhook\Factory::createFromRequest($request);
var_dump($verificationEvent->getStatus());
// From an array
$payload = $request->getBody()->getContents()
$verificationEvent = \Vonage\Verify2\Webhook\Factory::createFromArray($payload);
var_dump($verificationEvent->getStatus());

$requestId = 'c11236f4-00bf-4b89-84ba-88b25df97315';
$client->verify2()->cancel($requestId);

$basic  = new \Vonage\Client\Credentials\Basic(VONAGE_API_KEY, VONAGE_API_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));

$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/webhooks/answer')
    )
    ->setEventWebhook(
        new \Vonage\Voice\Webhook('https://example.com/webhooks/event')
    )
;

$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();

// 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://example.com/webhooks/event'
]);
$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\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://example.com/sounds/my-audio.mp3'));
$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\Talk::factory('Please record your name.',[
  'bargeIn' => true,
]));

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

$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\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://example.com/webhooks/notify')));
$outboundCall->setNCCO($ncco);

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

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

echo $call->getDirection();

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

$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/webhooks/answer',
                 'http_method' => 'GET',
             ],
             'event_url' => [
                 'address' => 'https://example.com/webhooks/event',
                 'http_method' => 'POST',
             ],
         ]
     ],
     'messages' => [
         'webhooks' => [
             'inbound_url' => [
                 'address' => 'https://example.com/webhooks/inbound',
                 'http_method' => 'POST'

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

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

$a = new Vonage\Application\Application();

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

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

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

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

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

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

$filter = new \Vonage\Numbers\Filter\OwnedNumbers();
$filter
    ->setPattern(234)
    ->setSearchPattern(\Vonage\Numbers\Filter\OwnedNumbers::SEARCH_PATTERN_CONTAINS)
;
$response = $client->numbers()->searchOwned($filter);

$filter = new \Vonage\Numbers\Filter\OwnedNumbers();
$filter->setHasApplication(true);
$response = $client->numbers()->searchOwned($filter);

$filter = new \Vonage\Numbers\Filter\OwnedNumbers();
$filter->setApplicationId("66c04cea-68b2-45e4-9061-3fd847d627b8");
$response = $client->numbers()->searchOwned($filter);

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

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

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

$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;

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

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

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

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

$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;
}

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

$response = $client->account()->getConfig();
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());


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
}

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
}

$client = new \Vonage\Client(new \Vonage\Client\Credentials\Basic(API_KEY, API_SECRET));
$apiKey = '34kokdf';
$subaccounts = $client->subaccount()->getSubaccounts($apiKey);
var_dump($subaccounts);

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

$apiKey = 'acc6111f';

$payload = [
    'name' => 'sub name',
    'secret' => 's5r3fds',
    'use_primary_account_balance' => false
];

$account = new Account();
$account->fromArray($payload);

$response = $client->subaccount()->createSubaccount($apiKey, $account);
var_dump($response);

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

$apiKey = 'acc6111f';
$subaccountKey = 'bbe6222f';

$response = $client->subaccount()->getSubaccount($apiKey, $subaccountKey);
var_dump($response);

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

$apiKey = 'acc6111f';
$subaccountKey = 'bbe6222f';

$payload = [
    'suspended' => true,
    'use_primary_account_balance' => false,
    'name' => 'Subaccount department B'
];

$account = new Account();
$account->fromArray($payload);

$response = $client->subaccount()->updateSubaccount($apiKey, $subaccountKey, $account)
var_dump($response);

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

$apiKey = 'acc6111f';
$filter = new Vonage\Subaccount\Filter\Subaccount(['subaccount' => '35wsf5'])
$transfers = $client->subaccount()->getCreditTransfers($apiKey);
var_dump($transfers);

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

$apiKey = 'acc6111f';

$transferRequest = (new TransferCreditRequest($apiKey))
    ->setFrom('acc6111f')
    ->setTo('s5r3fds')
    ->setAmount('123.45')
    ->setReference('this is a credit transfer');

$response = $this->subaccountClient->makeCreditTransfer($transferRequest);

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

$filter = new \Vonage\Subaccount\Filter\Subaccount(['end_date' => '2022-10-02']);
$transfers = $client->subaccount()->getBalanceTransfers($apiKey, $filter);

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

$apiKey = 'acc6111f';

$transferRequest = (new TransferBalanceRequest($apiKey))
    ->setFrom('acc6111f')
    ->setTo('s5r3fds')
    ->setAmount('123.45')
    ->setReference('this is a credit transfer');

$response = $client->subaccount()->makeBalanceTransfer($transferRequest);
var_dump($response);

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

$numberTransferRequest = (new NumberTransferRequest($apiKey))
    ->setFrom('acc6111f')
    ->setTo('s5r3fds')
    ->setNumber('4477705478484')
    ->setCountry('GB');

$response = $client->subaccount()->makeNumberTransfer($numberTransferRequest);
var_dump($response);

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

$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);

$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);

{
  "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"
}

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