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

Smsapi Notifier Laravel Package

symfony/smsapi-notifier

Symfony Notifier bridge for SMSAPI (smsapi.pl / smsapi.com). Send SMS using an OAuth token via DSN config, with options for sender name, fast delivery priority, and test mode.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies:

    composer require symfony/notifier symfony/smsapi-notifier
    

    For Laravel, ensure compatibility with Symfony components (e.g., via spatie/laravel-symfony-messenger if using queues).

  2. Configure DSN: Add to .env:

    SMSAPI_DSN=smsapi://YOUR_TOKEN@default?from=YOUR_SENDER&fast=0&test=0
    

    For smsapi.com, use:

    SMSAPI_DSN=smsapi://YOUR_TOKEN@api.smsapi.com?from=YOUR_SENDER
    
  3. First Use Case: Send a test SMS via a Laravel command or controller:

    use Symfony\Component\Notifier\NotifierInterface;
    use Symfony\Component\Notifier\Message\SmsMessage;
    
    public function sendTestSms(NotifierInterface $notifier) {
        $message = new SmsMessage('Hello from Laravel!', '1234567890');
        $notifier->send($message);
    }
    

    Bind NotifierInterface in Laravel’s service container (e.g., via AppServiceProvider).


Implementation Patterns

Core Workflows

  1. Symfony Notifier Integration:

    • Transport Configuration: Define transports in config/services.php or a Symfony-compatible config file:
      $notifier = new Notifier([
          new SmsapiTransport(env('SMSAPI_DSN')),
      ]);
      
    • Message Dispatch: Use Laravel’s event system or Symfony Messenger to trigger SMS:
      event(new SmsSentEvent($message));
      
      Or directly:
      $notifier->send(new SmsMessage('OTP: 1234', $user->phone));
      
  2. Laravel-Specific Patterns:

    • Service Binding: Bind the notifier in AppServiceProvider:
      $this->app->singleton(NotifierInterface::class, function ($app) {
          return new Notifier([new SmsapiTransport(env('SMSAPI_DSN'))]);
      });
      
    • Queue Integration: Use spatie/laravel-symfony-messenger to async SMS:
      $message = new SmsMessage('Your order is confirmed!', $user->phone);
      $this->bus->dispatch($message);
      
  3. Dynamic Configuration:

    • Override DSN per environment or feature flag:
      $dsn = config('services.smsapi.test_mode') ?
          'smsapi://TOKEN@default?test=1' :
          env('SMSAPI_DSN');
      

Advanced Patterns

  1. Template Management: Use SMSAPI’s templates via custom SmsMessage extensions:

    class TemplatedSmsMessage extends SmsMessage {
        public function __construct(string $templateName, array $params, string $to) {
            parent::__construct($this->renderTemplate($templateName, $params), $to);
        }
    }
    
  2. Event Listeners: Track SMS delivery status:

    public function handle(SentMessage $event) {
        if ($event->getMessage() instanceof SmsMessage) {
            Log::info('SMS sent to ' . $event->getMessage()->getRecipients()[0]);
        }
    }
    
  3. Fallback Mechanisms: Combine with other transports (e.g., email) for resilience:

    $notifier = new Notifier([
        new SmsapiTransport(env('SMSAPI_DSN')),
        new EmailTransport(env('MAILER_DSN')),
    ]);
    

Gotchas and Tips

Pitfalls

  1. DSN Configuration:

    • Issue: Forgetting from= in DSN causes "eco" sender (may be blocked by carriers). Fix: Always specify from=YOUR_SENDER.
    • Issue: test=1 mode doesn’t send real SMS but may still count against quotas. Fix: Disable in production (test=0).
  2. Rate Limiting:

    • SMSAPI throttles requests. Solution:
      • Use Laravel queues to batch sends.
      • Implement exponential backoff in custom clients:
        try {
            $response = $client->post(...);
        } catch (RateLimitException $e) {
            sleep(2 ** $retryCount);
        }
        
  3. Message Length:

    • SMSAPI truncates messages >160 chars. Tip:
      • Use Unicode characters sparingly (count as 2 chars each).
      • Split long messages into multiple parts (SMSAPI supports concatenated SMS).
  4. Recipient Validation:

    • Invalid phone numbers (e.g., +123) may fail silently. Tip: Validate with a regex before sending:
      preg_match('/^\+[0-9]{10,15}$/', $phone);
      

Debugging

  1. Enable Logging: Configure Symfony’s logger in config/logging.php to capture SMSAPI responses:

    'channels' => [
        'smsapi' => [
            'driver' => 'single',
            'path' => storage_path('logs/smsapi.log'),
            'level' => 'debug',
        ],
    ],
    
  2. Test Mode: Use test=1 in DSN to validate payloads without sending:

    SMSAPI_DSN=smsapi://TOKEN@default?test=1
    
  3. API Errors: SMSAPI returns HTTP codes (e.g., 400 for invalid tokens). Tip: Extend SmsapiTransport to map errors:

    public function send(SmsMessage $message): void {
        try {
            parent::send($message);
        } catch (ClientException $e) {
            throw new \RuntimeException('SMSAPI Error: ' . $e->getResponse()->getBody());
        }
    }
    

Extension Points

  1. Custom Transports: Extend SmsapiTransport for additional SMSAPI features (e.g., webhooks):

    class CustomSmsapiTransport extends SmsapiTransport {
        public function __construct(string $dsn, array $options = []) {
            parent::__construct($dsn, $options + ['webhook_url' => 'https://your-app.com/sms-webhook']);
        }
    }
    
  2. Laravel Notifications: Create a custom SmsChannel for Laravel’s notification system:

    use Illuminate\Notifications\Notification;
    
    class SmsNotification extends Notification {
        public function via($notifiable) {
            return ['sms'];
        }
    
        public function toSms($notifiable) {
            return (string) $this->message;
        }
    }
    
  3. Monitoring: Integrate with Laravel Telescope or Prometheus:

    // Track SMS metrics
    Telescope::log('sms.sent', ['to' => $phone, 'status' => 'success']);
    

Configuration Quirks

  • Boolean Options: Use Dsn::getBooleanOption() for flags like fast:
    $fast = $dsn->getBooleanOption('fast'); // Returns bool, not string
    
  • Endpoint Overrides: Force a specific endpoint (e.g., for staging):
    SMSAPI_DSN=smsapi://TOKEN@staging.smsapi.pl?from=TEST
    
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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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