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

Message Bird Notifier Laravel Package

symfony/message-bird-notifier

Symfony Notifier bridge for MessageBird SMS. Configure via MESSAGEBIRD_DSN (token, from sender) and send SmsMessage notifications. Supports MessageBirdOptions to set SMS API options like scheduling, validity, report URL, and URL shortening.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel

  1. Install Dependencies:

    composer require symfony/notifier message-bird/notifier
    

    Note: Laravel’s native symfony/notifier may conflict; use symfony/notifier directly or create a custom bridge.

  2. Configure .env:

    MESSAGEBIRD_DSN=messagebird://YOUR_TOKEN@default?from=YourSender
    

    Replace YOUR_TOKEN with your MessageBird API key and YourSender with a valid sender ID (e.g., SMS-12345).

  3. Register Transport in Laravel: Create a service provider (e.g., app/Providers/MessageBirdServiceProvider.php):

    use Symfony\Component\Notifier\Notifier;
    use Symfony\Component\Notifier\Transport\MessageBirdTransport;
    
    public function register()
    {
        $notifier = new Notifier([
            new MessageBirdTransport(env('MESSAGEBIRD_DSN')),
        ]);
        $this->app->singleton('notifier', fn() => $notifier);
    }
    
  4. First Use Case: Send an SMS

    use Symfony\Component\Notifier\Message\SmsMessage;
    use Symfony\Component\Notifier\NotifierInterface;
    
    public function sendWelcomeSms()
    {
        $notifier = app(NotifierInterface::class);
        $message = new SmsMessage('+1234567890', 'Welcome to our app!');
        $notifier->send($message);
    }
    
  5. Laravel Integration (Optional): Extend Laravel’s Notification facade by creating a custom channel:

    // app/Channels/MessageBirdChannel.php
    use Illuminate\Notifications\Notification;
    use Symfony\Component\Notifier\NotifierInterface;
    
    class MessageBirdChannel
    {
        public function __construct(private NotifierInterface $notifier) {}
    
        public function send($notifiable, Notification $notification)
        {
            $message = $notification->toSms($notifiable);
            $this->notifier->send($message);
        }
    }
    

    Register the channel in config/notifications.php:

    'channels' => [
        'messagebird' => [
            'driver' => 'messagebird',
        ],
    ],
    

Implementation Patterns

Core Workflows

1. Synchronous Notifications

Use directly in controllers or services:

$notifier = app(NotifierInterface::class);
$notifier->send(new SmsMessage('+1234567890', 'Hello!'));

2. Asynchronous Notifications (Recommended)

Dispatch to Laravel Queues:

use Illuminate\Support\Facades\Bus;

Bus::dispatch(new SendSmsJob('+1234567890', 'Hello!'));

Job Implementation:

use Symfony\Component\Notifier\NotifierInterface;

class SendSmsJob implements ShouldQueue
{
    public function __construct(
        private string $phone,
        private string $message,
    ) {}

    public function handle(NotifierInterface $notifier)
    {
        $notifier->send(new SmsMessage($this->phone, $this->message));
    }
}

3. Event-Driven Notifications

Trigger via Laravel Events:

// In an event listener
public function handle(UserRegistered $event)
{
    $notifier = app(NotifierInterface::class);
    $notifier->send(new SmsMessage(
        $event->user->phone,
        "Your account is ready! Verify at: {$event->verificationUrl}"
    ));
}

4. Template-Based Messages

Use Symfony’s Message classes with templates:

$message = new SmsMessage(
    '+1234567890',
    'Your order #{{ orderId }} is shipping!'
);
$message->options((new MessageBirdOptions())->reference('order_123'));

Advanced Patterns

1. Custom Transport Configuration

Extend MessageBirdTransport for additional logic:

use Symfony\Component\Notifier\Transport\MessageBirdTransport as BaseTransport;

class CustomMessageBirdTransport extends BaseTransport
{
    public function __construct(string $dsn, array $options = [])
    {
        parent::__construct($dsn, $options + ['custom_option' => true]);
    }

    protected function getOptions(SmsMessage $message): array
    {
        $options = parent::getOptions($message);
        $options['custom_option'] = true;
        return $options;
    }
}

2. Retry Logic with Symfony Messenger

Configure retries in config/services.php:

'symfony.messenger.transports.messagebird' => [
    'dsn' => env('MESSAGEBIRD_DSN'),
    'options' => [
        'retry_strategy' => [
            'max_retries' => 3,
            'delay' => 1000, // 1 second
        ],
    ],
],

3. Logging and Monitoring

Decorate the transport to log failures:

use Psr\Log\LoggerInterface;

class LoggingMessageBirdTransport implements TransportInterface
{
    public function __construct(
        private TransportInterface $transport,
        private LoggerInterface $logger,
    ) {}

    public function send(MessageInterface $message): void
    {
        try {
            $this->transport->send($message);
        } catch (\Throwable $e) {
            $this->logger->error('MessageBird failed', [
                'message' => $message,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }
}

4. Multi-Channel Notifications

Combine with other Symfony transports (e.g., email):

$notifier = new Notifier([
    new MessageBirdTransport(env('MESSAGEBIRD_DSN')),
    new EmailTransport(env('MAILER_DSN')),
]);

Gotchas and Tips

Pitfalls

  1. DSN Format Sensitivity:

    • Incorrect MESSAGEBIRD_DSN format (e.g., missing from parameter) will throw cryptic errors.
    • Fix: Validate with MessageBirdTransport::getDsn() before use.
  2. Phone Number Validation:

    • MessageBird rejects malformed phone numbers (e.g., missing + or country code).
    • Fix: Use a library like libphonenumber to validate:
      use libphonenumber\PhoneNumberUtil;
      $phone = PhoneNumberUtil::getInstance()->parse($rawPhone);
      
  3. Rate Limiting:

    • MessageBird enforces rate limits. Exceeding limits may cause silent failures.
    • Fix: Implement exponential backoff in retries or use Symfony Messenger’s RetryStrategy.
  4. Async Deadlocks:

    • If using Laravel Queues + Symfony Messenger, ensure the queue worker processes messages faster than they’re dispatched to avoid backlogs.
    • Fix: Monitor queue length with php artisan queue:work --sleep=3 --tries=3.
  5. Environment-Specific DSNs:

    • Hardcoding DSNs in config can leak secrets. Use Laravel’s .env or a secrets manager.
    • Fix: Validate DSN parsing in a service provider:
      $dsn = env('MESSAGEBIRD_DSN');
      if (!MessageBirdTransport::getDsn($dsn)) {
          throw new \RuntimeException('Invalid MessageBird DSN');
      }
      

Debugging Tips

  1. Enable Symfony Notifier Debug Mode:

    $notifier = new Notifier([$transport], [
        'debug' => true,
    ]);
    

    Logs will include raw API requests/responses.

  2. Mock MessageBird in Tests: Use symfony/notifier-bundle's test utilities:

    use Symfony\Component\Notifier\Test\Transport\NullTransport;
    
    $notifier = new Notifier([new NullTransport()]);
    
  3. Check MessageBird API Status:

    • Verify your token and sender ID via MessageBird Dashboard.
    • Test with a type: 'test' option to avoid billing:
      $options = (new MessageBirdOptions())->type('test');
      
  4. Handle API Errors Gracefully: MessageBird returns HTTP errors (e.g., 400 Bad Request). Catch exceptions:

    try {
        $notifier->send($message);
    } catch (\Symfony\Component\Notifier\Exception\TransportException $e) {
        // Log or retry
    }
    

Extension Points

  1. Custom Message Options: Extend `MessageBird
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope