Weave 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

Allmysms Notifier Laravel Package

symfony/allmysms-notifier

Symfony Notifier bridge for AllMySms. Configure via ALLMYSMS_DSN with login, API key, and optional sender. Send SmsMessage through AllMySms and customize delivery using AllMySmsOptions (campaign, scheduling, simulation, identifiers, verbosity).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:

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

    ALLMYSMS_DSN=allmysms://LOGIN:APIKEY@default?from=SENDER_NUMBER
    

    Replace LOGIN, APIKEY, and SENDER_NUMBER with your AllMySms credentials.

  3. Register the transport in Laravel’s config/services.php:

    'notifier' => [
        'transports' => [
            'allmysms' => [
                'dsn' => env('ALLMYSMS_DSN'),
            ],
        ],
    ],
    
  4. First SMS send (using Laravel’s Notifiable):

    use Illuminate\Notifications\Notifiable;
    use App\Notifications\SmsNotification;
    
    class User extends Model
    {
        use Notifiable;
    }
    
    // In a controller or job:
    $user->notify(new SmsNotification('Your verification code is: 12345'));
    
  5. Create a notification class (extend Illuminate\Notifications\Notification):

    use Illuminate\Notifications\Notification;
    use Symfony\Component\Notifier\Message\SmsMessage;
    use Symfony\Component\Notifier\Bridge\AllMySms\AllMySmsOptions;
    
    class SmsNotification extends Notification
    {
        protected $message;
    
        public function __construct(string $message)
        {
            $this->message = $message;
        }
    
        public function via($notifiable)
        {
            return ['sms'];
        }
    
        public function toSms($notifiable)
        {
            $sms = new SmsMessage($notifiable->phone, $this->message);
    
            // Optional: Add AllMySms-specific options
            $options = (new AllMySmsOptions())
                ->campaignName('Verification')
                ->uniqueIdentifier($notifiable->id);
    
            $sms->options($options);
    
            return $sms;
        }
    }
    

Implementation Patterns

Core Workflow: Sending SMS

  1. Laravel Job Integration (Recommended for async):

    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Bus\Dispatchable;
    use Illuminate\Notifications\Notification;
    
    class SendSmsJob implements ShouldQueue
    {
        use Dispatchable, Queueable;
    
        public function handle()
        {
            $user = User::find(1);
            $user->notify(new SmsNotification('Hello from queue!'));
        }
    }
    
  2. Direct Sending (Sync, for low-volume use):

    use Symfony\Component\Notifier\Notifier;
    use Symfony\Component\Notifier\Message\SmsMessage;
    
    $notifier = new Notifier([new AllMySmsTransport(env('ALLMYSMS_DSN'))]);
    $message = new SmsMessage('+1234567890', 'Hello!');
    $notifier->send($message);
    

Advanced Patterns

  1. Dynamic Sender IDs:

    // Override sender per message
    $sms->options((new AllMySmsOptions())->from('CUSTOM_SENDER'));
    
  2. Scheduled SMS:

    $sms->options((new AllMySmsOptions())->date('2023-12-31 12:00:00'));
    
  3. Simulated SMS (Testing):

    $sms->options((new AllMySmsOptions())->simulate(1));
    
  4. Campaign Tracking:

    $sms->options((new AllMySmsOptions())->campaignName('Marketing_2023'));
    
  5. Retry Logic (Laravel Queues):

    // In SendSmsJob:
    public function retryAfter()
    {
        return now()->addMinutes(5); // Retry after 5 minutes
    }
    

Integration with Laravel Ecosystem

  1. Events: Listen to Illuminate\Notifications\Events\NotificationSent or NotificationFailed:

    Notification::sent(function ($notification, $channel) {
        if ($channel === 'sms') {
            Log::info('SMS sent to ' . $notification->toSms()->getPhone());
        }
    });
    
  2. Rate Limiting: Use Laravel’s throttle middleware for jobs:

    SendSmsJob::dispatch()->throttle(60); // 60 messages/minute
    
  3. Fallbacks: Combine with email notifications for critical alerts:

    public function via($notifiable)
    {
        return ['sms', 'mail'];
    }
    

Gotchas and Tips

Pitfalls

  1. DSN Format Sensitivity:

    • Ensure the DSN follows allmysms://LOGIN:APIKEY@default?from=SENDER exactly.
    • Fix: Validate the DSN in a config file or use a helper:
      if (!preg_match('/^allmysms:\/\/[^:]+:[^@]+@default\?from=[^&]+$/', env('ALLMYSMS_DSN'))) {
          throw new \RuntimeException('Invalid ALLMYSMS_DSN format');
      }
      
  2. Character Limits:

    • AllMySMS enforces a 70-character limit per segment (concatenated SMS may be needed for longer messages).
    • Fix: Use Laravel’s Str::limit or a package like spatie/array-to-xml for segmentation:
      $message = Str::limit($longMessage, 60, '...');
      
  3. Async Delays:

    • Laravel queues may introduce delays. For time-sensitive SMS (e.g., OTPs), consider:
      • Sync sending (disable queue for critical paths).
      • Database-backed queues (e.g., database driver) for immediate processing.
  4. Error Handling:

    • AllMySMS may return HTTP 4xx/5xx errors. Laravel’s queue retries help, but log failures explicitly:
      Notification::failed(function ($notification, $exception) {
          Log::error('SMS failed', [
              'phone' => $notification->toSms()->getPhone(),
              'exception' => $exception->getMessage(),
          ]);
      });
      
  5. Testing:

    • Use simulate(1) in AllMySmsOptions for test environments.
    • Mock the AllMySmsTransport in unit tests:
      $transport = $this->createMock(AllMySmsTransport::class);
      $transport->method('send')->willReturn(new SentMessage());
      $notifier = new Notifier([$transport]);
      

Tips

  1. Environment-Specific Config: Use Laravel’s config('services.notifier.transports.allmysms') to override DSN per environment:

    // config/services.php
    'transports' => [
        'allmysms' => [
            'dsn' => env('ALLMYSMS_DSN'),
            'from' => env('ALLMYSMS_FROM', '36180'), // Fallback sender
        ],
    ],
    
  2. Template Reusability: Create a base SmsNotification class to avoid repetition:

    abstract class BaseSmsNotification extends Notification
    {
        protected $message;
    
        public function __construct(string $message)
        {
            $this->message = $message;
        }
    
        public function toSms($notifiable)
        {
            $sms = new SmsMessage($notifiable->phone, $this->message);
            $sms->options($this->getAllMySmsOptions());
            return $sms;
        }
    
        protected function getAllMySmsOptions(): AllMySmsOptions
        {
            return new AllMySmsOptions();
        }
    }
    
  3. Logging Delivery Status: Extend SentMessage to include AllMySMS-specific metadata:

    use Symfony\Component\Notifier\Message\SentMessage;
    
    class AllMySmsSentMessage extends SentMessage
    {
        public function __construct(
            string $messageId,
            array $additionalInfo = []
        ) {
            parent::__construct($messageId, $additionalInfo);
            $this->additionalInfo['allmysms'] = $additionalInfo['allmysms'] ?? [];
        }
    }
    
  4. Performance:

    • Batch SMS sends using Laravel’s Bus::batch:
      Bus::batch([
          new SendSmsJob($user1, 'Message 1'),
          new SendSmsJob($user2, 'Message 2'),
      ])->then(function (Batch $batch) {
          // Handle completion
      });
      
    • Avoid sending SMS in loops without chunking (e.g., use collect($users)->chunk(50)).
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.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log