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

Laravel Sms Client Laravel Package

asanak/laravel-sms-client

Laravel package for sending SMS via Asanak API. Supports simple send, P2P messages, OTP templates, and message status reports. Includes config publishing, .env credentials, optional logging, and auto-registered service provider and facade.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require asanak/laravel-sms-client
    php artisan vendor:publish --provider="Asanak\SmsClient\SmsClientServiceProvider" --tag="config"
    
    • Publishes config/sms-client.php for provider configuration.
  2. Configuration

    • Edit config/sms-client.php to define your SMS provider (e.g., twilio, nexmo, custom).
    • Example for Twilio:
      'providers' => [
          'twilio' => [
              'account_sid' => env('TWILIO_SID'),
              'auth_token' => env('TWILIO_TOKEN'),
              'from' => env('TWILIO_FROM'),
          ],
      ],
      
  3. First Use Case: Sending an SMS

    use Asanak\SmsClient\Facades\SmsClient;
    
    $response = SmsClient::send([
        'provider' => 'twilio',
        'to' => '+1234567890',
        'message' => 'Hello from Laravel!',
    ]);
    
    // Check response
    if ($response->success()) {
        // Log or handle success
    }
    

Key Files to Review

  • config/sms-client.php: Provider configurations.
  • app/Providers/SmsClientServiceProvider.php: Service binding and boot logic.
  • src/Facades/SmsClient.php: Primary facade for sending SMS.

Implementation Patterns

Core Workflows

1. Provider-Agnostic Sending

  • Use the facade to abstract provider logic:
    SmsClient::send([
        'provider' => 'nexmo', // Switch providers without code changes
        'to' => '+1234567890',
        'message' => 'Your OTP: 1234',
    ]);
    
  • Dynamic Provider Selection: Pass provider name dynamically (e.g., from config or user input).

2. Batch Sending

  • Send to multiple recipients:
    $recipients = ['+1234567890', '+9876543210'];
    foreach ($recipients as $phone) {
        SmsClient::send(['provider' => 'twilio', 'to' => $phone, 'message' => 'Batch message']);
    }
    
  • Optimization: Use provider-specific batch APIs if available (e.g., Twilio’s Messages::create with multiple to fields).

3. Template-Based Messages

  • Store templates in the database (e.g., sms_templates table) and fetch dynamically:
    $template = DB::table('sms_templates')->where('key', 'welcome')->first();
    SmsClient::send([
        'provider' => 'twilio',
        'to' => $user->phone,
        'message' => str_replace(['{name}'], [$user->name], $template->body),
    ]);
    

4. Event-Driven SMS

  • Trigger SMS on events (e.g., Registered, PasswordReset):
    // In EventServiceProvider
    protected $listen = [
        \App\Events\UserRegistered::class => [
            \Asanak\SmsClient\Listeners\SendWelcomeSms::class,
        ],
    ];
    
  • Listener Example:
    public function handle(UserRegistered $event) {
        SmsClient::send([
            'provider' => 'twilio',
            'to' => $event->user->phone,
            'message' => "Welcome, {$event->user->name}!",
        ]);
    }
    

5. Queueing SMS for Reliability

  • Dispatch SMS jobs to a queue (e.g., database, redis):
    use Asanak\SmsClient\Jobs\SendSmsJob;
    
    SendSmsJob::dispatch([
        'provider' => 'twilio',
        'to' => '+1234567890',
        'message' => 'Queued message',
    ]);
    
  • Job Class:
    namespace Asanak\SmsClient\Jobs;
    
    use Asanak\SmsClient\Facades\SmsClient;
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class SendSmsJob implements ShouldQueue {
        use Queueable;
    
        public $data;
    
        public function __construct(array $data) {
            $this->data = $data;
        }
    
        public function handle() {
            SmsClient::send($this->data);
        }
    }
    

Integration Tips

1. Environment Configuration

  • Use Laravel’s .env for sensitive provider credentials:
    TWILIO_SID=your_sid
    TWILIO_TOKEN=your_token
    TWILIO_FROM=+1234567890
    
  • Reference in config/sms-client.php:
    'providers' => [
        'twilio' => [
            'account_sid' => env('TWILIO_SID'),
            // ...
        ],
    ],
    

2. Logging and Monitoring

  • Log responses for debugging:
    $response = SmsClient::send([...]);
    \Log::info('SMS Response', ['data' => $response->getData()]);
    
  • Monitoring: Track failed sends with Laravel’s failed queue job or a custom observer.

3. Testing

  • Mock the facade in tests:
    $this->mock(SmsClient::class)->shouldReceive('send')->once()->andReturn(new \Asanak\SmsClient\Response(true, []));
    
  • Use phpunit.xml to exclude the database queue connection during tests:
    <env name="QUEUE_CONNECTION" value="sync"/>
    

4. Custom Providers

  • Extend the package by creating a custom provider:
    namespace App\Providers;
    
    use Asanak\SmsClient\Contracts\ProviderInterface;
    
    class CustomProvider implements ProviderInterface {
        public function send(array $message) {
            // Custom logic (e.g., HTTP request to your SMS gateway)
            return new \Asanak\SmsClient\Response(true, ['message_id' => 'custom123']);
        }
    }
    
  • Register in config/sms-client.php:
    'providers' => [
        'custom' => [
            'class' => \App\Providers\CustomProvider::class,
        ],
    ],
    

Gotchas and Tips

Pitfalls

1. Provider-Specific Quirks

  • Character Limits: Some providers (e.g., Twilio) enforce 1600-character limits for SMS. Longer messages may require concatenation or MMS.
    • Fix: Use parts in the message array to split text:
      SmsClient::send([
          'provider' => 'twilio',
          'to' => '+1234567890',
          'message' => ['Hello', 'This is a long message split into parts.'],
      ]);
      
  • Encoding Issues: Non-ASCII characters (e.g., emojis) may fail. Use UTF-8 encoding in your provider’s HTTP requests.

2. Rate Limiting

  • Providers like Twilio throttle requests. Handle 429 Too Many Requests responses gracefully:
    try {
        $response = SmsClient::send([...]);
    } catch (\Asanak\SmsClient\Exceptions\RateLimitExceeded $e) {
        \Log::warning('Rate limit exceeded. Retrying in 30s...');
        sleep(30);
        retry();
    }
    

3. Queue Job Failures

  • If using queues, ensure the failed table is monitored. Failed SMS jobs may indicate:
    • Invalid phone numbers (validate with Validator::make($data, ['to' => 'required|phone:international'])).
    • Provider API downtime (implement retries with exponential backoff).

4. Facade vs. Direct Service Container Access

  • Avoid instantiating the service directly (app(SmsClient::class)). Use the facade for consistency and easier mocking in tests.

5. Webhook Verification

  • If using provider webhooks (e.g., Twilio’s MessageStatus callbacks), verify the request signature:
    use Asanak\SmsClient\Http\Middleware\VerifyTwilioSignature;
    
    // In routes/web.php
    Route::post('/sms/webhook', [SmsWebhookController::class, 'handle'])
         ->middleware(VerifyTwilioSignature::class);
    

Debugging Tips

1. Enable Debug Mode

  • Set debug to true in config/sms-client.php to log raw API responses:
    'debug
    
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