Download the PHP package citricguy/twilio-laravel without Composer
On this page you can find all versions of the php package citricguy/twilio-laravel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download citricguy/twilio-laravel
More information about citricguy/twilio-laravel
Files in citricguy/twilio-laravel
Package twilio-laravel
Short Description A Laravel package to integrate Twilio for SMS/MMS messaging, notifications, and webhooks. This package leverages the official Twilio PHP SDK and adheres to Laravel conventions, providing a seamless, queued, and event-driven solution for sending messages and processing incoming Twilio callbacks. Ideal for modern Laravel projects needing robust Twilio integration.
License MIT
Homepage https://github.com/citricguy/twilio-laravel
Informations about the package twilio-laravel
Twilio for Laravel (Unofficial)
A Laravel package to integrate Twilio for SMS/MMS messaging, voice calls, notifications, and webhooks. This package leverages the official Twilio PHP SDK and adheres to Laravel conventions, providing a seamless, queued, and event-driven solution for sending messages, making calls, and processing incoming Twilio callbacks.
📋 Table of Contents
- Twilio for Laravel (Unofficial)
- 📋 Table of Contents
- Installation
- Configuration
- Sender Configuration
- Debug Mode
- Notification Channel Configuration
- Usage
- Sending SMS Messages
- Message Queuing
- Making Voice Calls
- Working with Webhooks
- Webhook Types
- Webhook Helper Methods
- Handling Different Webhook Types
- How Responses Work
- Events
- Message Events
- TwilioMessageSending Example
- TwilioMessageQueued Example
- TwilioMessageSent Example
- Call Events
- TwilioCallSending Example
- TwilioWebhookReceived Example
- Integration Guide
- Setting Up Event Listeners
- Handling Immediate Responses
- Background Processing
- Option 1: Queue the whole listener
- Option 2: Queue specific processing tasks
- Integration Patterns
- Multiple Specialized Listeners
- Service-Based Approach
- Setting Up Twilio Webhooks
- Step 1: Create a Webhook Endpoint
- Step 2: Make Your Endpoint Accessible
- Step 3: Configure Twilio to Send Webhooks
- Step 4: Test Your Webhook
- Webhook Security
- Webhook Validation Explained
- Testing
- Faking the Twilio Facade
- Testing Voice Calls
- Testing Your Webhook Handlers
- Option 1: Dispatching the Event Directly
- Option 2: Testing the HTTP Endpoint
- Option 3: Integration Testing with Response Expectations
- Using the Notification Channel
- Configuring Your Notifiable Model
- Creating a Notification
- Sending SMS Notifications
- Sending MMS Notifications
- Additional Options
- Simple String Responses
- Event Tracking
- Using the Call Notification Channel
- Configuring Your Notifiable Model
- Creating a Call Notification
- Sending Call Notifications
- Additional Call Options
- Simple String URL Responses
- Security
- Credits
- License
Upgrading to 3.0.0: see the validation report.
Installation
Once 3.0.0 is released:
You can install the package via composer:
Requirements / Support
- PHP:
^8.4(tested on PHP 8.4 and 8.5), with curl and mbstring. - Laravel:
^13.23. The full framework is required because jobs/events use Foundation traits. - Twilio SDK:
^8.12.1. - Development: Pest 5, Orchestra Testbench 11, Larastan/PHPStan level 9, and Pint.
composer.lock is not tracked in this package repository, so downstream installs resolve fresh dependency versions from the published Composer constraints.
Configuration
Publish the configuration file:
This will create a config/twilio-laravel.php file in your app where you can modify the configuration settings.
Add the following environment variables to your .env file:
If you are upgrading from an older install, TWILIO_VALIDATE_WEBHOOK_SIGNATURE is still honored for backward compatibility. TWILIO_VALIDATE_WEBHOOK is the canonical key going forward.
Sender Configuration
When sending messages, the package determines the sender using the following priority order:
- The
fromparameter in the options array passed to thesendMessagemethod - The
messagingServiceSidparameter in that options array - The messaging service SID from your config (set via
TWILIO_MESSAGING_SERVICE_SIDin.env) - The default sender number from your config (set via
TWILIO_FROMin.env)
If none of these are provided, an exception will be thrown indicating that no valid sender is configured.
Example usage with different sender options:
Debug Mode
Package logs use fixed messages and safe counts/booleans. They do not dump webhook payloads, request headers, URLs, signatures, credentials, phone numbers, provider identifiers, outbound options, cancellation reasons or exception messages. Debugging includes successful verification, webhook field counts, outbound option counts, cancellation presence and error categories/codes.
Events and cancellation results retain their application data, and SDK exceptions are still rethrown. Review application listeners, exception reporting, queue storage and independent SDK diagnostics separately. Do not replace removed log fields with payload dumps in application code.
The TWILIO_DEBUG environment variable can be used to enable or disable debug mode. When debug mode is enabled (TWILIO_DEBUG=true), additional logging and debugging information will be available to help troubleshoot issues. It is recommended to keep debug mode disabled (TWILIO_DEBUG=false) in production environments.
Notification Channel Configuration
The package registers two notification channels:
twilioSms- For sending SMS/MMS notificationstwilioCall- For initiating voice calls
You can customize the channel names in the configuration:
Usage
Sending SMS Messages
You can send SMS messages using the Twilio facade:
Message Queuing
By default, all messages are queued for sending. This behavior can be configured in config/twilio-laravel.php:
Making Voice Calls
You can initiate voice calls using the Twilio facade:
Voice calls require a URL that returns TwiML instructions. The TwiML document controls what happens during the call (playing messages, gathering input, etc.). Your application is responsible for creating and serving these TwiML documents.
Working with Webhooks
A key feature of this package is its ability to receive and handle webhooks from Twilio. Webhooks enable your application to respond to events like message deliveries, incoming texts, voice calls, and more.
Webhook Types
Voice requests with CallbackSource=call-progress-events are status callbacks even when CallStatus is ringing or in-progress. Without that marker, the existing status-based inbound classification remains.
The package automatically detects different types of Twilio webhooks and categorizes them to make handling easier:
| Type | Constant | Description | Example |
|---|---|---|---|
| Voice Inbound | TYPE_VOICE_INBOUND |
Incoming voice call | Someone calls your Twilio number |
| Voice Status | TYPE_VOICE_STATUS |
Voice call status update | A call ends or changes status |
| Message Inbound SMS | TYPE_MESSAGE_INBOUND_SMS |
Incoming SMS message | Someone texts your Twilio number |
| Message Inbound MMS | TYPE_MESSAGE_INBOUND_MMS |
Incoming MMS message | Someone sends media to your Twilio number |
| Message Status | TYPE_MESSAGE_STATUS_PREFIX + status |
Message status update | Your sent message is delivered or fails |
| Generic Message | TYPE_MESSAGE_GENERIC |
Other message webhook | Fallback for other message events |
Webhook Helper Methods
The TwilioWebhookReceived event provides helper methods to easily identify webhook types:
Handling Different Webhook Types
You can listen for webhook events in your EventServiceProvider:
Then create a listener to handle the different webhook types:
How Responses Work
The package is designed to handle both immediate responses and background processing:
- When a webhook arrives, the controller dispatches the
TwilioWebhookReceivedevent - Your listener processes the event and can optionally return a Symfony-compatible Response object (including Laravel Response and JsonResponse)
- The first such listener response is returned to Twilio unchanged; later response values are ignored
- If no Response is returned, the controller sends a default
202 AcceptedJSON response
This approach allows you to:
- Return TwiML responses for voice calls (which require immediate responses)
- Simply process other webhooks without worrying about responses
- Optionally queue time-consuming processing for any webhook type
Events
Immediate sends fire the sending event once. Queued sends fire it before enqueue and once per worker attempt. Cancellation is checked at each of those boundaries; retries can invoke listeners again. Make listener side effects safe for retries. Queue jobs delegate the worker check to the service.
The existing segmentsCount field prefers a positive SDK count after sending. When Twilio reports zero or no count (including initially queued Messaging Service messages), it falls back to the prior rough ceil(mb_strlen(body) / 153) estimate. Queued and fake events also use that estimate. It is not encoding-aware and must not be treated as a final billing count.
This package provides several events you can listen for in your application:
Message Events
| Event | Description | Properties |
|---|---|---|
TwilioMessageSending |
Fired before a message is sent - can be cancelled | to, message, options |
TwilioMessageQueued |
Fired when a message is queued for sending | to, message, status, segmentsCount, options |
TwilioMessageSent |
Fired when a message is sent successfully | messageSid, to, message, status, segmentsCount, options |
You can listen for these events in your EventServiceProvider:
TwilioMessageSending Example
The TwilioMessageSending event allows you to implement validation logic before a message is sent. You can cancel the message if it doesn't meet your criteria:
When a message is cancelled:
- The
sendMessageorsendMessageNowmethod returns an array with:status=> 'cancelled'to=> the recipient numberreason=> the optional cancellation reason provided
TwilioMessageQueued Example
The TwilioMessageQueued event is fired when a message is successfully queued for later sending:
TwilioMessageSent Example
The TwilioMessageSent event is fired when a message is actually sent to Twilio's API:
Call Events
| Event | Description | Properties |
|---|---|---|
TwilioCallSending |
Fired before a call is initiated - can be cancelled | to, url, options |
TwilioCallQueued |
Fired when a call is queued | to, url, status, options |
TwilioCallSent |
Fired when a call is successfully initiated | callSid, to, url, status, options |
You can listen for these events in your EventServiceProvider:
TwilioCallSending Example
Similar to message sending, the TwilioCallSending event allows you to implement validation logic before a call is initiated:
When a call is cancelled:
- The
makeCallormakeCallNowmethod returns an array with:status=> 'cancelled'to=> the recipient numberreason=> the optional cancellation reason provided
TwilioWebhookReceived Example
The TwilioWebhookReceived event is fired when a webhook is received from Twilio:
Integration Guide
This section provides practical examples of how to integrate this package into your Laravel application.
Setting Up Event Listeners
Register your listener in your EventServiceProvider:
Handling Immediate Responses
For webhooks that require immediate responses (like voice calls):
The key points:
- DO NOT make your listener implement
ShouldQueueif you need immediate responses - Return a Response object with TwiML content for voice calls
- Set the Content-Type header to 'text/xml' for TwiML responses
Background Processing
For webhooks that can be processed in the background:
Option 1: Queue the whole listener
Register this alongside your immediate response listener:
Option 2: Queue specific processing tasks
Integration Patterns
For larger applications, consider these patterns:
Multiple Specialized Listeners
Service-Based Approach
Setting Up Twilio Webhooks
Step 1: Create a Webhook Endpoint
This package automatically creates a webhook endpoint at /api/twilio/webhook (or the path you've configured in your .env file).
Step 2: Make Your Endpoint Accessible
During development, you can use tools like Ngrok to expose your local server to the internet:
This will give you a public URL that you can use to receive webhooks.
Step 3: Configure Twilio to Send Webhooks
- Log into your Twilio Console
- Navigate to Phone Numbers > Manage > Active Numbers
- Click on the phone number you want to configure
-
Configure the webhook URLs:
For SMS/MMS:
- Scroll to the "Messaging" section
-
Under "A MESSAGE COMES IN", set the webhook URL to:
(or your custom webhook path)
- Set the HTTP method to POST
For Voice:
- Scroll to the "Voice & Fax" section
-
Under "A CALL COMES IN", set the webhook URL to:
- Set the HTTP method to POST
- Save your changes
Step 4: Test Your Webhook
In a controlled staging test, trigger a Twilio webhook and verify your event listener processed it. With TWILIO_DEBUG=true, safe verification and webhook diagnostics are logged; successful requests are quiet by default. Return debugging to false afterward.
Webhook Security
By default, the package validates all incoming webhook requests from Twilio using their signature validation mechanism. This ensures that webhooks are genuinely from Twilio.
You can disable this in development by setting:
This is not recommended for production.
If you are upgrading from the last tagged release and already use TWILIO_VALIDATE_WEBHOOK_SIGNATURE, that older env key is still supported.
Webhook Validation Explained
The middleware verifies original form values even when Laravel has trimmed request input. The original query-string order and encoding are preserved. Requests containing bodySHA256 are validated against the raw body using the SDK; missing/invalid signatures return 403 and a missing auth token returns 500. Existing parameter-signed requests remain supported.
Configure Laravel's trusted proxies for your infrastructure so the scheme, host, port and forwarded prefix reproduce the public URL configured in Twilio. Do not trust arbitrary forwarded headers from the internet. The built-in route remains POST-only; applications may apply the middleware to their own GET routes if needed.
A boolean twilio-laravel.validate_webhook takes precedence over validate_webhook_signature; if neither is boolean, validation defaults to enabled. Both environment-variable aliases remain supported. The command php artisan twilio:verify-webhook-setup displays configuration guidance, not proof of a successful live signature check.
When Twilio sends a webhook, it includes an X-Twilio-Signature header that's generated based on:
- Your Twilio auth token
- The full URL of your webhook endpoint
- The request parameters
The package verifies this signature to ensure the request is legitimate.
Testing
Faking the Twilio Facade
The fake respects queue_messages. All six sending/queueing methods run their cancellation listener once; a cancelled result is an array with status, to and reason, and is not recorded. Fake successful results remain arrays and support the existing assertions. The fake does not emulate a real SDK response object or run a queue worker; use a recording SDK HTTP transport for integration tests.
During testing, you'll typically want to avoid making actual API calls to Twilio. The package provides a way to fake the Twilio facade:
This allows you to test code that uses the Twilio facade without actually sending messages or making API calls.
Testing Voice Calls
During testing, you can use the fake Twilio implementation to verify calls:
This allows you to test code that initiates calls without actually making API calls to Twilio.
Testing Your Webhook Handlers
You can test your webhook handlers in several ways:
Option 1: Dispatching the Event Directly
Option 2: Testing the HTTP Endpoint
Option 3: Integration Testing with Response Expectations
Using the Notification Channel
This package includes a Laravel Notification Channel for sending SMS and MMS through Twilio. This follows Laravel's notification system patterns and allows for easy integration with your existing notification architecture.
Configuring Your Notifiable Model
Ensure your model includes a method to determine the phone number to receive SMS:
Laravel's generic routeNotificationFor('twilioSms', $notification) path is also supported.
Creating a Notification
Create a notification with a toTwilioSms method:
Sending SMS Notifications
You can send notifications using Laravel's built-in notification system:
Sending MMS Notifications
You can include media in your notifications by using the mediaUrls method:
Additional Options
Options are a mix of the explicitly supported Twilio settings and application metadata; this is not an arbitrary SDK option passthrough. SMS supports from, messagingServiceSid, mediaUrls, statusCallback (and legacy metadata.statusCallback). Queue controls are queue and delay. Other values remain available to event listeners.
The TwilioSmsMessage class provides a fluent interface for setting various options:
Use TWILIO_MESSAGING_SERVICE_SID in your config / .env when you want to send through a messaging service. The current service layer uses the configured messaging service SID, not a per-message override.
Simple String Responses
For simple notifications, you can return a string directly:
Event Tracking
When sending SMS through the notification channel, the package automatically adds notification metadata to the event options, allowing you to identify messages sent through the notification system in your event listeners:
Using the Call Notification Channel
This package includes a Laravel Notification Channel for initiating voice calls through Twilio.
Configuring Your Notifiable Model
Ensure your model includes a method to determine the phone number to receive calls:
Laravel's generic routeNotificationFor('twilioCall', $notification) path is also supported.
Creating a Call Notification
Create a notification with a toTwilioCall method:
Sending Call Notifications
You can send notifications using Laravel's built-in notification system:
Additional Call Options
Calls support from, statusCallback, statusCallbackEvent, record, and timeout, plus queue and delay. Additional application metadata is kept in events and is not sent indiscriminately to Twilio.
The TwilioCallMessage class provides a fluent interface for setting various options:
Simple String URL Responses
For simple notifications, you can return a string URL directly:
Contributing and checks
Coverage requires Xdebug or PCOV and a minimum of 95% source line coverage. CI runs PHP 8.4/8.5 plus lowest-compatible dependencies, dependency audits/review, workflow validation, and safe offline SDK tests. Dependabot checks Composer and Actions weekly. The library lockfile is intentionally ignored; application lockfiles should be committed in consuming projects.
For the supplied application manifest, run php8.5 tools/check-consumer.php; see the fixture instructions. That solver check does not replace tests against actual application code. On PHP 8.5, bash tools/smoke-consumer.sh creates a temporary Laravel app, installs the local candidate with Symfony 8.1, tests package discovery/cached boot/notifications/serialized jobs/webhooks using a recording transport, and removes the temporary app. It is also run in CI.
Security
If you discover any security-related issues, please email [email protected] instead of using the issue tracker.
Credits
- Josh Sommers
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
All versions of twilio-laravel with dependencies
ext-curl Version *
ext-mbstring Version *
laravel/framework Version ^13.23
twilio/sdk Version ^8.12.1