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 Fast2Sms Laravel Package

itxshakil/laravel-fast2sms

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require itxshakil/laravel-fast2sms
    php artisan vendor:publish --provider="Itxshakil\Fast2SMS\Fast2SMSServiceProvider" --tag="config"
    

    Publish the config file to config/fast2sms.php and update your Fast2SMS API credentials.

  2. First Use Case: Send an SMS via the facade:

    use Itxshakil\Fast2SMS\Facades\Fast2SMS;
    
    Fast2SMS::send([
        'message' => 'Hello from Laravel!',
        'numbers' => ['+919876543210'],
        'senderId' => 'YOURSENDERID'
    ]);
    

Key Starting Points

  • Facade: Itxshakil\Fast2SMS\Facades\Fast2SMS (for quick usage).
  • Service Container: Bind the client via app('fast2sms') for dependency injection.
  • Config: Check config/fast2sms.php for API keys, default sender IDs, and rate limits.

Implementation Patterns

Core Workflows

1. Basic SMS/WhatsApp Dispatch

// Using facade
Fast2SMS::send([
    'message' => 'Your OTP is 123456',
    'numbers' => ['+919876543210'],
    'senderId' => env('FAST2SMS_SENDER_ID'),
]);

// Using service container (recommended for DI)
$client = app('fast2sms');
$client->send(['message' => 'Hello', 'numbers' => ['+911234567890']]);

2. Laravel Notifications Integration

Extend the Fast2SMSChannel for notifications:

use Itxshakil\Fast2SMS\Notifications\Fast2SMSChannel;
use Illuminate\Notifications\Notification;

class SMSNotification extends Notification
{
    public function via($notifiable)
    {
        return [Fast2SMSChannel::class];
    }

    public function toFast2SMS($notifiable)
    {
        return [
            'message' => 'Hello, ' . $notifiable->name,
            'numbers' => [$notifiable->phone],
            'senderId' => 'YOURSENDERID',
        ];
    }
}

Dispatch via:

$user->notify(new SMSNotification());

3. Queued Messages

Use Laravel queues to defer SMS delivery:

Fast2SMS::queue([
    'message' => 'Deferred message',
    'numbers' => ['+919876543210'],
]);

Configure the queue connection in config/fast2sms.php:

'queue' => [
    'connection' => 'sqs', // or 'database', 'redis', etc.
    'queue' => 'sms-queue',
],

4. Bulk SMS with Chunking

Process large recipient lists in batches:

$recipients = User::pluck('phone')->toArray();
$chunkSize = 50; // Fast2SMS API limit

array_chunk($recipients, $chunkSize)->each(function ($chunk) {
    Fast2SMS::send([
        'message' => 'Bulk message',
        'numbers' => $chunk,
    ]);
});

5. WhatsApp Messages

Fast2SMS::sendWhatsApp([
    'message' => 'Hi via WhatsApp!',
    'numbers' => ['+919876543210'],
    'templateId' => 'YOUR_TEMPLATE_ID', // Optional for templates
]);

Integration Tips

  • Logging: Enable debug logging in config/fast2sms.php:
    'debug' => env('FAST2SMS_DEBUG', false),
    
  • Retry Logic: Use Laravel’s retry helper for transient failures:
    retry(5, function () {
        Fast2SMS::send([...]);
    }, 100);
    
  • Rate Limiting: Respect Fast2SMS’s rate limits (e.g., 1 SMS/sec by default). Configure in config/fast2sms.php:
    'rate_limits' => [
        'sms' => 1, // per second
        'whatsapp' => 0.5, // per second
    ],
    

Gotchas and Tips

Common Pitfalls

  1. Sender ID Validation:

    • Fast2SMS requires pre-approved sender IDs. Test with a valid ID before production.
    • WhatsApp messages require a business account and approved template IDs.
  2. Number Formatting:

    • Ensure phone numbers are in E.164 format (e.g., +919876543210). Strip country codes if needed:
      $number = '+91' . str_replace('+91', '', $user->phone);
      
  3. Queue Stuck Jobs:

    • If jobs hang, check the queue worker logs. Fast2SMS may throttle requests:
      php artisan queue:work --sleep=3 --tries=3
      
  4. Character Limits:

    • SMS: 160 characters per message. Longer messages auto-split (but count as multiple SMS).
    • WhatsApp: 4096 characters (but templates have stricter limits).
  5. API Key Exposure:

    • Never commit config/fast2sms.php to version control. Use .env:
      FAST2SMS_API_KEY=your_key_here
      FAST2SMS_SENDER_ID=YOURSENDERID
      

Debugging Tips

  • Fake Testing: Use the fake driver for unit tests:
    Fast2SMS::fake();
    Fast2SMS::assertSent(function ($message) {
        return $message['message'] === 'Test message';
    });
    
  • Exception Handling: Catch specific exceptions for better error handling:
    try {
        Fast2SMS::send([...]);
    } catch (\Itxshakil\Fast2SMS\Exceptions\InvalidNumberException $e) {
        // Handle invalid numbers
    } catch (\Itxshakil\Fast2SMS\Exceptions\RateLimitExceededException $e) {
        // Retry or notify admin
    }
    

Extension Points

  1. Custom Responses: Override the default response handling by binding a custom Fast2SMSResponse class:

    $client = app('fast2sms')->setResponseHandler(MyCustomResponseHandler::class);
    
  2. Middleware: Add middleware to the Fast2SMS client for pre/post-processing:

    $client->withMiddleware(new LogSMSMiddleware());
    
  3. Template Management: For WhatsApp, dynamically fetch template IDs from a database or cache:

    $templateId = cache()->remember("whatsapp_template_{$type}", now()->addHours(1), function () {
        return Template::where('type', $type)->value('fast2sms_id');
    });
    
  4. Webhook Validation: If using Fast2SMS webhooks (e.g., for delivery reports), validate signatures:

    use Itxshakil\Fast2SMS\WebhookValidator;
    
    $validator = new WebhookValidator(request()->header('X-Signature'));
    if (!$validator->validate(request()->getContent())) {
        abort(403);
    }
    

Configuration Quirks

  • Default Sender ID: Set a default in config/fast2sms.php to avoid repetition:
    'defaults' => [
        'senderId' => env('FAST2SMS_SENDER_ID', 'DEFAULTSENDER'),
    ],
    
  • Timeouts: Adjust HTTP client timeouts if Fast2SMS API is slow:
    'http' => [
        'timeout' => 30, // seconds
        'connect_timeout' => 10,
    ],
    
  • Environment-Specific Keys: Use Laravel’s env() helpers or .env files for different environments:
    FAST2SMS_API_KEY=prod_key
    FAST2SMS_API_KEY_STAGING=staging_key
    
    Then reference in config:
    'api_key' => env('FAST2SMS_API_KEY_' . app()->environment(), env('FAST2SMS_API_KEY')),
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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