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

Light Sms Notifier Laravel Package

symfony/light-sms-notifier

Symfony Notifier bridge for LightSms. Configure via LIGHTSMS_DSN (lightsms://LOGIN:TOKEN@default?from=PHONE) to send SMS messages through your LightSms account using your login, API token, and sender phone number.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require symfony/light-sms-notifier
    
  2. Configure the DSN Add to your .env:

    LIGHTSMS_DSN=lightsms://LOGIN:TOKEN@default?from=PHONE
    

    Replace LOGIN, TOKEN, and PHONE with your LightSms credentials.

  3. Set Up Symfony Notifier Register the transport in your Laravel service provider (e.g., AppServiceProvider):

    use Symfony\Component\Notifier\Notifier;
    use Symfony\Component\Notifier\Transport\LightSmsTransport;
    
    public function register()
    {
        $this->app->singleton(Notifier::class, function ($app) {
            $dsn = $app['config']['services.sms.dsn'];
            $transport = new LightSmsTransport($dsn);
            return new Notifier([$transport]);
        });
    }
    
  4. Send Your First SMS

    use Symfony\Component\Notifier\Message\SmsMessage;
    use Symfony\Component\Notifier\Notifier;
    
    $notifier = app(Notifier::class);
    $notifier->send(new SmsMessage('Hello from Laravel!', 'recipient@example.com'));
    

First Use Case

OTP Verification

$otp = '123456';
$notifier->send(new SmsMessage("Your OTP is: {$otp}", $user->phone));

Implementation Patterns

Usage Patterns

  1. Environment-Based Configuration Use Laravel’s .env for DSN and fallback to config:

    // config/services.php
    'sms' => [
        'dsn' => env('LIGHTSMS_DSN', 'lightsms://default:token@default?from=12345'),
    ],
    
  2. Integration with Laravel Notifications Create a custom notification channel:

    namespace App\Notifications\Channels;
    
    use Illuminate\Notifications\Notification;
    use Symfony\Component\Notifier\Notifier;
    
    class LightSmsChannel
    {
        public function __construct(private Notifier $notifier) {}
    
        public function send($notifiable, Notification $notification)
        {
            $this->notifier->send($notification->toLightSms($notifiable));
        }
    }
    
  3. Async Delivery with Laravel Queues Dispatch notifications via Laravel’s queue system:

    $notifier = app(Notifier::class);
    $notifier->send(new SmsMessage('Hello', '1234567890'))
        ->then(function () {
            // Handle success/failure
        });
    
  4. Dynamic Sender Numbers Override the from parameter per message:

    $transport = new LightSmsTransport($dsn, 'custom-sender@example.com');
    

Workflows

  1. User Onboarding

    $notifier->send(new SmsMessage('Welcome! Use code WELCOME10 for 10% off.', $user->phone));
    
  2. Transaction Alerts

    $notifier->send(new SmsMessage(
        "Your payment of \$99.99 was processed. Order #{$order->id}",
        $user->phone
    ));
    
  3. Scheduled Notifications Use Laravel’s scheduler to send time-sensitive messages:

    $schedule->call(function () {
        $notifier->send(new SmsMessage('Your subscription renews tomorrow!', $user->phone));
    })->dailyAt('16:00');
    

Integration Tips

  • Laravel Facades: Wrap the Notifier in a facade for cleaner syntax:

    // app/Facades/Sms.php
    public static function send(string $message, string $phone)
    {
        return app(Notifier::class)->send(new SmsMessage($message, $phone));
    }
    

    Usage:

    Sms::send('Hello', '1234567890');
    
  • Logging: Enable Symfony’s Monolog for SMS delivery logs:

    $notifier = new Notifier([$transport], [
        'logger' => app(\Psr\Log\LoggerInterface::class),
    ]);
    
  • Testing: Mock the transport in PHPUnit:

    $transport = $this->createMock(LightSmsTransport::class);
    $transport->expects($this->once())->method('send');
    $notifier = new Notifier([$transport]);
    

Gotchas and Tips

Pitfalls

  1. DSN Format Sensitivity

    • Issue: Incorrect DSN format (e.g., missing from parameter) causes silent failures.
    • Fix: Validate the DSN in config:
      $dsn = 'lightsms://LOGIN:TOKEN@default?from=PHONE';
      if (!preg_match('/lightsms:\/\/.+@.+\?from=.+/', $dsn)) {
          throw new \InvalidArgumentException('Invalid LightSms DSN format.');
      }
      
  2. Phone Number Formatting

    • Issue: LightSms expects E.164 format (e.g., +1234567890). Invalid formats may fail silently.
    • Fix: Normalize phone numbers:
      use libphonenumber\PhoneNumberUtil;
      use libphonenumber\PhoneNumberFormat;
      
      $phoneUtil = PhoneNumberUtil::getInstance();
      $phone = $phoneUtil->parse($user->phone, 'US');
      $e164Phone = $phoneUtil->format($phone, PhoneNumberFormat::E164);
      
  3. Rate Limits

    • Issue: LightSms may throttle requests during high-volume periods.
    • Fix: Implement exponential backoff in Laravel:
      use Symfony\Component\Notifier\Exception\TransportException;
      
      try {
          $notifier->send($message);
      } catch (TransportException $e) {
          if (str_contains($e->getMessage(), 'rate limit')) {
              sleep(2); // Retry after delay
              $notifier->send($message);
          }
      }
      
  4. Symfony Dependency Conflicts

    • Issue: Version mismatches between symfony/light-sms-notifier and other Symfony packages (e.g., symfony/messenger).
    • Fix: Pin versions in composer.json:
      "require": {
          "symfony/light-sms-notifier": "^8.1",
          "symfony/messenger": "^6.4",
          "symfony/http-client": "^6.4"
      }
      

Debugging

  1. Enable Verbose Logging Configure Monolog to log SMS delivery attempts:

    $notifier = new Notifier([$transport], [
        'logger' => app(\Psr\Log\LoggerInterface::class),
        'logger_level' => \Psr\Log\LogLevel::DEBUG,
    ]);
    
  2. Check LightSms API Status Verify your LightSms credentials and API access at LightSms Dashboard.

  3. Test with a Sandbox Number Use LightSms’s sandbox environment for testing:

    LIGHTSMS_DSN=lightsms://LOGIN:TOKEN@sandbox?from=12345
    

Tips

  1. Retry Failed Messages Use Laravel’s queue retries for transient failures:

    $notifier->send($message)->then(function () {
        // Success
    }, function ($e) {
        if ($e instanceof TransportException) {
            // Retry logic
        }
    });
    
  2. Batch Processing For bulk SMS, use Laravel’s chunking:

    User::chunk(100, function ($users) {
        foreach ($users as $user) {
            $notifier->send(new SmsMessage('Hello', $user->phone));
        }
    });
    
  3. Custom Transport Options Extend LightSmsTransport for additional features:

    class CustomLightSmsTransport extends LightSmsTransport
    {
        public function __construct(string $dsn, ?string $from = null, array $options = [])
        {
            $options['custom_header'] = 'X-Custom-Header';
            parent::__construct($dsn, $from, $options);
        }
    }
    
  4. Monitor Delivery Status LightSms provides delivery receipts. Hook into Symfony’s MessageSentEvent:

    $notifier->send($message)->then(function ($event) {
        $event->getMessage()->getTransport()->getDeliveryStatus();
    });
    
  5. Fallback Mechanisms Combine with other channels (e.g., email) for critical messages:

    $notifier->send(new 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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views