Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Client Core Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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')
        );
    });
    
  2. 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'),
    ],
    
  3. 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!'
        )
    );
    

Implementation Patterns

Common Workflows

  1. Dependency Injection Inject VonageClient into controllers/services:

    public function __construct(private VonageClient $vonage) {}
    
  2. 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);
    }
    
  3. Async Processing Use Laravel Queues for non-critical SMS/voice calls:

    dispatch(new SendVonageSMSJob($message));
    
  4. 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')
    );
    

Integration Tips

  • 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).


Gotchas and Tips

Pitfalls

  1. Rate Limits Vonage enforces rate limits. Cache responses or implement exponential backoff:

    if ($this->vonage->isRateLimited()) {
        sleep(1); // Adjust delay as needed
    }
    
  2. 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');
    
  3. Async Delays SMS/voice messages may take seconds to process. Avoid assuming immediate delivery.

  4. Deprecated Methods Check the changelog for breaking changes (e.g., Vonage_ClientVonageClient).

Debugging

  • 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']]]);
    

Extension Points

  1. Custom Headers Add headers to all requests:

    $client = new VonageClient($key, $secret, $apiUrl, [
        'headers' => ['X-Custom-Header' => 'value'],
    ]);
    
  2. 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;
                }
            });
        }
    }
    
  3. 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);
        }
    }
    

Config Quirks

  • 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,
        ],
    ]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport