twilio/sdk
Official Twilio PHP SDK for interacting with Twilio APIs. Send SMS/WhatsApp, place calls, manage messaging, Verify, and other Twilio services from PHP apps. Composer-ready, supports PHP 7.2–8.4, with docs and examples.
Installation:
composer require twilio/sdk
Add to config/services.php (Laravel convention):
'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]);
}
Service Facade Integration:
Use Laravel's service container to inject Twilio\Laravel\Facades\Twilio:
public function __construct(Twilio $twilio) {
$this->twilio = $twilio;
}
Event-Driven Patterns: Handle Twilio webhooks via Laravel routes:
Route::post('/twilio-webhook', [TwilioWebhookController::class, 'handle']);
Use Twilio\Laravel\TwilioWebhookRequest to validate and parse payloads:
$request = new TwilioWebhookRequest();
$request->handle($this->request);
Batch Processing: Stream large datasets (e.g., call logs) with pagination:
$calls = Twilio::calls()->stream(['status' => 'completed'], 100, 20);
foreach ($calls as $call) {
// Process each call
}
TwiML Generation: Dynamically generate TwiML responses in routes:
return response(Twilio::response()->say('Welcome!')->generate(), 200)
->header('Content-Type', 'text/xml');
.env (never hardcode).public function handle($request, Closure $next) {
$request->validateTwilioSignature();
return $next($request);
}
SendSmsJob::dispatch('+15558675309', 'Your message');
Rate Limiting: Twilio enforces rate limits. Use exponential backoff in retries:
try {
$message->send();
} catch (TwilioException $e) {
if ($e->getCode() === 429) {
sleep(2); // Retry after delay
}
}
Timeouts: Default HTTP client timeout is 30s. Adjust for long operations:
$client = new Twilio\Rest\Client($sid, $token);
$client->setHttpClient(new CurlClient(['timeout' => 60]));
TwiML Validation:
Invalid TwiML throws TwimlException. Validate dynamically:
try {
$response = Twilio::response()->dial()->conference('room123');
$response->validate(); // Explicit check
} catch (TwimlException $e) {
Log::error($e->getMessage());
}
Log Requests: Enable debug logging via config:
'twilio' => [
'log_level' => 'debug',
],
Or programmatically:
Twilio::setLogLevel('debug');
Inspect Responses: Access raw HTTP data:
$lastResponse = Twilio::getLastResponse();
Log::debug($lastResponse->getBody());
Custom HTTP Clients: Replace the default client for advanced use cases (e.g., Guzzle):
$client = new Twilio\Rest\Client($sid, $token, new GuzzleHttpClient());
Middleware Hooks: Extend Twilio requests/responses via Laravel middleware:
public function handle($request, Closure $next) {
$request->setHeader('X-Custom-Header', 'value');
return $next($request);
}
Event Listeners: Subscribe to Twilio events (e.g., message status changes):
event(new MessageStatusChanged($message));
Service Binding:
Ensure the TwilioServiceProvider is registered before use. If not, bind manually:
$this->app->bind('twilio', function ($app) {
return new Twilio\Rest\Client(
$app['config']['services.twilio.account_sid'],
$app['config']['services.twilio.auth_token'],
null,
$app['config']['services.twilio.region']
);
});
Testing: Use mocks for unit tests:
$mockClient = Mockery::mock(Twilio\Rest\Client::class);
$this->app->instance(Twilio\Rest\Client::class, $mockClient);
How can I help you explore Laravel packages today?