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

Kavenegar Php Laravel Package

erfanhemmati/kavenegar-php

PHP client for the Kavenegar RESTful SMS API. Install via Composer, set your API key, then send SMS to one or multiple recipients using KavenegarApi::Send. Includes basic exception handling and response details (messageid, status, cost).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require kavenegar/php
    

    Ensure your composer.json includes "kavenegar/php": "^x.x" (replace with the latest version).

  2. Retrieve API Key: Sign up at Kavenegar Panel and grab your API key from Settings.

  3. First Use Case: Send an SMS in a Laravel controller or service:

    use Kavenegar\KavenegarApi;
    
    $api = new KavenegarApi(env('KAVENEGAR_API_KEY'));
    $sender = env('KAVENEGAR_SENDER'); // e.g., "10004346"
    $receptors = ['09123456789', '09367891011'];
    $message = "Your verification code is: 123456";
    
    try {
        $result = $api->Send($sender, $receptors, $message);
        // Handle response (see Implementation Patterns)
    } catch (\Kavenegar\Exceptions\ApiException $e) {
        Log::error('Kavenegar API Error: ' . $e->errorMessage());
    }
    
  4. Store Config in .env:

    KAVENEGAR_API_KEY=your_api_key_here
    KAVENEGAR_SENDER=10004346
    

Implementation Patterns

Core Workflows

  1. Sending SMS:

    • Single Recipient:
      $result = $api->Send($sender, ['09123456789'], $message);
      
    • Bulk SMS:
      $result = $api->Send($sender, ['09123456789', '09367891011'], $message);
      
    • Async Handling: Use Laravel's queue to defer SMS sending (e.g., for user notifications):
      Queue::push(new SendSmsJob($api, $sender, $receptors, $message));
      
  2. Response Handling:

    • Check status (200 = success) and iterate over entries:
      if ($result && $result['status'] === 200) {
          foreach ($result['entries'] as $entry) {
              Log::info("Sent to {$entry->receptor}: {$entry->statustext}");
          }
      }
      
  3. Verification Codes:

    • Generate and send codes dynamically:
      $code = Str::random(6);
      $message = "Your code is: {$code}";
      $api->Send($sender, [$user->phone], $message);
      
  4. Error Handling:

    • API Errors (e.g., invalid API key):
      catch (\Kavenegar\Exceptions\ApiException $e) {
          // Log and retry or notify admin
      }
      
    • HTTP Errors (e.g., network issues):
      catch (\Kavenegar\Exceptions\HttpException $e) {
          // Implement retry logic with exponential backoff
      }
      

Integration Tips

  1. Laravel Service Provider: Bind the API client to the container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(KavenegarApi::class, function () {
            return new KavenegarApi(env('KAVENEGAR_API_KEY'));
        });
    }
    

    Usage in controllers:

    public function __construct(private KavenegarApi $kavenegar) {}
    
  2. Queue Jobs: Create a job for async SMS sending:

    // app/Jobs/SendSmsJob.php
    public function handle()
    {
        $this->kavenegar->Send($this->sender, $this->receptors, $this->message);
    }
    
  3. Logging: Log all SMS attempts (success/failure) for auditing:

    Log::channel('sms')->info('Sent to ' . $receptor, ['status' => $entry->status]);
    
  4. Testing: Use Laravel's Mockery to stub the API in tests:

    $mock = Mockery::mock(KavenegarApi::class);
    $mock->shouldReceive('Send')->andReturn(['status' => 200, 'entries' => []]);
    $this->app->instance(KavenegarApi::class, $mock);
    
  5. Rate Limiting: Implement Laravel's throttle middleware for API calls:

    Route::middleware(['throttle:10,1'])->group(function () {
        // Routes using Kavenegar
    });
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never hardcode the API key. Use Laravel's .env and validate it:
      if (empty(env('KAVENEGAR_API_KEY'))) {
          throw new \RuntimeException('Kavenegar API key not configured.');
      }
      
  2. Phone Number Validation:

    • Kavenegar expects 09xx format for Iranian numbers. Validate before sending:
      $phone = preg_replace('/[^0-9]/', '', $phone);
      if (!preg_match('/^09[0-9]{9}$/', $phone)) {
          throw new \InvalidArgumentException('Invalid phone number.');
      }
      
  3. Cost Tracking:

    • Monitor cost in responses to track SMS expenses. Log costs for billing:
      $totalCost = collect($result['entries'])->sum('cost');
      Log::info("Total SMS cost: {$totalCost} rials");
      
  4. Status Codes:

    • Common status values:
      • 1: "در صف ارسال" (Queued)
      • 2: "ارسال شد" (Sent)
      • 3: "ناموفق" (Failed)
    • Handle failures gracefully (e.g., retry or notify user).
  5. Character Limits:

    • Kavenegar enforces a 300-character limit per SMS. Split long messages:
      $chunks = array_chunk(str_split($message, 300), 300);
      foreach ($chunks as $chunk) {
          $api->Send($sender, $receptors, implode('', $chunk));
      }
      

Debugging Tips

  1. Enable Debugging:

    • Check raw API responses by inspecting $result:
      dd($result); // Debug full response structure
      
  2. HTTP Errors:

    • For HttpException, verify:
      • Internet connectivity.
      • Kavenegar's API status (status.kavenegar.com).
      • No firewall/proxy blocking requests.
  3. API Quotas:

  4. Timeouts:

    • Increase Laravel's HTTP timeout if responses are slow:
      $client = new \GuzzleHttp\Client(['timeout' => 30]);
      // Inject custom client if the package allows (check source).
      

Extension Points

  1. Custom Response Handling:

    • Extend the package by creating a decorator:
      class EnhancedKavenegarApi extends KavenegarApi {
          public function Send(...$args) {
              $result = parent::Send(...$args);
              // Add custom logic (e.g., translate status codes)
              return $this->processResponse($result);
          }
      }
      
  2. Webhook Integration:

    • Use Kavenegar's webhook to receive delivery reports:
      Route::post('/kavenegar-webhook', function (Request $request) {
          Log::info('Webhook received:', $request->all());
      });
      
  3. Fallback Mechanism:

    • Implement a fallback to another SMS provider if Kavenegar fails:
      try {
          $api->Send($sender, $receptors, $message);
      } catch (\Exception $e) {
          $fallbackApi->Send($sender, $receptors, $message);
      }
      
  4. Local Testing:

    • Mock the API for local development:
      $mock = Mockery::mock(KavenegarApi::class);
      $mock->shouldReceive('Send')->andReturn(['status' => 200, 'entries' => []]);
      $this->app->instance(KavenegarApi::class, $mock);
      
  5. **Configuration

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