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' => [
'sid' => env('TWILIO_SID'),
'token' => env('TWILIO_AUTH_TOKEN'),
'from' => env('TWILIO_FROM_NUMBER'),
],
Service Provider & Facade (Laravel):
// config/app.php
'providers' => [
Twilio\Laravel\TwilioServiceProvider::class,
],
'aliases' => [
'Twilio' => Twilio\Laravel\Facades\Twilio::class,
],
First Use Case: Send an SMS via a Laravel controller:
use Twilio\Laravel\Facades\Twilio;
public function sendSms()
{
Twilio::message()
->to('+15558675309')
->body('Hello from Laravel!')
->send();
}
SMS & MMS:
// Send SMS
Twilio::message()
->to('+15558675309')
->from(config('services.twilio.from'))
->body('Your OTP: 123456')
->send();
// Send MMS
Twilio::message()
->to('+15558675309')
->from(config('services.twilio.from'))
->body('Check this out!')
->media('https://example.com/image.jpg')
->send();
Voice Calls:
// Initiate a call
Twilio::call()
->to('+15558675309')
->from(config('services.twilio.from'))
->url('https://example.com/twiml')
->send();
// TwiML for call handling (e.g., `routes/twilio.php`)
$response = new \Twilio\TwiML\VoiceResponse();
$response->say('Welcome to our service!');
$response->gather(['action' => '/handle-input']);
return $response;
Webhooks:
Validate and handle incoming Twilio webhooks (e.g., app/Http/Controllers/TwilioWebhookController.php):
public function handleIncomingSms(Request $request)
{
$message = $request->input('MessageSid');
$from = $request->input('From');
$body = $request->input('Body');
// Process logic (e.g., reply, log, etc.)
Twilio::message()
->to($from)
->from(config('services.twilio.from'))
->body("You said: {$body}")
->send();
}
Batch Operations:
// Fetch all messages (paginated)
$messages = Twilio::messages()->read(['dateSentAfter' => '2023-01-01'], 50);
// Stream messages (lazy loading)
$stream = Twilio::messages()->stream(['status' => 'queued'], 100, 20);
foreach ($stream as $message) {
// Process each message
}
Regions & Edge:
// Initialize client with region/edge (e.g., for low-latency)
$client = new \Twilio\Rest\Client(
config('services.twilio.sid'),
config('services.twilio.token'),
null,
'eu1' // Region
);
$client->setEdge('frankfurt'); // Edge
Laravel Events:
Trigger Twilio actions on Laravel events (e.g., registered):
// app/Providers/EventServiceProvider.php
public function boot()
{
Registered::listen(function ($user) {
Twilio::message()
->to($user->phone)
->body('Welcome! Your account is ready.')
->send();
});
}
Queued Jobs: Offload Twilio tasks to Laravel queues:
// app/Jobs/SendWelcomeSms.php
public function handle()
{
Twilio::message()
->to($this->phone)
->body('Welcome!')
->send();
}
Testing:
Use Mockery or Twilio\Testing\MockClient for unit tests:
$mockClient = new \Twilio\Testing\MockClient();
$mockClient->expectsMessages()->create('+15558675309', [
'from' => '+15017250604',
'body' => 'Test',
]);
Middleware: Validate Twilio webhook signatures:
// app/Http/Middleware/ValidateTwilioSignature.php
public function handle($request, Closure $next)
{
$request->validateTwilioSignature();
return $next($request);
}
Credentials Exposure:
TWILIO_SID/TWILIO_AUTH_TOKEN in production..env and config/services.php:
TWILIO_SID=your_sid
TWILIO_AUTH_TOKEN=your_token
TWILIO_FROM_NUMBER=+15017250604
Rate Limiting:
Twilio\Exceptions\TwilioException for 429 Too Many Requests:
try {
Twilio::message()->send();
} catch (\Twilio\Exceptions\TwilioException $e) {
if ($e->getCode() === 429) {
sleep(1); // Retry after delay
retry();
}
}
Timeouts:
$client = new \Twilio\Rest\Client($sid, $token);
$client->setHttpClient(new \GuzzleHttp\Client([
'timeout' => 60, // 60 seconds
]));
TwiML Validation:
Twilio\Exceptions\TwimlException. Validate dynamically:
$response = new \Twilio\TwiML\VoiceResponse();
$response->say('Hello');
// Throws if malformed:
$response->invalidMethod(); // Exception!
Phone Number Formatting:
+15551234567). Twilio rejects malformed numbers.Enable Debug Logging:
$client->setLogLevel('debug');
// Or via env:
TWILIO_LOG_LEVEL=debug
Inspect Requests/Responses:
$client->messages->create(...);
print $client->lastRequest->url; // Debug URL
print $client->lastResponse->statusCode; // Debug status
Common Errors:
21211: Invalid From number (not Twilio-owned).21610: Invalid phone number format.20404: Authentication failed (check credentials).Custom HTTP Client:
Replace the default CurlClient with Guzzle or Psr-7 clients:
use Twilio\Http\GuzzleHttpClient;
$client = new \Twilio\Rest\Client($sid, $token, new GuzzleHttpClient());
Extend Twilio Facade (Laravel):
// app/Extensions/TwilioExtension.php
namespace App\Extensions;
use Twilio\Laravel\Facades\Twilio as BaseTwilio;
class TwilioExtension extends BaseTwilio
{
public function sendTransactional($to, $templateId, $data = [])
{
return $this->messages()->create($to, [
'from' => config('services.twilio.from'),
'body' => $this->renderTemplate($templateId, $data),
]);
}
}
Webhook Validation: Add custom validation to incoming requests:
// app/Http/Middleware/ValidateTwilioSignature.php
public function handle($request, Closure $next)
{
$request->validate([
'From'
How can I help you explore Laravel packages today?