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

Php Laravel Package

kavenegar/php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require kavenegar/php
    

    Ensure your composer.json includes "kavenegar/php": "^1.2.1" (or latest stable version).

  2. Retrieve API Key Sign up at Kavenegar Panel and grab your API key from Settings.

  3. First Use Case: Send SMS

    use Kavenegar\KavenegarApi;
    
    $api = new KavenegarApi(env('KAVENEGAR_API_KEY'));
    $sender = "10004346"; // Your sender ID (e.g., "1000XXXX")
    $receptors = ["09123456789", "09367891011"];
    $message = "Your SMS content here";
    
    try {
        $result = $api->Send($sender, $receptors, $message);
        // Handle response (see below)
    } catch (\Kavenegar\Exceptions\ApiException $e) {
        log::error($e->errorMessage());
    }
    
  4. Environment Configuration Add to .env:

    KAVENEGAR_API_KEY=your_api_key_here
    

Implementation Patterns

Core Workflows

  1. Sending SMS

    • Single Recipient:
      $result = $api->Send($sender, ["09123456789"], $message);
      
    • Bulk Recipients:
      $result = $api->Send($sender, ["09123456789", "09367891011"], $message);
      
    • Async Handling: Use Laravel’s queue to defer SMS sending:
      dispatch(new SendSmsJob($sender, $receptors, $message));
      
  2. Verifying API Responses Check status and statustext in the response:

    if ($result && $result[0]->status === 1) {
        // Success (e.g., "در صف ارسال")
    }
    
  3. Error Handling

    • API Errors (e.g., invalid API key, rate limits):
      catch (\Kavenegar\Exceptions\ApiException $e) {
          $this->handleApiError($e->errorMessage());
      }
      
    • HTTP Errors (e.g., network issues):
      catch (\Kavenegar\Exceptions\HttpException $e) {
          $this->handleHttpError($e->errorMessage());
      }
      
  4. Logging Responses Log raw responses for debugging:

    \Log::debug('Kavenegar Response:', ['data' => $result]);
    

Integration Tips

  1. Laravel Service Provider Bind the API client to the container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->singleton(KavenegarApi::class, function ($app) {
            return new KavenegarApi(env('KAVENEGAR_API_KEY'));
        });
    }
    

    Usage in controllers:

    use KavenegarApi;
    
    public function sendSms(KavenegarApi $api) {
        $api->Send($sender, $receptors, $message);
    }
    
  2. Queue Jobs Create a job for async SMS sending:

    // app/Jobs/SendSmsJob.php
    public function handle() {
        $api = new KavenegarApi(env('KAVENEGAR_API_KEY'));
        $api->Send($this->sender, $this->receptors, $this->message);
    }
    
  3. Validation Validate phone numbers before sending:

    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make(['phone' => $receptor], [
        'phone' => 'required|string|regex:/^09[0-9]{9}$/'
    ]);
    
  4. Rate Limiting Implement a throttle middleware to avoid hitting API limits:

    // app/Http/Middleware/ThrottleKavenegar.php
    public function handle($request, Closure $next) {
        return parent::handle($request, $next)
            ->throttle(['kavenegar' => 1, 'minute']);
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Never hardcode API keys in source files. Use Laravel’s .env.
    • Restrict access to .env in version control (add to .gitignore).
  2. Phone Number Format

    • Kavenegar expects 09xxxxxxxx format (no + or 0098 prefixes).
    • Validate input to avoid failed requests:
      $cleanedPhone = preg_replace('/[^0-9]/', '', $phone);
      
  3. Response Parsing

    • The Send() method returns an array of objects. Always check entries for per-recipient statuses:
      if (empty($result[0]->entries)) {
          throw new \RuntimeException("No entries in response");
      }
      
  4. Deprecated Methods

    • The package is outdated (last release: 2019). Test thoroughly or fork for updates.
  5. Cost Tracking

    • Monitor cost in responses to track SMS expenses:
      $totalCost = array_sum(array_map(fn($r) => $r->cost, $result));
      

Debugging Tips

  1. Enable Guzzle Logging Configure Guzzle to log HTTP requests:

    $api = new KavenegarApi(env('KAVENEGAR_API_KEY'));
    $api->getClient()->getEmitter()->addSubscriber(new \GuzzleHttp\HandlerStack());
    
  2. Mock API Calls Use Laravel’s Mockery to test without hitting the real API:

    $mock = Mockery::mock(KavenegarApi::class);
    $mock->shouldReceive('Send')->andReturn([(object)['status' => 1]]);
    
  3. Check API Status Verify Kavenegar’s service status at status.kavenegar.com.


Extension Points

  1. Custom Response Handling Extend the KavenegarApi class to add methods for specific use cases:

    class ExtendedKavenegarApi extends KavenegarApi {
        public function sendVerificationCode($phone, $code) {
            $message = "Your verification code: {$code}";
            return $this->Send("10004346", [$phone], $message);
        }
    }
    
  2. Webhook Integration Use Kavenegar’s webhook feature to receive delivery reports:

    // routes/web.php
    Route::post('/kavenegar-webhook', [SmsWebhookController::class]);
    
  3. Fallback Mechanisms Implement retries for failed sends:

    use Illuminate\Support\Facades\Retry;
    
    Retry::retry(3, function () use ($api, $sender, $receptors, $message) {
        $result = $api->Send($sender, $receptors, $message);
        if ($result[0]->status !== 1) {
            throw new \RuntimeException("SMS failed");
        }
    });
    
  4. Local Testing Use a local SMS gateway (e.g., Twilio Sandbox) during development.

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor