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

Ersalak Laravel Sms Laravel Package

ersalak/ersalak-laravel-sms

Laravel package for sending SMS via Ersalak API. Provides facade-based methods for simple SMS, P2P messages, OTP template sends, and message status reports. Easy install via Composer, publish config, and set ERSALAK env credentials.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ersalak/ersalak-laravel-sms
    php artisan vendor:publish --tag=ersalak-config
    

    Update .env with your Ersalak credentials:

    ERSALAK_SMS_USERNAME=your_username
    ERSALAK_SMS_PASSWORD=your_password
    ERSALAK_SMS_BASE_URL=https://sms.ersalak.ir
    ERSALAK_SMS_LOG=true
    
  2. First Use Case: Send a basic SMS in a controller:

    use Ersalak\Sms\Facade\ErsalakSmsFacade;
    
    public function sendOtp()
    {
        $response = ErsalakSmsFacade::sendSms(
            source: '1000', // Your sender ID
            destination: '09121234567',
            message: 'Your OTP is 123456',
            send_to_black_list: 0
        );
        return $response;
    }
    
  3. Key Files to Review:

    • config/ersalak-sms.php (published config)
    • vendor/ersalak/ersalak-laravel-sms/src/ErsalakSmsServiceProvider.php (service provider)
    • vendor/ersalak/ersalak-laravel-sms/src/Facade/ErsalakSmsFacade.php (facade methods)

Implementation Patterns

Core Workflows

1. Sending SMS

  • Basic Usage:
    $response = ErsalakSmsFacade::sendSms([
        'source' => '1000',
        'destination' => '09121234567',
        'message' => 'Hello from Laravel!',
        'send_to_black_list' => 0,
    ]);
    
  • Bulk SMS:
    $response = ErsalakSmsFacade::sendBulkSms([
        'source' => '1000',
        'destinations' => ['09121234567', '09357654321'],
        'message' => 'Bulk message',
    ]);
    

2. Checking Status

  • Single Message Status:
    $status = ErsalakSmsFacade::getMessageStatus('message_id_from_response');
    
  • Bulk Status Report:
    $report = ErsalakSmsFacade::getReport(['message_id_1', 'message_id_2']);
    

3. Integration with Laravel Events

  • Trigger SMS on user registration:
    use Illuminate\Support\Facades\Event;
    
    Event::listen('registered', function ($user) {
        ErsalakSmsFacade::sendSms([
            'source' => '1000',
            'destination' => $user->phone,
            'message' => "Welcome, {$user->name}! Your account is active.",
        ]);
    });
    

4. Queueing SMS Jobs

  • Create a job:
    php artisan make:job SendSmsJob
    
  • Implement job logic:
    public function handle()
    {
        ErsalakSmsFacade::sendSms([
            'source' => '1000',
            'destination' => $this->phone,
            'message' => $this->message,
        ]);
    }
    
  • Dispatch the job:
    SendSmsJob::dispatch('09121234567', 'Hello from queue!');
    

5. Logging and Monitoring

  • Enable logging in .env:
    ERSALAK_SMS_LOG=true
    
  • Check logs in storage/logs/laravel.log for SMS responses and errors.

Integration Tips

1. Validation

Validate phone numbers before sending:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make(['phone' => $request->phone], [
    'phone' => 'required|string|regex:/^09[0-9]{9}$/',
]);

2. Rate Limiting

Use Laravel's rate limiting middleware:

Route::middleware(['throttle:10,1'])->group(function () {
    Route::post('/send-sms', [SmsController::class, 'send']);
});

3. Retry Mechanism

Implement a retry logic for failed SMS:

use Illuminate\Support\Facades\Bus;

Bus::dispatch(new SendSmsJob($phone, $message))->onQueue('sms');

4. Testing

Mock the facade in tests:

$this->mock(ErsalakSmsFacade::class)->shouldReceive('sendSms')->once()->andReturn(['success' => true]);

Gotchas and Tips

Pitfalls

  1. API Rate Limits:

    • Ersalak may throttle requests. Monitor your .env for rate limit errors and implement exponential backoff in your retry logic.
  2. Phone Number Formatting:

    • Ensure phone numbers are in the correct format (e.g., 09121234567 without + or spaces). Invalid formats will fail silently or return errors.
  3. Blacklist Flag:

    • send_to_black_list defaults to 0 (do not send to blacklisted numbers). Set to 1 if you want to override this.
  4. Message Length:

    • SMS messages are limited to 1100 Persian characters or 160 Latin characters. Longer messages will be truncated or split (check Ersalak's API docs for behavior).
  5. Logging Overhead:

    • Enabling ERSALAK_SMS_LOG=true can bloat logs quickly. Disable in production if not needed for debugging.

Debugging

  1. Check Raw Responses:

    • Enable logging and inspect the raw API response in logs to debug issues:
      try {
          $response = ErsalakSmsFacade::sendSms([...]);
      } catch (\Throwable $e) {
          \Log::error('Ersalak SMS Error: ' . $e->getMessage(), ['response' => $e->getTraceAsString()]);
      }
      
  2. Validate Credentials:

    • Ensure ERSALAK_SMS_USERNAME and ERSALAK_SMS_PASSWORD are correct. Test with a simple API call using Postman or cURL to verify credentials.
  3. Network Issues:

    • If SMS fails intermittently, check for network timeouts. Increase PHP's max_execution_time or implement retry logic.
  4. Facade vs. Service Container:

    • Prefer using the facade for simplicity in controllers/views, but inject the service container binding (Ersalak\Sms\ErsalakSms) in services/repositories for better testability.

Tips

  1. Store Message IDs:

    • Save returned message_ids in your database to track status later:
      $message = new Message();
      $message->phone = $request->phone;
      $message->message_id = $response['message_id'];
      $message->save();
      
  2. Customize Config:

    • Override default config values in config/ersalak-sms.php:
      'timeout' => 30, // Increase timeout for slow connections
      'retry_attempts' => 3, // Retry failed requests
      
  3. Extend Functionality:

    • Create a custom trait for reusable SMS logic:
      trait SmsNotifier
      {
          public function notifyViaSms($phone, $message)
          {
              return ErsalakSmsFacade::sendSms([
                  'source' => config('ersalak-sms.source'),
                  'destination' => $phone,
                  'message' => $message,
              ]);
          }
      }
      
  4. Webhook for Status Updates:

    • Use Ersalak's webhook feature (if supported) to receive real-time status updates. Implement a Laravel route to handle the webhook:
      Route::post('/ersalak-webhook', [ErsalakWebhookController::class, 'handle']);
      
  5. Environment-Specific Config:

    • Use Laravel's environment-specific config to switch between sandbox and production:
      'base_url' => env('ERSALAK_SMS_BASE_URL', 'https://sms.ersalak.ir'),
      
  6. Local Testing:

    • For local development, use a sandbox URL (if provided by Ersalak) to avoid hitting rate limits or incurring costs.
  7. Error Handling:

    • Catch specific exceptions for better error handling:
      try {
          $response = ErsalakSmsFacade::sendSms([...]);
      } catch (\Ersalak\Sms\Exceptions\InvalidCredentialsException $e) {
          // Handle credential errors
      } catch (\Ersalak\Sms\Exceptions\RateLimit
      
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