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

Nexmo Notification Channel Laravel Package

laravel/nexmo-notification-channel

Laravel Vonage (Nexmo) Notification Channel adds SMS support to Laravel notifications via Vonage. Configure credentials, define a toVonage method on notifications, and send messages to users through the built-in notification system.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/vonage-notification-channel
    

    Publish the config file:

    php artisan vendor:publish --provider="Vonage\LaravelNotificationChannel\VonageServiceProvider"
    
  2. Configuration: Add Vonage credentials to .env:

    VONAGE_KEY=your_api_key
    VONAGE_SECRET=your_api_secret
    VONAGE_SMS_FROM=YourApp
    
  3. First Use Case: Send an SMS notification via a Notification class:

    use Vonage\LaravelNotificationChannel\VonageChannel;
    use Illuminate\Notifications\Notification;
    
    class OrderPlaced extends Notification
    {
        public function via($notifiable)
        {
            return [VonageChannel::class];
        }
    
        public function toVonage($notifiable)
        {
            return 'Your order #12345 has been placed!';
        }
    }
    

    Trigger it in a controller:

    $user->notify(new OrderPlaced());
    

Implementation Patterns

Core Workflows

  1. Multi-Channel Notifications: Combine Vonage SMS with other channels (e.g., Mail, Slack) in a single notification:

    public function via($notifiable)
    {
        return [VonageChannel::class, MailChannel::class];
    }
    
  2. Dynamic Recipients: Use toVonage() to dynamically construct messages based on user data:

    public function toVonage($notifiable)
    {
        return "Hello {$notifiable->name}, your verification code is: {$this->code}";
    }
    
  3. Queue Integration: Leverage Laravel’s queue system for async SMS delivery:

    $user->notify(new OrderPlaced())->onQueue('sms');
    
  4. Customizing Sender: Override the default sender in config/services.php:

    'vonage' => [
        'sms' => [
            'from' => 'CustomSenderName',
        ],
    ],
    

Advanced Patterns

  1. Attachments (Media): Send SMS with a link to a media file (e.g., invoice PDF):

    public function toVonage($notifiable)
    {
        return "Your invoice is ready: " . route('invoices.show', $this->invoiceId);
    }
    
  2. Two-Way Messaging: Use Vonage’s Two-Way Messaging API for interactive SMS (requires custom logic outside this package).

  3. Rate Limiting: Implement rate limiting in AppServiceProvider:

    use Illuminate\Support\Facades\RateLimiter;
    
    RateLimiter::for('sms', function ($request) {
        return Limit::perMinute(5)->by($request->user()?->id);
    });
    
  4. Fallback Channels: Add a fallback channel if Vonage fails:

    public function via($notifiable)
    {
        return [VonageChannel::class, MailChannel::class];
    }
    

Gotchas and Tips

Common Pitfalls

  1. API Credentials:

    • Gotcha: Hardcoding credentials in .env without .gitignore.
    • Fix: Use Laravel’s environment variables and validate them in AppServiceProvider:
      if (empty(config('services.vonage.key'))) {
          throw new RuntimeException('Vonage API key not configured.');
      }
      
  2. Character Limits:

    • Gotcha: Vonage SMS has a 1600-character limit (split into multiple messages if exceeded).
    • Tip: Use Str::limit() or a package like spatie/array-to-xml for long messages.
  3. Testing:

    • Gotcha: Vonage’s sandbox environment requires a valid Vonage number for testing.
    • Tip: Use Laravel’s MockVonage in tests:
      $this->actingAs($user)
           ->fake()
           ->vonage()
           ->assertSent(function ($notification) {
               return $notification->message === 'Test message';
           });
      
  4. Error Handling:

    • Gotcha: Vonage may return cryptic errors (e.g., 400 Bad Request for invalid numbers).
    • Tip: Extend the channel to log errors:
      use Vonage\Client\Exceptions\VonageException;
      
      public function send($notifiable, $message)
      {
          try {
              parent::send($notifiable, $message);
          } catch (VonageException $e) {
              Log::error("Vonage SMS failed: {$e->getMessage()}");
              throw $e;
          }
      }
      

Configuration Quirks

  1. Regional Numbers:

    • Tip: Configure regional sender numbers in config/services.php:
      'vonage' => [
          'sms' => [
              'from' => '1234567890', // US number
              'regional' => [
                  'UK' => '441234567890',
              ],
          ],
      ],
      
    • Dynamically select based on user locale:
      $sender = config("services.vonage.sms.regional.{$notifiable->locale}") ?? config('services.vonage.sms.from');
      
  2. Unicode Support:

    • Tip: Vonage supports Unicode, but some carriers may strip special characters. Test with emojis or non-Latin scripts.
  3. Webhook Validation:

    • Tip: If using Vonage’s inbound webhooks, validate requests in a middleware:
      public function handle($request, Closure $next)
      {
          $signature = $request->header('X-Vonage-Signature');
          $expected = hash_hmac('sha1', $request->getContent(), config('services.vonage.secret'));
          if (!hash_equals($signature, $expected)) {
              abort(403);
          }
          return $next($request);
      }
      

Extension Points

  1. Custom Channel Logic: Extend the VonageChannel class to add features like:

    • Message Templates: Store templates in the database and fetch dynamically.
    • Webhook Handling: Process inbound SMS via a custom route:
      Route::post('/vonage-webhook', [VonageWebhookController::class, 'handle']);
      
  2. Database Logging: Log sent SMS to a notifications table:

    public function send($notifiable, $message)
    {
        $notifiable->routeNotificationFor('vonage', $notifiable->phone);
        $sent = parent::send($notifiable, $message);
        $notifiable->notifications()->create([
            'type' => 'sms',
            'data' => ['message' => $message],
            'read_at' => null,
        ]);
        return $sent;
    }
    
  3. Batch Processing: Use Laravel’s Bus to send bulk SMS efficiently:

    $users->each->notify(new OrderPlaced())->onQueue('sms-bulk');
    
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