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

如何配置Twilio Webhook实现用户短信回复在Django后台展示?

解决Twilio Webhook无法访问Django认证接口的问题

核心问题分析

你的Django接收短信的Webhook接口受管理员认证拦截,导致Twilio推送的用户回复请求无法进入应用,自然没法同步到消息面板。下面是两种直接可行的解决方式:


方案1:给接收短信的视图跳过认证

Twilio的请求是服务器端发起的,不需要用户登录态,所以可以给处理短信接收的视图单独跳过认证和CSRF校验:

函数视图写法

from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse

@csrf_exempt
@require_POST
def receive_sms(request):
    # 提取Twilio推送的短信核心字段
    sender_number = request.POST.get('From')
    message_content = request.POST.get('Body')
    message_time = request.POST.get('DateCreated')
    
    # 把数据存入你消息面板对应的数据库模型
    # 示例:Message.objects.create(sender=sender_number, content=message_content, created_at=message_time)
    
    # 必须返回Twilio要求的TwiML格式响应,空响应也可以
    return HttpResponse('<Response></Response>', content_type='application/xml')

类视图(如APIView)写法

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

@method_decorator(csrf_exempt, name='dispatch')
class ReceiveSMSView(APIView):
    permission_classes = [AllowAny]  # 跳过登录认证

    def post(self, request):
        sender_number = request.data.get('From')
        message_content = request.data.get('Body')
        
        # 存入消息面板数据库逻辑
        # ...
        
        return Response('<Response></Response>', content_type='application/xml')

方案2:验证Twilio请求合法性(可选但推荐)

为了避免恶意请求,即使跳过认证,也可以验证请求确实来自Twilio:

  1. 先安装Twilio官方库:pip install twilio
  2. 在视图中添加签名验证:
from twilio.request_validator import RequestValidator
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse

@csrf_exempt
@require_POST
def receive_sms(request):
    validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
    twilio_signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')
    # 这里的URL要和你在Twilio控制台配置的完全一致(包括http/https、路径)
    full_webhook_url = f"{settings.YOUR_DOMAIN}{request.path}"
    
    # 验证失败直接返回403
    if not validator.validate(full_webhook_url, request.POST, twilio_signature):
        return HttpResponse('非法请求', status=403)
    
    # 后续的短信存储逻辑...
    return HttpResponse('<Response></Response>', content_type='application/xml')

Twilio控制台配置步骤

  1. 登录Twilio控制台,进入你的短信专用号码页面
  2. 找到「Messaging」板块下的「A Message Comes In」选项
  3. 选择「Webhook」,填入你部署后的接收短信公网URL(比如https://你的域名.com/receive-sms/)
  4. 请求方法选择POST,点击保存即可

消息面板同步逻辑

只要你在接收短信的视图里,把Twilio推送的From(用户手机号)、Body(短信内容)、DateCreated(时间)存入对应数据库表,你的消息面板视图直接从该表读取数据展示即可。

内容的提问来源于stack exchange,提问作者wchesh24

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:15:48