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 with your token and sender, then send SmsMessage instances. Supports advanced per-message settings through MessageBirdOptions (scheduling, encoding, callbacks, URL shortening, more).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:

    composer require symfony/message-bird-notifier
    
  2. Configure the DSN in your .env:

    MESSAGEBIRD_DSN=messagebird://YOUR_MESSAGEBIRD_TOKEN@default?from=YOUR_SENDER_ID
    
    • Replace YOUR_MESSAGEBIRD_TOKEN with your MessageBird API token.
    • Replace YOUR_SENDER_ID with your sender ID (e.g., phone number or alphanumeric sender ID).
  3. Register the transport in your Laravel/Symfony app:

    // config/services.php (Laravel)
    'notifier.transports' => [
        'messagebird' => [
            'dsn' => env('MESSAGEBIRD_DSN'),
        ],
    ],
    

    Or in Symfony:

    # config/packages/notifier.yaml
    notifier:
        transports:
            messagebird:
                dsn: '%env(MESSAGEBIRD_DSN)%'
    
  4. Send your first SMS:

    use Symfony\Component\Notifier\NotifierInterface;
    use Symfony\Component\Notifier\Message\SmsMessage;
    
    $notifier = app(NotifierInterface::class);
    $notifier->send(new SmsMessage('+1234567890', 'Hello from Laravel!'));
    

First Use Case: Password Reset SMS

use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\Bridge\MessageBird\MessageBirdOptions;

$sms = new SmsMessage('+1234567890', 'Your password reset code: 123456');
$sms->options(
    (new MessageBirdOptions())
        ->reference('password_reset_' . $user->id)
        ->validity(3600) // 1 hour validity
);

$notifier->send($sms);

Implementation Patterns

1. Integration with Laravel Queues

Leverage Laravel’s queue system for async SMS delivery:

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Symfony\Component\Notifier\Message\SmsMessage;

class SendSmsJob implements ShouldQueue
{
    use Dispatchable, Queueable;

    public function __construct(
        public string $phoneNumber,
        public string $message,
        public ?array $options = null
    ) {}

    public function handle(NotifierInterface $notifier): void
    {
        $sms = new SmsMessage($this->phoneNumber, $this->message);
        if ($this->options) {
            $sms->options($this->options);
        }
        $notifier->send($sms);
    }
}

2. Dynamic Sender IDs

Switch sender IDs based on region or use case:

$senderId = $user->region === 'eu' ? 'EU_SENDER_ID' : 'US_SENDER_ID';
$dsn = "messagebird://{$token}@default?from={$senderId}";
$notifier->send(new SmsMessage($phone, 'Hello'), ['dsn' => $dsn]);

3. Event-Driven Notifications

Use Laravel events to trigger SMS:

// In an event listener
public function handle(UserRegistered $event)
{
    $notifier->send(
        new SmsMessage(
            $event->user->phone,
            "Welcome! Your account is ready."
        )
    );
}

4. MessageBirdOptions for Advanced Use Cases

Scheduled SMS:

$sms->options(
    (new MessageBirdOptions())
        ->scheduledDatetime('2024-12-25T10:00:00') // Christmas reminder
);

WhatsApp Messages:

$sms->options(
    (new MessageBirdOptions())
        ->type('whatsapp')
);

URL Shortening:

$sms->options(
    (new MessageBirdOptions())
        ->shortenUrls(true)
);

5. Testing with Mocks

Use Mockery or VCR to avoid hitting MessageBird’s API:

// Example with Mockery
$mockTransport = Mockery::mock(MessageBirdTransport::class);
$mockTransport->shouldReceive('send')
    ->once()
    ->andReturn(new SentMessage());

$notifier = new Notifier([$mockTransport]);
$notifier->send(new SmsMessage('+1234567890', 'Test'));

6. Bulk SMS with Laravel Collections

$users = User::whereNotNull('phone')->get();
$users->each(function ($user) use ($notifier) {
    $notifier->send(
        new SmsMessage($user->phone, "Hello, {$user->name}!")
    );
});

Gotchas and Tips

Pitfalls

  1. DSN Format Sensitivity:

    • Incorrect DSN format (e.g., missing from or malformed token) will throw InvalidArgumentException.
    • Fix: Validate with MessageBirdTransport::getDsnParts().
  2. Phone Number Formatting:

    • MessageBird expects E.164 format (e.g., +14155552671).
    • Fix: Use Laravel’s Str::of($phone)->start('+') or a library like libphonenumber.
  3. Rate Limits:

    • MessageBird enforces rate limits (e.g., 1 SMS/sec for free tier).
    • Fix: Implement exponential backoff in your queue worker or use Laravel’s retryAfter:
      public function handle(): void
      {
          $this->retryAfter(5); // Retry after 5 seconds
      }
      
  4. Async Delivery Guarantees:

    • Queued SMS may fail silently if the queue worker crashes.
    • Fix: Use Laravel’s failed event to log failures:
      SendSmsJob::failed(function (FailedJob $event) {
          Log::error('SMS failed', ['job' => $event->job, 'exception' => $event->exception]);
      });
      
  5. Message Length Limits:

    • SMS: 160 chars (70 chars for Unicode). Longer messages auto-concat.
    • Fix: Use MessageBirdOptions::type('unicode') for non-ASCII text.

Debugging Tips

  1. Enable Verbose Logging:

    $notifier->send($sms, ['debug' => true]);
    

    Or configure Monolog in Symfony:

    monolog:
        handlers:
            main:
                level: debug
                channels: ['!event']
    
  2. Check MessageBird Webhooks:

    • Configure webhooks in MessageBird dashboard to log delivery status.
    • Laravel Example:
      Route::post('/messagebird/webhook', [MessageBirdWebhookHandler::class]);
      
  3. Validate DSN:

    $dsn = 'messagebird://token@default?from=sender';
    $parts = MessageBirdTransport::getDsnParts($dsn);
    if (empty($parts['token'])) {
        throw new \RuntimeException('Invalid DSN');
    }
    

Extension Points

  1. Custom Transport: Extend MessageBirdTransport to add logic (e.g., logging, analytics):

    class CustomMessageBirdTransport extends MessageBirdTransport
    {
        protected function doSend(SmsMessage $message): void
        {
            // Add custom logic (e.g., track in database)
            parent::doSend($message);
        }
    }
    
  2. Event Listeners: Listen to NotificationSent events:

    public function handle(NotificationSent $event)
    {
        if ($event->message instanceof SmsMessage) {
            // Log or analyze SMS
        }
    }
    
  3. Dynamic Options: Create a service to generate MessageBirdOptions dynamically:

    class SmsOptionsGenerator
    {
        public function generateForReset(string $userId): MessageBirdOptions
        {
            return (new MessageBirdOptions())
                ->reference("reset_{$userId}")
                ->validity(3600);
        }
    }
    

Performance Optimizations

  1. Batch Processing: Use Laravel’s chunk() for large datasets:

    User::whereNotNull('phone')->chunk(100, function ($users) {
        $users->each(fn ($user) => $notifier->send(...));
    });
    
  2. Caching Sender IDs: Cache sender IDs by region to avoid repeated DSN reconstruction:

    Cache::remember("sender_id_{$region}", now()->addHours(1), fn () => $senderId);
    
  3. Queue Priorities: Use Laravel’s queue priorities for urgent SMS:

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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony