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.
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'),
],
Service Provider:
Register in config/app.php:
'providers' => [
// ...
Twilio\Laravel\TwilioServiceProvider::class,
],
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]);
}
Twilio Client Initialization:
// Via Facade (Laravel)
Twilio::setAccountSid(env('TWILIO_SID'));
Twilio::setAuthToken(env('TWILIO_TOKEN'));
// Or via Service Container
$client = app('twilio');
Common API Calls:
$message = Twilio::message('+15558675309', 'Hello!');
$message->send();
$call = Twilio::call('+15558675309', '+15017250604');
$call->url('https://example.com/twiml')->make();
$response = new \Twilio\TwiML\VoiceResponse();
$response->say('Welcome!');
return response($response)->header('Content-Type', 'text/xml');
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
}
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]);
}
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());
Authentication Errors:
20003 or 21211 errors.TWILIO_SID/TWILIO_TOKEN in .env and ensure no typos. Use setLogLevel('debug') to inspect requests:
Twilio::setLogLevel('debug');
Rate Limiting:
429 responses gracefully:
try {
$message->send();
} catch (\Twilio\Exceptions\TwilioException $e) {
if ($e->getCode() === 429) {
sleep(1); // Retry after delay
$message->send();
}
}
TwiML Validation:
TwimlException. Validate XML structure:
try {
$response = new \Twilio\TwiML\VoiceResponse();
$response->invalidTag(); // Throws exception
} catch (\Twilio\Exceptions\TwimlException $e) {
Log::error($e->getMessage());
}
Timeouts:
$client = new \Twilio\Rest\Client($sid, $token);
$client->setHttpClient(new \GuzzleHttp\Client(['timeout' => 60]));
Inspect Requests/Responses:
$client->lastRequest->getUrl(); // Full URL
$client->lastResponse->getStatusCode(); // HTTP status
Enable Verbose Logging:
Twilio::setLogLevel('debug');
// Or via .env: TWILIO_LOG_LEVEL=debug
Common HTTP Issues:
php-curl is enabled (php -m | grep curl).$client->setHttpClient(new \GuzzleHttp\Client([
'curl' => [CURLOPT_CAINFO => '/path/to/cert.pem']
]));
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']
]));
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);
}
Region/Edge Overrides: Dynamically set region for global infrastructure:
$client = new \Twilio\Rest\Client($sid, $token, null, 'eu1');
$client->setEdge('frankfurt');
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());
How can I help you explore Laravel packages today?