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

shahabbasian/kavenegar

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require kavenegar/laravel
    

    Ensure Kavenegar\Laravel\ServiceProvider is added to config/app.php under providers and Kavenegar facade is added to aliases.

  2. Publish Config:

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

    This generates config/kavenegar.php. Update with your API key and default settings (e.g., sender, template type).

  3. First Use Case: Send a basic SMS via a facade call in a controller or service:

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

Implementation Patterns

Core Workflows

  1. Sending SMS:

    • Basic SMS:
      Kavenegar::send($receiver, $sender, $message);
      
    • Template-Based SMS (recommended for production):
      Kavenegar::sendTemplate($receiver, $sender, $templateId, ['var1' => 'value1']);
      
    • Async Sending (for background jobs):
      dispatch(new SendKavenegarSmsJob($receiver, $sender, $message));
      
  2. Verification & Validation:

    • Check API response status:
      $result = Kavenegar::send(...);
      if ($result['status'] === 'success') {
          // Handle success
      }
      
  3. Integration with Laravel Features:

    • Events: Trigger SMS on user registration/login:
      event(new Registered($user));
      // In listener:
      Kavenegar::send($user->phone, '1234567890', 'Welcome!');
      
    • Notifications: Extend MustBeVerified for SMS verification:
      use Kavenegar\Laravel\Notifications\VerifyPhoneNotification;
      
      $user->notify(new VerifyPhoneNotification($token));
      
  4. Configuration Management:

    • Override defaults per environment or dynamically:
      config(['kavenegar.sender' => 'NewSender']);
      

Gotchas and Tips

Pitfalls

  1. API Key Security:

    • Never hardcode the API key in .env or version control. Use Laravel’s .env file:
      KAVENEGAR_API_KEY=your_key_here
      
    • Update config/kavenegar.php to read from .env:
      'api_key' => env('KAVENEGAR_API_KEY'),
      
  2. Template Limitations:

    • Template IDs must be numeric strings (e.g., '123' not 'abc').
    • Variable names in templates must match exactly with the array keys passed to sendTemplate().
  3. Rate Limits:

    • Kavenegar enforces rate limits (e.g., 1 SMS/second for free tier). Handle 429 Too Many Requests gracefully:
      try {
          $result = Kavenegar::send(...);
      } catch (\Kavenegar\Exceptions\KavenegarException $e) {
          if ($e->getCode() === 429) {
              sleep(1); // Retry after delay
          }
      }
      
  4. Deprecation Warnings:

    • The package lacks Laravel 10+ testing. Test thoroughly in staging before production.

Debugging Tips

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

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

    Logs API responses to storage/logs/kavenegar.log.

  2. Mocking for Tests: Use a mock HTTP client (e.g., Guzzle) to intercept requests:

    $mock = Mockery::mock('overload', Kavenegar::class);
    $mock->shouldReceive('send')->andReturn(['status' => 'success']);
    
  3. Common Errors:

    • Invalid API Key: Verify .env and config file.
    • Template Not Found: Ensure the template ID exists in Kavenegar Panel.
    • Sender Not Allowed: Check sender number is whitelisted in Kavenegar dashboard.

Extension Points

  1. Custom Responses: Extend the facade to add domain-specific logic:

    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class CustomKavenegar extends Facade {
        protected static function getFacadeAccessor() {
            return 'custom.kavenegar';
        }
    }
    
  2. Queueable Jobs: Create a job for async sending:

    namespace App\Jobs;
    
    use Kavenegar\Facades\Kavenegar;
    use Illuminate\Bus\Queueable;
    
    class SendKavenegarSmsJob extends Job {
        use Queueable;
    
        public function handle() {
            Kavenegar::send($this->receiver, $this->sender, $this->message);
        }
    }
    
  3. Webhook Integration: Validate incoming Kavenegar webhooks (e.g., delivery reports) via middleware:

    namespace App\Http\Middleware;
    
    use Closure;
    use Kavenegar\Exceptions\InvalidSignatureException;
    
    class VerifyKavenegarWebhook {
        public function handle($request, Closure $next) {
            if ($request->isKavenegarWebhook()) {
                $this->validateSignature($request);
            }
            return $next($request);
        }
    }
    
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