erfanhemmati/kavenegar-laravel-notification
Laravel 5.3/5.4 notification channel for sending SMS via Kavenegar. Configure your API key (and optional sender) in services.php, add the service provider, then use KavenegarChannel in notifications and routeNotificationForSms to supply the recipient number.
Installation:
composer require erfanhemmati/kavenegar-laravel-notification
Register the service provider in config/app.php:
Kavenegar\LaravelNotification\KavenegarServiceProvider::class,
Configure API Key:
Add your Kavenegar API key and sender number (optional) in config/services.php:
'kavenegar' => [
'key' => env('KAVENEGAR_API_KEY'),
'sender' => env('KAVENEGAR_SENDER'),
],
First Use Case:
Create a notification class (e.g., HappyNewYear) and use the KavenegarChannel in the via() method:
use Kavenegar\LaravelNotification\KavenegarChannel;
public function via($notifiable) {
return [KavenegarChannel::class];
}
Define SMS Content:
Implement the toSMS() method to return the message string:
public function toSMS($notifiable) {
return 'Happy new year!';
}
Route Notifications:
Add routeNotificationForSms() to your User model (or notifiable model):
public function routeNotificationForSms() {
return $this->phone_number; // Ensure this field exists
}
Send Notification: Trigger the notification via a user instance:
$user->notify(new HappyNewYear());
Dynamic Message Content:
Use the toSMS() method to dynamically generate messages based on user data:
public function toSMS($notifiable) {
return "Hello {$notifiable->name}, your verification code is: {$this->code}";
}
Multi-Channel Notifications:
Combine KavenegarChannel with other channels (e.g., MailChannel) for hybrid notifications:
public function via($notifiable) {
return [MailChannel::class, KavenegarChannel::class];
}
Conditional SMS Sending:
Override via() to conditionally include KavenegarChannel:
public function via($notifiable) {
return $notifiable->prefers_sms ? [KavenegarChannel::class] : [];
}
Reusing Notifications: Extend base notification classes to avoid repetition:
class BaseSMSNotification extends Notification {
public function via($notifiable) {
return [KavenegarChannel::class];
}
}
Queueing Notifications: Leverage Laravel’s queue system for async SMS delivery:
$user->notify(new HappyNewYear())->onQueue('sms');
Customizing Sender: Override the sender number per notification by extending the channel:
class CustomKavenegarChannel extends KavenegarChannel {
protected $sender = 'MyApp';
}
Two-Factor Authentication (2FA):
public function toSMS($notifiable) {
return "Your 2FA code: {$this->code}";
}
Password Reset:
public function toSMS($notifiable) {
return "Reset your password: {$this->url}";
}
Order Confirmation:
public function toSMS($notifiable) {
return "Order #{$this->order->id} confirmed. Total: {$this->order->total}";
}
Alerts/Reminders:
$user->notify(new Reminder())->delay(now()->addMinutes(10));
Environment Configuration:
Use .env for sensitive data:
KAVENEGAR_API_KEY=your_api_key_here
KAVENEGAR_SENDER=YourSenderName
Logging Failures: Extend the channel to log failed sends:
class KavenegarChannel extends \Kavenegar\LaravelNotification\KavenegarChannel {
public function send($notifiable, $message) {
try {
parent::send($notifiable, $message);
} catch (\Exception $e) {
\Log::error("Kavenegar SMS failed: " . $e->getMessage());
throw $e;
}
}
}
Testing:
Use Laravel’s NotificationFake for unit tests:
$this->fake()->assertSent(function ($notification) {
return $notification instanceof HappyNewYear;
});
Rate Limiting: Implement rate limiting in middleware or the channel itself to avoid API throttling.
Missing routeNotificationForSms:
Call to undefined method User::routeNotificationForSms().Invalid API Key:
Kavenegar API request failed or empty responses.KAVENEGAR_API_KEY in .env and config/services.php.Sender Number Restrictions:
Message Length Limits:
Queue Deadlocks:
failed_jobs table size if needed.Timeouts:
max_execution_time or implement retry logic.Enable Debugging: Add debug logging to the channel:
\Log::debug("Sending SMS to {$notifiable->routeNotificationForSms()}: {$message}");
Check API Responses: Inspect raw responses from Kavenegar:
$response = $this->kavenegar->send($message, $notifiable->routeNotificationForSms());
\Log::debug("Kavenegar Response: " . print_r($response, true));
Test with Postman: Manually test your API key and sender using Kavenegar’s API docs.
Validate Phone Numbers:
Ensure phone numbers are in the correct format (e.g., +989123456789 for Iran).
Sender Number Fallback:
If KAVENEGAR_SENDER is not set, Kavenegar uses a default sender (e.g., Kavenegar). Configure it explicitly for branding:
'sender' => env('KAVENEGAR_SENDER', 'YourAppName'),
Environment-Specific Keys:
Use .env placeholders for different environments:
KAVENEGAR_API_KEY=${KAVENEGAR_KEY_STAGING}
Caching API Key: Avoid caching the Kavenegar client instance if the key changes frequently (e.g., in testing).
Custom Channel Logic:
Extend KavenegarChannel to add features like:
Event-Based Notifications:
Listen to Laravel events (e.g., registered, password.resetting) and dispatch SMS notifications:
Event::listen('registered', function ($user) {
$user->notify(new WelcomeSMS());
});
Bulk SMS: Implement a batch sender for marketing campaigns:
class BulkKavenegarChannel extends KavenegarChannel {
public function sendBulk(array $users, $message) {
foreach ($users as $user) {
$this->send($user, $message);
}
}
}
Fallback Channels: Add fallback logic if Kavenegar fails:
How can I help you explore Laravel packages today?