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

如何在Python Django应用中获取LINE Messaging API的Webhook数据?

在Django应用中接收LINE Messaging API的Webhook JSON数据

1. 配置URL路由

在Django项目的urls.py中添加路由,指向处理Webhook请求的视图:

from django.urls import path
from . import views

urlpatterns = [
    # 其他路由...
    path('line-webhook/', views.line_webhook_handler, name='line-webhook'),
]

2. 编写Webhook处理视图

创建视图函数接收POST请求并解析JSON数据,注意豁免CSRF验证(外部服务无法提供Django的CSRF令牌):

from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json

@csrf_exempt
def line_webhook_handler(request):
    # 仅处理POST请求
    if request.method != 'POST':
        return HttpResponse(status=405)
    
    # 解析JSON数据
    try:
        # Django 3.1+ 可直接使用 request.json
        webhook_data = request.json
        # 低版本Django请使用以下方式:
        # webhook_data = json.loads(request.body)
        
        # 此处添加业务逻辑,比如存储数据、触发内部事件等
        print("Received Webhook Data:", webhook_data)
        
        # 返回200状态码告知LINE请求已接收(必须返回,否则LINE会重试)
        return JsonResponse({'status': 'success'}, status=200)
    except Exception as e:
        print("Webhook处理错误:", str(e))
        return JsonResponse({'status': 'error'}, status=400)

3. 本地开发暴露公网(测试用)

LINE需要访问公网可访问的URL,本地开发时可使用工具(如ngrok)将本地服务暴露到公网:

ngrok http 8000

将生成的公网URL(如https://xxx.ngrok.io/line-webhook/)配置为MessageBird的Webhook地址。

4. 可选:验证Webhook签名(安全性建议)

为确保请求来自LINE,建议验证请求签名。先在settings.py中添加LINE通道密钥:

LINE_CHANNEL_SECRET = "你的LINE通道密钥"

然后在视图中添加验证逻辑:

import hmac
import hashlib
import base64
from django.conf import settings

@csrf_exempt
def line_webhook_handler(request):
    if request.method != 'POST':
        return HttpResponse(status=405)
    
    # 验证签名
    signature = request.META.get('HTTP_X_LINE_SIGNATURE', '')
    body = request.body
    hash = hmac.new(settings.LINE_CHANNEL_SECRET.encode('utf-8'), body, hashlib.sha256).digest()
    computed_signature = base64.b64encode(hash).decode('utf-8')
    
    if not hmac.compare_digest(computed_signature, signature):
        return HttpResponse(status=403)
    
    # 后续解析数据逻辑...
    try:
        webhook_data = request.json
        print("Received Webhook Data:", webhook_data)
        return JsonResponse({'status': 'success'}, status=200)
    except Exception as e:
        print("Webhook处理错误:", str(e))
        return JsonResponse({'status': 'error'}, status=400)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 21:11:01