You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

1. Setting Up Laravel to Receive Incoming SMS (Webhook Configuration)

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');
    }
}
  1. Log into your Twilio Console and navigate to your phone number
  2. Under the Messaging section, find A Message Comes In
  3. Select HTTP POST and paste your webhook URL (e.g., https://your-production-domain.com/api/twilio/incoming-sms)
  4. 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)
2. Adding SMS Delivery Receipts

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')),
];
Key Notes
  • 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 RequestValidator to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:12:03