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.
Installation:
composer require erfanhemmati/kavenegar
Ensure kavenegar/php is also installed (handled automatically by the package).
Register Service Provider & Facade:
Add to config/app.php:
'providers' => [
// ...
Kavenegar\Laravel\ServiceProvider::class,
],
'aliases' => [
// ...
'Kavenegar' => Kavenegar\Laravel\Facade::class,
]
Publish Config:
php artisan vendor:publish --provider="Kavenegar\Laravel\ServiceProvider"
Select the Kavenegar config option (e.g., 9 if listed).
Configure API Key:
Edit .env or config/kavenegar.php:
KAVENEGAR_API_KEY=your_api_key_here
use Kavenegar\Laravel\Facade\Kavenegar;
Kavenegar::send('1234567890', 'Hello from Laravel!', []);
receiver: Phone number (string, e.g., '09123456789').message: SMS content (string).options: Array for advanced settings (e.g., ['lineAlpha' => 'YourBrand']).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);
}
use Kavenegar\Laravel\Jobs\SendSMS;
SendSMS::dispatch('09123456789', 'Your OTP is: 1234', []);
SendSMS job is registered in App\Console\Kernel.php:
protected $jobs = [
\Kavenegar\Laravel\Jobs\SendSMS::class,
];
$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']]);
}
$template = "Hello {name}, your balance is {balance}.";
$params = ['name' => 'John', 'balance' => 1000];
Kavenegar::send('09123456789', $template, ['params' => $params]);
// In EventServiceProvider
protected $listen = [
'user.registered' => [
\App\Listeners\SendWelcomeSMS::class,
],
];
public function handle($event) {
Kavenegar::send($event->user->phone, 'Welcome!', []);
}
Override the default client in config/kavenegar.php:
'client' => [
'api_url' => 'https://custom-api.kavenegar.com/api/v1',
'timeout' => 30,
],
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);
});
Use Laravel’s rate limiting middleware:
Route::middleware(['throttle:10,1'])->group(function () {
Route::post('/sms', [SMSController::class, 'send']);
});
Mock the facade in tests:
$this->mock(Kavenegar::class)->shouldReceive('send')
->once()
->with('09123456789', 'Test', [])
->andReturn(['status' => 200]);
API Key Validation:
Kavenegar::send('09123456789', 'Test', []);
401 Unauthorized (invalid key) or 403 Forbidden (quota exceeded).Phone Number Formatting:
0 (e.g., 9123456789, not 09123456789).$phone = preg_replace('/^0/', '', $request->phone);
Queue Job Failures:
SendSMS jobs fail silently, check:
php artisan queue:work).receiver, message, options).Deprecated Laravel Versions:
Character Limits:
Enable Verbose Logging:
Add to config/kavenegar.php:
'debug' => env('KAVENEGAR_DEBUG', false),
Check logs for raw API responses.
Check HTTP Status Codes:
200: Success.400: Bad request (e.g., invalid phone).401: Invalid API key.429: Rate limit exceeded.Test with Sandbox Mode: Use Kavenegar’s sandbox API for testing:
Kavenegar::setApiUrl('https://sandbox.kavenegar.com/api/v1');
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. |
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;
}
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]);
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') {
How can I help you explore Laravel packages today?