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

mahdimajidzadeh/kavenegar

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mahdimajidzadeh/kavenegar
    

    For Laravel <5.5, add the service provider to config/app.php:

    MahdiMajidzadeh\Kavenegar\KavenegarServiceProvider::class
    
  2. Publish Config:

    php artisan vendor:publish --provider="MahdiMajidzadeh\Kavenegar\KavenegarServiceProvider"
    

    This generates .env keys and a config file at config/kavenegar.php.

  3. Configure .env:

    KAVENEGAR_API_KEY=your_api_key_here
    
  4. First Use Case: Send a basic SMS in a controller or service:

    use MahdiMajidzadeh\Kavenegar\KavenegarSMS;
    
    $sms = new KavenegarSMS();
    $result = $sms->send('09123456789', 'Hello from Laravel!');
    

Implementation Patterns

Core Workflows

  1. Sending SMS:

    • Single Recipient:
      $sms->send('09123456789', 'Your verification code is 1234.');
      
    • Multiple Recipients (Bulk):
      $sms->sendArray(['09123456789', '09198765432'], 'Hello all!');
      
  2. Verification & Tracking:

    • Check status of a sent SMS:
      $sms->status('local_message_id');
      
    • Retrieve sent messages:
      $sms->select(); // All outbox messages
      $sms->latestOutbox(10); // Last 10 messages
      
  3. Inbox Management:

    • Fetch received messages:
      $sms->receive(); // All inbox messages
      $sms->receive(10); // Last 10 messages
      
  4. Integration with Laravel:

    • Service Container: Bind the SMS client in a service provider for dependency injection:

      $this->app->singleton(KavenegarSMS::class, function ($app) {
          return new KavenegarSMS(config('kavenegar.api_key'));
      });
      

      Then inject KavenegarSMS into controllers/services.

    • Queued Jobs: Dispatch SMS sending as a job for async processing:

      use MahdiMajidzadeh\Kavenegar\Jobs\SendSMS;
      
      SendSMS::dispatch('09123456789', 'Your code is 1234.')->onQueue('sms');
      
  5. Event-Driven Notifications: Extend Laravel’s Notifiable trait to send SMS notifications:

    use MahdiMajidzadeh\Kavenegar\HasSmsNotifications;
    
    class User extends Authenticatable implements Notifiable
    {
        use HasSmsNotifications;
    }
    

    Then define a sendSmsVerification method in the model.


Advanced Patterns

  1. Template-Based SMS: Use Kavenegar’s templates for dynamic content:

    $sms->send('09123456789', 'template_name', ['code' => '1234']);
    
  2. Rate Limiting: Implement middleware to throttle SMS requests:

    use Illuminate\Cache\RateLimiting\Limit;
    
    RateLimiter::for('sms', function (Request $request) {
        return Limit::perMinute(5)->by($request->user()->id);
    });
    
  3. Logging & Retries: Log failed SMS attempts and retry using Laravel’s queue:

    try {
        $sms->send($phone, $message);
    } catch (\Exception $e) {
        Log::error("SMS failed: " . $e->getMessage());
        // Retry logic or notify admin
    }
    

Gotchas and Tips

Common Pitfalls

  1. API Key Misconfiguration:

    • Ensure KAVENEGAR_API_KEY is set in .env and matches the config file.
    • Debug Tip: Check the status property after sending:
      if ($sms->status !== 200) {
          throw new \Exception($sms->message);
      }
      
  2. Phone Number Formatting:

    • Kavenegar expects 0912... (without + or 0098).
    • Fix: Sanitize input:
      $phone = preg_replace('/[^0-9]/', '', $phone);
      
  3. Rate Limits:

    • Kavenegar enforces rate limits. Handle 429 responses gracefully:
      if ($sms->status === 429) {
          sleep(1); // Retry after delay
          $sms->send($phone, $message);
      }
      
  4. Timeouts:

    • API requests may time out. Increase PHP’s max_execution_time or use async jobs.
  5. Local Testing:

    • Mock the SMS client in tests:
      $this->app->instance(KavenegarSMS::class, Mockery::mock(KavenegarSMS::class));
      

Debugging Tips

  1. Enable Debug Mode: Set debug to true in config/kavenegar.php to log raw API responses.

  2. Check HTTP Status:

    • 200: Success.
    • 400: Invalid parameters (e.g., malformed phone).
    • 401: Invalid API key.
    • 403: Insufficient balance or blocked number.
  3. Inspect Raw Response:

    $response = $sms->send($phone, $message);
    dd($response->getRawResponse()); // Debug full API response
    

Extension Points

  1. Custom Responses: Extend the KavenegarSMS class to handle business logic:

    class CustomKavenegarSMS extends KavenegarSMS {
        public function sendVerification($phone, $code) {
            $result = $this->send($phone, "Your code is {$code}.");
            if ($result->status !== 200) {
                event(new SmsFailed($phone, $result->message));
            }
            return $result;
        }
    }
    
  2. Webhook Integration: Use Kavenegar’s webhooks to handle delivery reports:

    Route::post('/kavenegar-webhook', function (Request $request) {
        $payload = $request->json()->all();
        // Process delivery status (e.g., update DB)
    });
    
  3. Fallback Mechanisms: Implement a fallback to another SMS provider if Kavenegar fails:

    try {
        $sms->send($phone, $message);
    } catch (\Exception $e) {
        $fallbackSms->send($phone, $message); // e.g., Twilio
    }
    

Configuration Quirks

  1. Environment Overrides: Override config values in .env:

    KAVENEGAR_DEBUG=true
    KAVENEGAR_TIMEOUT=30
    
  2. Proxy Support: If behind a proxy, configure Guzzle’s client in the service provider:

    $client = new \GuzzleHttp\Client([
        'timeout' => 30,
        'proxy' => 'http://your-proxy:port',
    ]);
    
  3. SSL Verification: Disable SSL verification only for testing (not production):

    $sms = new KavenegarSMS(config('kavenegar.api_key'), false); // Disables SSL
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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