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

erfanhemmati/kavenegar

Laravel integration for the Kavenegar SMS API. Install via Composer, register the service provider and facade, publish the config, and set your API key in config/kavenegar.php to start sending SMS from your Laravel app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require erfanhemmati/kavenegar
    

    Ensure kavenegar/php is also installed (handled automatically by the package).

  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 API Key: Edit .env or config/kavenegar.php:

    KAVENEGAR_API_KEY=your_api_key_here
    

First Use Case: Sending an SMS

use Kavenegar\Laravel\Facade\Kavenegar;

Kavenegar::send('1234567890', 'Hello from Laravel!', []);
  • Parameters:
    • receiver: Phone number (string, e.g., '09123456789').
    • message: SMS content (string).
    • options: Array for advanced settings (e.g., ['lineAlpha' => 'YourBrand']).

Implementation Patterns

Common Workflows

1. Sending SMS in Controllers

public function sendWelcomeSMS(Request $request) {
    $validated = $request->validate(['phone' => 'required|string']);
    $result = Kavenegar::send($validated['phone'], 'Welcome!', []);

    if ($result['status'] === 200) {
        return response()->json(['success' => true]);
    }
    return response()->json(['error' => $result['message']], 500);
}

2. Queueing SMS for Background Processing

use Kavenegar\Laravel\Jobs\SendSMS;

SendSMS::dispatch('09123456789', 'Your OTP is: 1234', []);
  • Queue Setup: Ensure SendSMS job is registered in App\Console\Kernel.php:
    protected $jobs = [
        \Kavenegar\Laravel\Jobs\SendSMS::class,
    ];
    

3. Handling Responses

$result = Kavenegar::send('09123456789', 'Test', []);
if ($result['status'] === 200) {
    // Success: Log or notify user
    Log::info('SMS sent successfully', ['response' => $result]);
} else {
    // Handle errors (e.g., invalid API key, quota exceeded)
    Log::error('SMS failed', ['error' => $result['message']]);
}

4. Dynamic Messages with Templates

$template = "Hello {name}, your balance is {balance}.";
$params = ['name' => 'John', 'balance' => 1000];
Kavenegar::send('09123456789', $template, ['params' => $params]);

5. Integration with Events

// In EventServiceProvider
protected $listen = [
    'user.registered' => [
        \App\Listeners\SendWelcomeSMS::class,
    ],
];
  • Listener:
    public function handle($event) {
        Kavenegar::send($event->user->phone, 'Welcome!', []);
    }
    

Advanced Patterns

1. Customizing the Kavenegar Client

Override the default client in config/kavenegar.php:

'client' => [
    'api_url' => 'https://custom-api.kavenegar.com/api/v1',
    'timeout' => 30,
],

2. Logging All SMS Activity

Extend the facade or service provider to log all requests:

// In ServiceProvider boot()
Kavenegar::setLogger(function ($message, array $context = []) {
    Log::channel('sms')->info($message, $context);
});

3. Rate Limiting

Use Laravel’s rate limiting middleware:

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

4. Testing SMS Sending

Mock the facade in tests:

$this->mock(Kavenegar::class)->shouldReceive('send')
    ->once()
    ->with('09123456789', 'Test', [])
    ->andReturn(['status' => 200]);

Gotchas and Tips

Pitfalls

  1. API Key Validation:

    • The package does not validate the API key on installation. Always test with a dummy key first:
      Kavenegar::send('09123456789', 'Test', []);
      
    • Error Handling: Check for 401 Unauthorized (invalid key) or 403 Forbidden (quota exceeded).
  2. Phone Number Formatting:

    • Kavenegar expects Iranian phone numbers without 0 (e.g., 9123456789, not 09123456789).
    • Fix: Normalize numbers in your code:
      $phone = preg_replace('/^0/', '', $request->phone);
      
  3. Queue Job Failures:

    • If SendSMS jobs fail silently, check:
      • Queue worker is running (php artisan queue:work).
      • Job payload includes all required fields (receiver, message, options).
  4. Deprecated Laravel Versions:

    • The package claims support for Laravel 4–10, but no tests are provided. Test thoroughly on older versions.
  5. Character Limits:

    • Kavenegar enforces a 300-character limit per SMS. Long messages auto-split but may incur extra costs.

Debugging Tips

  1. Enable Verbose Logging: Add to config/kavenegar.php:

    'debug' => env('KAVENEGAR_DEBUG', false),
    

    Check logs for raw API responses.

  2. Check HTTP Status Codes:

    • 200: Success.
    • 400: Bad request (e.g., invalid phone).
    • 401: Invalid API key.
    • 429: Rate limit exceeded.
  3. Test with Sandbox Mode: Use Kavenegar’s sandbox API for testing:

    Kavenegar::setApiUrl('https://sandbox.kavenegar.com/api/v1');
    
  4. Common Errors & Fixes:

    Error Message Solution
    Invalid API Key Regenerate key in Kavenegar panel.
    Invalid Phone Number Ensure format: 9123456789 (no 0).
    Quota Exceeded Upgrade plan or check usage in panel.
    Job Failed (queue) Check failed_jobs table in DB.

Extension Points

  1. Custom Response Handling: Extend the facade to transform responses:

    // In a service class
    public function sendWithRetry($phone, $message, $options = []) {
        $attempts = 0;
        while ($attempts < 3) {
            $result = Kavenegar::send($phone, $message, $options);
            if ($result['status'] === 200) break;
            $attempts++;
            sleep(2);
        }
        return $result;
    }
    
  2. Add SMS Templates: Store templates in the database and fetch dynamically:

    $template = DB::table('sms_templates')->where('name', 'welcome')->first();
    Kavenegar::send($phone, $template->body, ['params' => $data]);
    
  3. Webhook Integration: Listen for Kavenegar webhook events (e.g., delivery reports):

    Route::post('/kavenegar/webhook', function (Request $request) {
        $event = $request->input('event');
        if ($event === 'delivery') {
    
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