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

ariaieboy/kavenegar-laravel

Laravel integration for the Kavenegar SMS API. Install via Composer, register the service provider and facade, publish config, and set your API key. Then send messages anywhere in your app using the Kavenegar facade.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ariaieboy/kavenegar-laravel
    

    Publish the config file:

    php artisan vendor:publish --provider="Ariaieboy\KavenegarLaravel\KavenegarServiceProvider"
    
  2. Configuration Edit .env with your Kavenegar API credentials:

    KAVENEGAR_API_KEY=your_api_key
    KAVENEGAR_API_URL=https://api.kavenegar.com/v1
    
  3. First Use Case Send an SMS via a controller:

    use Ariaieboy\KavenegarLaravel\Facades\Kavenegar;
    
    public function sendSms()
    {
        $result = Kavenegar::send('1234567890', 'Hello from Laravel!');
        return $result->success() ? 'SMS sent!' : 'Failed: ' . $result->message();
    }
    
  4. Where to Look First

    • Facade: Ariaieboy\KavenegarLaravel\Facades\Kavenegar
    • Config: config/kavenegar.php
    • Exceptions: Ariaieboy\KavenegarLaravel\Exceptions\KavenegarException

Implementation Patterns

Core Workflows

  1. Basic SMS Sending

    Kavenegar::send($receiver, $message, ['smsType' => 'default']);
    
    • Supports optional parameters like smsType, lineNumber, and token.
  2. Verification Codes

    $verification = Kavenegar::sendVerificationCode($receiver, 6, [
        'template' => 'verify_code',
        'token' => 'user123',
    ]);
    
  3. Batch Sending

    $receivers = ['09123456789', '09987654321'];
    $result = Kavenegar::sendBatch($receivers, 'Hello batch!');
    
  4. Event-Based Integration Use Laravel events to trigger SMS after model actions:

    // In User model
    protected static function booted()
    {
        static::created(function ($user) {
            Kavenegar::send($user->phone, "Welcome, {$user->name}!");
        });
    }
    

Integration Tips

  • Queue Jobs: Wrap SMS calls in a job for async processing:
    use Ariaieboy\KavenegarLaravel\Jobs\SendSmsJob;
    
    SendSmsJob::dispatch($receiver, $message)->onQueue('sms');
    
  • Logging: Log responses for debugging:
    $result = Kavenegar::send($receiver, $message);
    \Log::info('Kavenegar response', $result->toArray());
    
  • Fallbacks: Implement fallback logic for failed sends:
    try {
        $result = Kavenegar::send($receiver, $message);
        if (!$result->success()) {
            // Fallback to email or another SMS provider
        }
    } catch (\Exception $e) {
        \Log::error('Kavenegar error', ['error' => $e->getMessage()]);
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Ensure .env is never committed to version control.
    • Use Laravel's .env ignore patterns.
  2. Rate Limits

    • Kavenegar enforces rate limits (e.g., 1 SMS/sec for free tier).
    • Implement exponential backoff in retries:
      $attempts = 0;
      while (!$result->success() && $attempts < 3) {
          $attempts++;
          sleep(2 ** $attempts); // Exponential delay
          $result = Kavenegar::send($receiver, $message);
      }
      
  3. Receiver Validation

    • Always validate phone numbers before sending:
      $receiver = preg_replace('/[^0-9]/', '', $phone); // Remove non-digits
      if (!preg_match('/^09\d{9}$/', $receiver)) {
          throw new \InvalidArgumentException('Invalid phone number');
      }
      
  4. Response Parsing

    • The success() method returns a boolean, but the underlying response may contain additional data:
      $result = Kavenegar::send($receiver, $message);
      if (!$result->success()) {
          \Log::error('Kavenegar error code: ' . $result->getErrorCode());
      }
      

Debugging

  • Enable Debug Mode Set debug to true in config/kavenegar.php to log raw API responses:
    'debug' => env('KAVENEGAR_DEBUG', false),
    
  • Check HTTP Status Codes Use Laravel's HTTP client to inspect raw responses:
    $response = \Http::withHeaders([
        'apikey' => config('kavenegar.api_key'),
    ])->post(config('kavenegar.api_url') . '/sms/send.json', [
        'receptor' => $receiver,
        'message' => $message,
    ]);
    

Extension Points

  1. Custom Templates Extend the package to support dynamic templates:

    // In a service class
    public function sendCustomTemplate($receiver, $data)
    {
        $message = $this->renderTemplate('welcome', $data);
        return Kavenegar::send($receiver, $message);
    }
    
  2. Webhook Handling Add a route to handle Kavenegar webhook callbacks:

    Route::post('/kavenegar/webhook', [KavenegarWebhookController::class, 'handle']);
    
    • Implement KavenegarWebhookController to parse and act on delivery reports.
  3. Mocking for Tests Use Laravel's HTTP mocking to test SMS sends:

    \Http::fake([
        config('kavenegar.api_url') . '/*' => Http::response([
            'status' => 'success',
            'message' => 'Mocked SMS',
        ]),
    ]);
    
  4. Multi-Provider Support Abstract the Kavenegar client to support multiple SMS providers:

    // In a service provider
    $this->app->bind(\Ariaieboy\KavenegarLaravel\Contracts\SmsProvider::class, function () {
        return new KavenegarProvider();
        // Or return new AlternativeProvider();
    });
    
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