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

Sdk Laravel Package

twilio/sdk

Official Twilio PHP SDK for working with Twilio’s APIs (SMS, Voice, WhatsApp, Verify, and more). Install via Composer, supports PHP 7.2–8.4, and provides a typed client to send messages, make calls, and manage Twilio resources.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require twilio/sdk
    

    Add to config/services.php (Laravel):

    'twilio' => [
        'account_sid' => env('TWILIO_SID'),
        'auth_token' => env('TWILIO_TOKEN'),
        'region' => env('TWILIO_REGION', 'us1'),
    ],
    
  2. Service Provider: Register in config/app.php:

    'providers' => [
        // ...
        Twilio\Laravel\TwilioServiceProvider::class,
    ],
    
  3. First Use Case: Send an SMS via a Laravel controller:

    use Twilio\Laravel\Facades\Twilio;
    
    public function sendSms()
    {
        $message = Twilio::message('+15558675309', 'Hello from Laravel!');
        $message->send();
        return response()->json(['success' => true]);
    }
    

Implementation Patterns

Core Workflows

  1. Twilio Client Initialization:

    // Via Facade (Laravel)
    Twilio::setAccountSid(env('TWILIO_SID'));
    Twilio::setAuthToken(env('TWILIO_TOKEN'));
    
    // Or via Service Container
    $client = app('twilio');
    
  2. Common API Calls:

    • SMS:
      $message = Twilio::message('+15558675309', 'Hello!');
      $message->send();
      
    • Calls:
      $call = Twilio::call('+15558675309', '+15017250604');
      $call->url('https://example.com/twiml')->make();
      
    • TwiML Generation:
      $response = new \Twilio\TwiML\VoiceResponse();
      $response->say('Welcome!');
      return response($response)->header('Content-Type', 'text/xml');
      
  3. Pagination & Streaming:

    // Eager fetch (read)
    $messages = Twilio::messages()->read(['status' => 'sent'], 10);
    
    // Lazy fetch (stream)
    $stream = Twilio::messages()->stream(['status' => 'sent'], 100, 20);
    foreach ($stream as $message) {
        // Process each message
    }
    
  4. Event Hooks (Webhooks): Validate and handle incoming Twilio events:

    public function handleIncomingSms(Request $request)
    {
        $event = new \Twilio\Laravel\Events\IncomingSms($request);
        event($event);
    
        return response()->json(['success' => true]);
    }
    

Integration Tips

  • Environment Variables: Use Laravel's .env for credentials:

    TWILIO_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    TWILIO_TOKEN=yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
    TWILIO_REGION=us1
    
  • Middleware for Auth: Protect Twilio webhook routes:

    Route::post('/twilio-webhook', [TwilioController::class, 'handleWebhook'])
         ->middleware('twilio.signature');
    
  • Testing: Use Mockery or Laravel's MockHttpClient:

    $client = new \Twilio\Rest\Client('AC123', 'token');
    $client->setHttpClient(new \Mockery\MockInterface());
    

Gotchas and Tips

Pitfalls

  1. Authentication Errors:

    • Symptom: 20003 or 21211 errors.
    • Fix: Verify TWILIO_SID/TWILIO_TOKEN in .env and ensure no typos. Use setLogLevel('debug') to inspect requests:
      Twilio::setLogLevel('debug');
      
  2. Rate Limiting:

    • Twilio enforces rate limits. Handle 429 responses gracefully:
      try {
          $message->send();
      } catch (\Twilio\Exceptions\TwilioException $e) {
          if ($e->getCode() === 429) {
              sleep(1); // Retry after delay
              $message->send();
          }
      }
      
  3. TwiML Validation:

    • Invalid TwiML throws TwimlException. Validate XML structure:
      try {
          $response = new \Twilio\TwiML\VoiceResponse();
          $response->invalidTag(); // Throws exception
      } catch (\Twilio\Exceptions\TwimlException $e) {
          Log::error($e->getMessage());
      }
      
  4. Timeouts:

    • Default HTTP timeout is 30 seconds. Adjust for long-running calls:
      $client = new \Twilio\Rest\Client($sid, $token);
      $client->setHttpClient(new \GuzzleHttp\Client(['timeout' => 60]));
      

Debugging Tips

  1. Inspect Requests/Responses:

    $client->lastRequest->getUrl(); // Full URL
    $client->lastResponse->getStatusCode(); // HTTP status
    
  2. Enable Verbose Logging:

    Twilio::setLogLevel('debug');
    // Or via .env: TWILIO_LOG_LEVEL=debug
    
  3. Common HTTP Issues:

    • CURL Errors: Ensure php-curl is enabled (php -m | grep curl).
    • SSL Certificates: Update CA bundle if using self-signed certs:
      $client->setHttpClient(new \GuzzleHttp\Client([
          'curl' => [CURLOPT_CAINFO => '/path/to/cert.pem']
      ]));
      

Extension Points

  1. Custom HTTP Client: Replace the default client (e.g., for testing or custom headers):

    $client = new \Twilio\Rest\Client($sid, $token);
    $client->setHttpClient(new \GuzzleHttp\Client([
        'headers' => ['User-Agent' => 'MyApp/1.0']
    ]));
    
  2. Event Listeners: Extend Twilio events (e.g., log all incoming calls):

    // app/Listeners/TwilioCallListener.php
    public function handle(IncomingCall $event) {
        Log::info('Incoming call from: ' . $event->from);
    }
    
  3. Region/Edge Overrides: Dynamically set region for global infrastructure:

    $client = new \Twilio\Rest\Client($sid, $token, null, 'eu1');
    $client->setEdge('frankfurt');
    
  4. Mocking for Tests: Use Laravel's MockHttpClient:

    $client = new \Twilio\Rest\Client('AC123', 'token');
    $client->setHttpClient(new \Mockery\MockInterface());
    $client->shouldReceive('request')->andReturn(new \stdClass());
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle