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

Plivo Php Laravel Package

plivo/plivo-php

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require plivo/plivo-php:^4.69.1

Verify the package is autoloaded in composer.json under require.

  1. First Use Case: Sending an SMS

    use Plivo\RestClient;
    
    $client = new RestClient('YOUR_AUTH_ID', 'YOUR_AUTH_TOKEN');
    $response = $client->messages()->create(
        '+12025551234', // From number
        '+12025555678', // To number
        'Hello from Laravel!'
    );
    return $response->message_uuid;
    
  2. Where to Look First

    • Official Documentation (if available)
    • src/Plivo/RestClient.php (core client class)
    • src/Plivo/Exceptions/ (error handling)
    • src/Plivo/PhoneNumberCompliance/ (new compliance API)
    • tests/ (real-world examples)

Implementation Patterns

Common Workflows

1. SMS & MMS

  • Bulk SMS with Queue

    $client = new RestClient(config('plivo.auth_id'), config('plivo.auth_token'));
    $messages = [
        ['to' => '+12025551234', 'text' => 'Message 1'],
        ['to' => '+12025555678', 'text' => 'Message 2'],
    ];
    foreach ($messages as $msg) {
        dispatch(new SendSmsJob($client, $msg));
    }
    
  • MMS with Media

    $response = $client->messages()->create(
        '+12025551234',
        '+12025555678',
        'Check this out!',
        ['media_urls' => ['https://example.com/image.jpg']]
    );
    

2. Calls

  • Make a Call

    $response = $client->calls()->create(
        '+12025551234', // From
        '+12025555678', // To
        'https://example.com/answer.xml' // Answer URL
    );
    
  • Answer URL (Laravel Route)

    Route::post('/answer', function (Request $request) {
        $call = $request->input('Call');
        // Handle call logic (e.g., play audio, transfer)
        return response()->xml('<Response><Say>Hello!</Say></Response>');
    });
    

3. Numbers

  • Buy a Number

    $response = $client->numbers()->create(
        '+1202', // Country code + area code
        ['capabilities' => ['inbound' => true, 'outbound' => true]]
    );
    
  • List Numbers

    $numbers = $client->numbers()->get();
    foreach ($numbers as $number) {
        log($number->phone_number);
    }
    

4. Phone Number Compliance (New in 4.69.1)

  • Check Number Compliance

    $compliance = $client->phoneNumberCompliance()->check(
        '+12025551234', // Phone number to validate
        ['type' => 'mobile'] // Optional: 'mobile', 'landline', etc.
    );
    if ($compliance->is_compliant) {
        log("Number is compliant for messaging.");
    } else {
        log("Number compliance issues: " . $compliance->reason);
    }
    
  • Bulk Compliance Check

    $numbers = ['+12025551234', '+12025555678'];
    foreach ($numbers as $number) {
        $compliance = $client->phoneNumberCompliance()->check($number);
        log("{$number}: " . ($compliance->is_compliant ? 'Compliant' : 'Non-compliant'));
    }
    

5. Integration with Laravel

  • Service Provider

    // app/Providers/PlivoServiceProvider.php
    public function register()
    {
        $this->app->singleton(PlivoClient::class, function ($app) {
            return new RestClient(
                config('plivo.auth_id'),
                config('plivo.auth_token')
            );
        });
    }
    
  • Config File

    // config/plivo.php
    return [
        'auth_id' => env('PLIVO_AUTH_ID'),
        'auth_token' => env('PLIVO_AUTH_TOKEN'),
        'default_from' => '+12025551234',
    ];
    
  • Facade (Optional)

    // app/Facades/Plivo.php
    public static function checkNumberCompliance($number)
    {
        return app(PlivoClient::class)->phoneNumberCompliance()->check($number);
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limits

    • Plivo enforces rate limits (e.g., 1 SMS/sec by default). Handle Plivo\Exceptions\RateLimitException gracefully.
    • Fix: Implement exponential backoff in retries or use batch processing.
  2. Number Formatting

    • Always validate phone numbers with Plivo\Utils::is_valid_phone_number().
    • Example:
      if (!Plivo\Utils::is_valid_phone_number('+12025551234')) {
          throw new \InvalidArgumentException('Invalid number');
      }
      
  3. Answer URL Timeouts

    • Plivo waits 60 seconds for an answer URL response. Ensure your Laravel endpoint is fast and returns XML.
    • Tip: Use response()->xml() instead of JSON for call responses.
  4. Webhook Verification

    • Plivo sends webhooks with an X-Plivo-Signature header. Verify it to prevent spoofing.
    • Example Middleware:
      public function handle($request, Closure $next)
      {
          $signature = $request->header('X-Plivo-Signature');
          $payload = $request->getContent();
          if (!Plivo\Utils::verify_webhook_signature($payload, $signature, config('plivo.auth_token'))) {
              abort(403);
          }
          return $next($request);
      }
      
  5. Phone Number Compliance (New)

    • Non-compliant numbers may fail SMS delivery or incur penalties.
    • Tip: Always check compliance before sending messages:
      $compliance = $client->phoneNumberCompliance()->check($toNumber);
      if (!$compliance->is_compliant) {
          log("Skipping non-compliant number: {$toNumber}");
          continue;
      }
      

Debugging

  • Enable Logging

    $client = new RestClient('AUTH_ID', 'AUTH_TOKEN', [
        'log' => true,
        'log_file' => storage_path('logs/plivo.log')
    ]);
    
  • Common Errors

    Error Class Cause Solution
    Plivo\Exceptions\AuthenticationError Invalid auth_id/auth_token Check .env credentials
    Plivo\Exceptions\InvalidArgument Malformed request (e.g., invalid URL) Validate inputs before sending
    Plivo\Exceptions\ApiError Plivo API rejected request Check Plivo dashboard for details
    Plivo\Exceptions\ComplianceError Number failed compliance check Review compliance response

Extension Points

  1. Custom Middleware

    • Extend Plivo\RestClient to add request/response filters:
      $client = new class('AUTH_ID', 'AUTH_TOKEN') extends RestClient {
          protected function modifyRequest($request) {
              $request->headers->set('X-Custom-Header', 'value');
              return $request;
          }
      };
      
  2. Event Dispatching for Compliance

    • Trigger Laravel events for compliance results:
      $compliance = $client->phoneNumberCompliance()->check($number);
      if (!$compliance->is_compliant) {
          event(new NumberComplianceFailed($number, $compliance->reason));
      }
      
  3. Mocking for Tests

    • Use Plivo\MockClient in phpunit.xml:
      <env name="PLIVO_MOCK" value="true"/>
      
    • Test Example:
      $mockClient = new Plivo\MockClient();
      $mockClient->expects('phoneNumberCompliance.check')->once()->andReturn
      
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle