Laravel集成Twilio接收短信:Webhook配置及相关问题咨询
Hey there! Let's break down how to handle incoming SMS and delivery receipts in Laravel with the aloha/laravel-twilio package—this is totally manageable once you map Twilio's webhooks to Laravel's structure.
Twilio sends incoming SMS data to a webhook URL you specify, so we'll set up a Laravel route, controller, and link it to your Twilio account.
Step 1: Create a Webhook Route
First, add a route in routes/api.php (we use the API route group to avoid CSRF issues by default, but you can use web.php if you exempt the route from CSRF checks):
use App\Http\Controllers\TwilioWebhookController; Route::post('/twilio/incoming-sms', [TwilioWebhookController::class, 'handleIncomingSms']);
If you use web.php, add the route to the $except array in app/Http/Middleware/VerifyCsrfToken.php:
protected $except = [ '/twilio/incoming-sms', ];
Step 2: Build the Webhook Controller
Generate a controller to handle the incoming request:
php artisan make:controller TwilioWebhookController
Then add the handleIncomingSms method to parse Twilio's data, process it, and optionally send an auto-reply:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Twilio\TwiML\MessagingResponse; use Twilio\Security\RequestValidator; use App\Models\Message; // Assume you have a Message model to store SMS class TwilioWebhookController extends Controller { public function handleIncomingSms(Request $request) { // Validate the request is actually from Twilio (critical for security) $validator = new RequestValidator(config('twilio.auth_token')); $signature = $request->header('X-Twilio-Signature'); $validUrl = url($request->path()); if (!$validator->validate($signature, $validUrl, $request->all())) { abort(403, 'Invalid Twilio request'); } // Extract incoming SMS details $fromNumber = $request->input('From'); $messageBody = $request->input('Body'); $twilioSid = $request->input('MessageSid'); // Save the message to your database (example) Message::create([ 'twilio_sid' => $twilioSid, 'from' => $fromNumber, 'body' => $messageBody, 'direction' => 'incoming', 'status' => 'received' ]); // Optional: Send an auto-reply using TwiML $response = new MessagingResponse(); $response->message("Thanks for reaching out! We'll respond shortly."); return response($response)->header('Content-Type', 'application/xml'); } }
Step 3: Link Twilio to Your Laravel Webhook
- Log into your Twilio Console and navigate to your phone number
- Under the Messaging section, find A Message Comes In
- Select HTTP POST and paste your webhook URL (e.g.,
https://your-production-domain.com/api/twilio/incoming-sms) - For local development, use a tool like ngrok to expose your Laravel app: run
ngrok http 8000, then use the HTTPS URL ngrok provides (e.g.,https://abc123.ngrok.io/api/twilio/incoming-sms)
Twilio can send status updates (like "sent", "delivered", "failed") to another webhook. Here's how to set this up:
Step 1: Add a Status Callback Route
Add another route in routes/api.php:
Route::post('/twilio/sms-status', [TwilioWebhookController::class, 'handleSmsStatus']);
Step 2: Add the Status Handler Method
Update your TwilioWebhookController with a method to process status updates:
public function handleSmsStatus(Request $request) { // Validate Twilio request (same as before) $validator = new RequestValidator(config('twilio.auth_token')); $signature = $request->header('X-Twilio-Signature'); $validUrl = url($request->path()); if (!$validator->validate($signature, $validUrl, $request->all())) { abort(403, 'Invalid Twilio request'); } // Extract status details $twilioSid = $request->input('MessageSid'); $status = $request->input('MessageStatus'); // Possible values: queued, sent, delivered, failed, etc. // Update your message record with the new status Message::where('twilio_sid', $twilioSid)->update(['status' => $status]); // Twilio just needs a 200 response—no TwiML required return response()->json(['status' => 'processed'], 200); }
Step 3: Attach the Status Callback When Sending SMS
When using the aloha/laravel-twilio package to send SMS, include the statusCallback parameter to point to your new route:
use Aloha\Twilio\Facades\Twilio; // Send SMS with status tracking Twilio::message($recipientNumber, $messageContent, [ 'statusCallback' => url('/api/twilio/sms-status') ]);
If you want this to apply globally to all SMS, you can add a default statusCallback to your config/twilio.php file:
return [ // ... other configs 'status_callback' => env('TWILIO_STATUS_CALLBACK', url('/api/twilio/sms-status')), ];
- HTTPS Requirement: Twilio requires HTTPS for webhooks in production (ngrok works for local testing since it provides HTTPS)
- Request Validation: Always validate Twilio requests using the
RequestValidatorto prevent spoofing - TwiML Responses: For incoming SMS, return TwiML if you want to send an auto-reply; status callbacks only need a 200 OK
内容的提问来源于stack exchange,提问作者Zach Handley

