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

erfanhemmati/kavenegar-php

PHP client for the Kavenegar RESTful SMS API. Install via Composer, set your API key, then send SMS to one or multiple recipients using KavenegarApi::Send. Includes basic exception handling and response details (messageid, status, cost).

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Synchronous API Client: The package is a thin wrapper around Kavenegar’s RESTful SMS API, making it suitable for Laravel applications requiring outbound SMS notifications (e.g., OTPs, alerts, transactional messages).
  • Event-Driven Potential: While the package itself is synchronous, it could be extended to integrate with Laravel’s queue system (e.g., sendLater via bus:queue) for async processing, reducing latency in high-traffic scenarios.
  • Laravel Ecosystem Compatibility: No native Laravel service provider or facade, but can be manually instantiated in controllers/services or wrapped in a custom facade/service for consistency.

Integration Feasibility

  • Low Coupling: Minimal dependencies (only PHP + Guzzle for HTTP requests), reducing risk of conflicts with existing Laravel packages.
  • API Key Management: Requires secure storage of the API key (e.g., Laravel’s .env or AWS Secrets Manager). No built-in encryption, so manual handling is needed.
  • Error Handling: Basic exceptions (ApiException, HttpException) align with Laravel’s exception handling but lack structured logging or retry logic (e.g., exponential backoff for transient failures).

Technical Risk

  • Vendor Lock-in: Tight coupling to Kavenegar’s API schema; migrating to another SMS provider (e.g., Twilio) would require rewriting logic.
  • No Type Safety: PHP 8+ type hints are absent, increasing risk of runtime errors (e.g., invalid sender/receptor formats).
  • Limited Features: No support for template-based SMS, scheduling, or inbound SMS handling (only outbound). May require custom extensions.
  • Documentation Gaps: README lacks examples for batch processing, webhook validation, or rate-limiting.

Key Questions

  1. Use Case Scope:
    • Is this for one-time notifications (e.g., OTPs) or high-volume campaigns? If the latter, async queuing is critical.
    • Are inbound SMS or webhook callbacks needed? If yes, the package is insufficient.
  2. Error Recovery:
    • How should failed SMS deliveries be retried? Manual implementation or a package like spatie/laravel-queue-retries?
  3. Cost Tracking:
    • Does the app need to log SMS costs (e.g., cost field in responses) for billing? If so, a custom observer or job is needed.
  4. Compliance:
    • Does the app require GDPR/CCPA compliance for SMS storage? The package doesn’t handle message archival.
  5. Testing:
    • How will SMS API responses be mocked in tests? The package lacks a test double (e.g., KavenegarApiMock).

Integration Approach

Stack Fit

  • Laravel Core: Works natively with PHP 7.4+ and Laravel 8+ (composer-based).
  • Service Container: Can be bound to Laravel’s IoC container for dependency injection:
    $this->app->singleton(KavenegarApi::class, fn($app) =>
        new KavenegarApi(config('services.kavenegar.api_key'))
    );
    
  • Queue Integration: Wrap KavenegarApi::Send() in a job (e.g., SendSmsJob) to decouple from HTTP requests:
    class SendSmsJob implements ShouldQueue {
        public function handle() {
            $api = app(KavenegarApi::class);
            $api->Send($this->sender, $this->receptors, $this->message);
        }
    }
    
  • Event System: Emit events (e.g., SmsSent) after successful API calls for downstream processing (e.g., analytics).

Migration Path

  1. Phase 1: Basic Integration
    • Install via Composer.
    • Store API key in .env (KAVENEGAR_API_KEY).
    • Implement a service class to wrap KavenegarApi (e.g., app/Services/SmsService.php).
    • Example:
      class SmsService {
          public function __construct(private KavenegarApi $api) {}
          public function sendOtp(string $phone, string $otp): void {
              $this->api->Send("10004346", [$phone], "Your OTP: $otp");
          }
      }
      
  2. Phase 2: Async & Resilience
    • Replace direct calls with queued jobs (e.g., SendSmsJob).
    • Add retry logic for transient failures (e.g., 3 retries with 5s delay).
  3. Phase 3: Observability
    • Log API responses to a database/table (e.g., sms_logs) for auditing.
    • Integrate with Laravel’s Horizon for queue monitoring.

Compatibility

  • PHP Version: Tested on PHP 7.4+ (Laravel 8+ LTS). No PHP 8.1+ features used (e.g., named arguments).
  • Laravel Version: No framework-specific dependencies, but Laravel 5.5+ recommended for service container support.
  • Database: None required, but custom logging may need a table (e.g., migrations/create_sms_logs_table.php).
  • Third-Party Risks: Relies on Guzzle (included via Composer), which is stable but may need updates.

Sequencing

  1. Prerequisites:
    • Register for a Kavenegar account and obtain an API key.
    • Configure .env:
      KAVENEGAR_API_KEY=your_api_key_here
      KAVENEGAR_SENDER=10004346
      
  2. Core Implementation:
    • Add to composer.json and run composer install.
    • Create a service class (e.g., SmsService) to abstract API calls.
  3. Advanced Features:
    • Implement queued jobs for async sending.
    • Add middleware to validate phone numbers (e.g., regex ^09\d{9}$ for Iran).
  4. Testing:
    • Mock KavenegarApi in unit tests (e.g., using Mockery).
    • Test edge cases: invalid API keys, rate limits, malformed phone numbers.

Operational Impact

Maintenance

  • Dependency Updates: Monitor for Guzzle/Kavenegar API changes (e.g., deprecated endpoints). Use composer why-not kavenegar/php to check for updates.
  • API Key Rotation: Implement a secure rotation process (e.g., via Laravel Forge/Envoyer) to avoid hardcoding keys.
  • Deprecation Risk: Kavenegar may change their API; the package lacks backward-compatibility tests.

Support

  • Vendor Support: Limited to Kavenegar’s support email. No GitHub issues or community-driven fixes.
  • Debugging: Errors are thrown as exceptions, but stack traces may not include context (e.g., which SMS failed). Consider adding:
    catch (\Kavenegar\Exceptions\ApiException $e) {
        Log::error("Kavenegar API failed", [
            'message' => $e->errorMessage(),
            'receptors' => $receptors,
            'sender' => $sender,
        ]);
        throw $e;
    }
    
  • Localization: No built-in support for Unicode messages or language-specific sender IDs.

Scaling

  • Rate Limits: Kavenegar’s API has rate limits (e.g., 100 SMS/minute). Implement:
    • Queue throttling (e.g., maxAttempts: 100 in SendSmsJob).
    • Circuit breakers (e.g., spatie/laravel-circuitbreaker) to avoid cascading failures.
  • Batch Processing: The package supports bulk SMS (array of receptors), but large batches (>100 recipients) may hit API limits. Split into chunks:
    array_chunk($phones, 50); // Process in batches of 50
    
  • Cost Monitoring: Track cost field in responses to avoid unexpected charges. Alert on anomalies (e.g., Laravel Monitor).

Failure Modes

Failure Scenario Impact Mitigation
API Key invalid/expired All SMS fail Automated key validation on app startup.
Kavenegar API downtime SMS delivery halted Queue retries + fallback to another provider.
Rate limit exceeded Partial SMS failures Exponential backoff + batch splitting.
Malformed phone numbers Invalid requests charged Validate phone numbers before API calls.
No internet connectivity
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui