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

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require erfanhemmati/kavenegar-laravel-notification
    

    Register the service provider in config/app.php:

    Kavenegar\LaravelNotification\KavenegarServiceProvider::class,
    
  2. 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'),
    ],
    
  3. 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];
    }
    
  4. Define SMS Content: Implement the toSMS() method to return the message string:

    public function toSMS($notifiable) {
        return 'Happy new year!';
    }
    
  5. Route Notifications: Add routeNotificationForSms() to your User model (or notifiable model):

    public function routeNotificationForSms() {
        return $this->phone_number; // Ensure this field exists
    }
    
  6. Send Notification: Trigger the notification via a user instance:

    $user->notify(new HappyNewYear());
    

Implementation Patterns

Usage Patterns

  1. 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}";
    }
    
  2. Multi-Channel Notifications: Combine KavenegarChannel with other channels (e.g., MailChannel) for hybrid notifications:

    public function via($notifiable) {
        return [MailChannel::class, KavenegarChannel::class];
    }
    
  3. Conditional SMS Sending: Override via() to conditionally include KavenegarChannel:

    public function via($notifiable) {
        return $notifiable->prefers_sms ? [KavenegarChannel::class] : [];
    }
    
  4. Reusing Notifications: Extend base notification classes to avoid repetition:

    class BaseSMSNotification extends Notification {
        public function via($notifiable) {
            return [KavenegarChannel::class];
        }
    }
    
  5. Queueing Notifications: Leverage Laravel’s queue system for async SMS delivery:

    $user->notify(new HappyNewYear())->onQueue('sms');
    
  6. Customizing Sender: Override the sender number per notification by extending the channel:

    class CustomKavenegarChannel extends KavenegarChannel {
        protected $sender = 'MyApp';
    }
    

Workflows

  1. Two-Factor Authentication (2FA):

    • Generate a code, store it in the session, and send via SMS:
      public function toSMS($notifiable) {
          return "Your 2FA code: {$this->code}";
      }
      
  2. Password Reset:

    • Send a reset link via SMS:
      public function toSMS($notifiable) {
          return "Reset your password: {$this->url}";
      }
      
  3. Order Confirmation:

    • Send order details dynamically:
      public function toSMS($notifiable) {
          return "Order #{$this->order->id} confirmed. Total: {$this->order->total}";
      }
      
  4. Alerts/Reminders:

    • Schedule notifications for time-sensitive alerts:
      $user->notify(new Reminder())->delay(now()->addMinutes(10));
      

Integration Tips

  1. Environment Configuration: Use .env for sensitive data:

    KAVENEGAR_API_KEY=your_api_key_here
    KAVENEGAR_SENDER=YourSenderName
    
  2. 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;
            }
        }
    }
    
  3. Testing: Use Laravel’s NotificationFake for unit tests:

    $this->fake()->assertSent(function ($notification) {
        return $notification instanceof HappyNewYear;
    });
    
  4. Rate Limiting: Implement rate limiting in middleware or the channel itself to avoid API throttling.


Gotchas and Tips

Pitfalls

  1. Missing routeNotificationForSms:

    • Error: Call to undefined method User::routeNotificationForSms().
    • Fix: Ensure the method is defined in your notifiable model.
  2. Invalid API Key:

    • Error: Kavenegar API request failed or empty responses.
    • Fix: Verify KAVENEGAR_API_KEY in .env and config/services.php.
  3. Sender Number Restrictions:

    • Error: SMS sent with an invalid/blocked sender number.
    • Fix: Check Kavenegar’s sender number guidelines and ensure the sender is approved.
  4. Message Length Limits:

    • Error: Long messages are truncated or fail silently.
    • Fix: Kavenegar supports up to 310 characters (including spaces). Split longer messages or use Unicode optimizations.
  5. Queue Deadlocks:

    • Error: SMS notifications stuck in the queue.
    • Fix: Monitor queue workers and adjust failed_jobs table size if needed.
  6. Timeouts:

    • Error: API requests timeout during peak loads.
    • Fix: Increase PHP’s max_execution_time or implement retry logic.

Debugging

  1. Enable Debugging: Add debug logging to the channel:

    \Log::debug("Sending SMS to {$notifiable->routeNotificationForSms()}: {$message}");
    
  2. Check API Responses: Inspect raw responses from Kavenegar:

    $response = $this->kavenegar->send($message, $notifiable->routeNotificationForSms());
    \Log::debug("Kavenegar Response: " . print_r($response, true));
    
  3. Test with Postman: Manually test your API key and sender using Kavenegar’s API docs.

  4. Validate Phone Numbers: Ensure phone numbers are in the correct format (e.g., +989123456789 for Iran).

Config Quirks

  1. 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'),
    
  2. Environment-Specific Keys: Use .env placeholders for different environments:

    KAVENEGAR_API_KEY=${KAVENEGAR_KEY_STAGING}
    
  3. Caching API Key: Avoid caching the Kavenegar client instance if the key changes frequently (e.g., in testing).

Extension Points

  1. Custom Channel Logic: Extend KavenegarChannel to add features like:

    • Message Templates: Predefined templates for common use cases.
    • Attachments: Support for sending images/videos (if Kavenegar supports it).
    • Webhooks: Trigger actions on SMS delivery status.
  2. 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());
    });
    
  3. 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);
            }
        }
    }
    
  4. Fallback Channels: Add fallback logic if Kavenegar fails:

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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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