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

mohamadtsn/kavenegar-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mohamadtsn/kavenegar-laravel
    

    Ensure kavenegar/php is also installed (handled automatically via dependency).

  2. Register Service Provider & Facade: Add to config/app.php:

    'providers' => [
        // ...
        Kavenegar\Laravel\ServiceProvider::class,
    ],
    'aliases' => [
        // ...
        'Kavenegar' => Kavenegar\Laravel\Facade::class,
    ],
    
  3. Publish Config:

    php artisan vendor:publish --provider="Kavenegar\Laravel\ServiceProvider"
    

    Select the Kavenegar config option (e.g., 9 if listed).

  4. Configure .env:

    KAVENEGAR_API_KEY=your_api_key_here
    KAVENEGAR_SANDBOX=false  # Set to `true` for testing
    
  5. First Use Case: Send an SMS via facade:

    use Kavenegar\Facades\Kavenegar;
    
    Kavenegar::send('1234567890', 'Hello from Laravel!');
    

Implementation Patterns

Core Workflows

  1. Sending SMS:

    • Basic:
      Kavenegar::send('recipient_number', 'message_text');
      
    • With Options:
      Kavenegar::send([
          'receptor' => '1234567890',
          'message'  => 'Hello',
          'type'     => 'sms', // or 'voice'
          'token'    => '123456', // optional token for verification
      ]);
      
  2. Verification Codes:

    $token = Kavenegar::send([
        'receptor' => '1234567890',
        'message'  => 'Your code is {code}',
        'token'    => '123456',
        'type'     => 'sms',
    ]);
    
  3. Queueing SMS: Dispatch a job (Laravel 5.5+):

    use Kavenegar\Jobs\SendSms;
    
    SendSms::dispatch('1234567890', 'Hello')->onQueue('sms');
    
  4. Customizing Responses: Override default response handling in app/Providers/KavenegarServiceProvider.php:

    public function boot()
    {
        Kavenegar::setResponseHandler(function ($response) {
            return $response->data; // or custom logic
        });
    }
    

Integration Tips

  • Validation: Use Laravel’s validation to sanitize recipient numbers:
    $request->validate(['phone' => 'required|digits:11|starts_with:0']);
    
  • Logging: Log failed sends via a middleware or observer:
    Kavenegar::catch(function ($exception) {
        Log::error('Kavenegar failed: ' . $exception->getMessage());
    });
    
  • Testing: Use sandbox mode (KAVENEGAR_SANDBOX=true) with test numbers from Kavenegar’s docs.

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never commit .env or hardcode keys. Use Laravel’s .env or a secure secrets manager.
    • Fix: Validate .env is in .gitignore.
  2. Rate Limits:

    • Kavenegar enforces rate limits. Handle KavenegarException for throttling:
      try {
          Kavenegar::send('1234567890', 'Message');
      } catch (\Kavenegar\Exceptions\KavenegarException $e) {
          if ($e->getCode() === 429) {
              // Retry logic or notify admin
          }
      }
      
  3. Number Formatting:

    • Recipient numbers must include the country code (e.g., +989121234567 for Iran).
    • Fix: Use a helper or middleware to format numbers:
      $formattedNumber = '+98' . ltrim($request->phone, '0');
      
  4. Queue Deadlocks:

    • If using queues, ensure KAVENEGAR_API_KEY is available in the queue worker’s environment (e.g., via shared storage or .env in the worker container).
  5. Deprecated Methods:

    • Avoid Kavenegar::sendSms() (deprecated in favor of Kavenegar::send()).

Debugging

  1. Enable Debug Mode: Set KAVENEGAR_DEBUG=true in .env to log raw API responses to storage/logs/kavenegar.log.

  2. Common Errors:

    Error Code Cause Solution
    400 Invalid API key Check .env and regenerate key.
    403 Insufficient balance Top up your Kavenegar account.
    429 Rate limit exceeded Implement exponential backoff.
    500 Server error Contact Kavenegar support.
  3. Testing Locally:

    • Use KAVENEGAR_SANDBOX=true and test numbers like 1000000000 (sandbox-only).

Extension Points

  1. Custom HTTP Client: Override the default Guzzle client in the service provider:

    $this->app->singleton(\Kavenegar\Kavenegar::class, function ($app) {
        $client = new \GuzzleHttp\Client([
            'timeout' => 10,
            'headers' => ['User-Agent' => 'MyApp/1.0'],
        ]);
        return new \Kavenegar\Kavenegar($app['config']['kavenegar.api_key'], $client);
    });
    
  2. Add New Features: Extend the facade to support custom endpoints:

    // In app/Providers/KavenegarServiceProvider.php
    public function boot()
    {
        if (method_exists(Kavenegar::class, 'customMethod')) {
            Kavenegar::extend('customMethod', function () {
                // Custom logic
            });
        }
    }
    
  3. Local Overrides: Override config values in config/kavenegar.php:

    'timeout' => 15, // Default is 10 seconds
    'endpoint' => env('KAVENEGAR_CUSTOM_ENDPOINT', 'https://api.kavenegar.com/v1'),
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor