vonage/client-core
Core PHP client library for Vonage APIs (PHP 8.1+). Create a Vonage\Client with your API key/secret, make requests, and optionally customize base API URLs for testing. Install via Composer (vonage/client) or use core with your own HTTP client.
Installation
composer require vonage/client-core
Register the client in your Laravel service provider (e.g., AppServiceProvider):
$this->app->singleton(VonageClient::class, function ($app) {
return new VonageClient(
config('services.vonage.key'),
config('services.vonage.secret'),
config('services.vonage.api_url', 'https://api.vonage.com')
);
});
Configuration
Add to config/services.php:
'vonage' => [
'key' => env('VONAGE_KEY'),
'secret' => env('VONAGE_SECRET'),
'api_url' => env('VONAGE_API_URL', 'https://api.vonage.com'),
],
First Use Case: Sending an SMS
use Vonage\Client\Credentials\Basic;
use Vonage\Client\VonageClient;
use Vonage\SMS\Message\SMSMessage;
$client = app(VonageClient::class);
$response = $client->sms()->send(
new SMSMessage(
'from' => 'YourApp',
'to' => '1234567890',
'text' => 'Hello from Laravel!'
)
);
Dependency Injection
Inject VonageClient into controllers/services:
public function __construct(private VonageClient $vonage) {}
Error Handling Wrap API calls in try-catch:
try {
$response = $this->vonage->sms()->send($message);
} catch (\Vonage\Client\Exceptions\VonageException $e) {
Log::error("Vonage SMS failed: " . $e->getMessage());
return response()->json(['error' => 'SMS delivery failed'], 500);
}
Async Processing Use Laravel Queues for non-critical SMS/voice calls:
dispatch(new SendVonageSMSJob($message));
Configuration Overrides Dynamically set API URL/credentials per environment:
$client = new VonageClient(
env('VONAGE_KEY_OVERRIDE'),
env('VONAGE_SECRET_OVERRIDE'),
env('VONAGE_API_URL_OVERRIDE')
);
Laravel Notifications: Extend VonageChannel for SMS notifications:
use Vonage\Client\VonageClient;
use Illuminate\Notifications\Notification;
class VonageSMSNotification extends Notification {
public function via($notifiable) {
return ['vonage'];
}
public function toVonage($notifiable) {
return (new SMSMessage())
->setFrom('AppName')
->setTo($notifiable->phone)
->setText($this->message);
}
}
Webhooks: Use vonage/webhooks package to validate and process Vonage events (e.g., SMS delivery reports).
Rate Limits Vonage enforces rate limits. Cache responses or implement exponential backoff:
if ($this->vonage->isRateLimited()) {
sleep(1); // Adjust delay as needed
}
Number Formatting
Ensure phone numbers are in E.164 format (e.g., +1234567890). Use a library like libphonenumber for validation:
use giggsey\LibPhonenumber\PhoneNumberUtil;
$phoneUtil = PhoneNumberUtil::getInstance();
$number = $phoneUtil->parse($rawPhone, 'US');
Async Delays SMS/voice messages may take seconds to process. Avoid assuming immediate delivery.
Deprecated Methods
Check the changelog for breaking changes (e.g., Vonage_Client → VonageClient).
Enable Logging Configure Monolog to log Vonage requests/responses:
$client = new VonageClient($key, $secret, $apiUrl, [
'logger' => new \Monolog\Logger('vonage', [new \Monolog\Handler\StreamHandler(storage_path('logs/vonage.log'))]),
]);
Mocking for Tests
Use Vonage\Client\Mock\VonageClient in PHPUnit:
$mockClient = new VonageClient($key, $secret, 'https://mock.vonage.com');
$mockClient->setMockResponse('sms/send', ['messages' => [['status' => '0']]]);
Custom Headers Add headers to all requests:
$client = new VonageClient($key, $secret, $apiUrl, [
'headers' => ['X-Custom-Header' => 'value'],
]);
Middleware
Extend VonageClient to add request/response middleware:
class CustomVonageClient extends VonageClient {
public function __construct($key, $secret, $apiUrl, array $config = []) {
parent::__construct($key, $secret, $apiUrl, $config);
$this->addMiddleware(new class {
public function handle($request) {
$request->setHeader('X-Request-ID', Str::uuid());
return $request;
}
});
}
}
Retry Logic Implement exponential backoff for transient failures:
use Vonage\Client\Exceptions\VonageException;
$attempts = 0;
while ($attempts < 3) {
try {
$response = $this->vonage->sms()->send($message);
break;
} catch (VonageException $e) {
$attempts++;
sleep(2 ** $attempts);
}
}
API URL Overrides
Use VONAGE_API_URL for staging/production splits:
$client = new VonageClient($key, $secret, config('vonage.api_url'));
Proxy Support
Configure proxy via config:
$client = new VonageClient($key, $secret, $apiUrl, [
'proxy' => [
'host' => 'proxy.example.com',
'port' => 8080,
],
]);
How can I help you explore Laravel packages today?