我在尝试处理本地主机上的 Stripe webhooks 时遇到了 Django 的 CSRF 保护问题。我收到 403 Forbidden 错误,并显示消息“CSRF cookie not set”。尝试访问 /collect-stripe-webhook/ URL 时会发生错误,该 URL 旨在处理来自 Stripe 的传入 webhook 请求。此外,付款也会顺利完成
urls.py
urlpatterns = [
path('subscribe/', product_list, name='product_list'),
path('create-checkout-session/<int:product_id>/', create_checkout_session, name='create_checkout_session'),
path('collect-stripe-webhook/', stripe_webhook, name='stripe_webhook'), # Updated path
path('success/', TemplateView.as_view(template_name="subscriptions/success.html"), name='success'),
path('cancel/', TemplateView.as_view(template_name="subscriptions/cancel.html"), name='cancel'),
]
views.py:
@csrf_exempt
def stripe_webhook(request):
"""
View to handle Stripe webhooks.
"""
payload = request.body
sig_header = request.META.get('HTTP_STRIPE_SIGNATURE', None)
endpoint_secret = settings.STRIPE_WEBHOOK_SECRET
if not sig_header:
logger.error("No signature header found in the request")
return JsonResponse({'status': 'invalid request'}, status=400)
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
logger.error(f"Invalid payload: {e}")
return JsonResponse({'status': 'invalid payload'}, status=400)
except stripe.error.SignatureVerificationError as e:
logger.error(f"Invalid signature: {e}")
return JsonResponse({'status': 'invalid signature'}, status=400)
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
handle_checkout_session(session)
return HttpResponse(status=200)
模板:
<form action="{% url 'subscriptions:create_checkout_session' product.id %}" method="POST">
{% csrf_token %}
<button type="submit">Subscribe</button>
</form>
错误信息:
Forbidden (CSRF cookie not set.): /collect-stripe-webhook/
问题:
什么可能导致 Django 的 CSRF 保护出现此问题,以及如何解决它以成功处理 Stripe webhooks?
您能否分享整个日志,包括来自 create_checkout_session 的重定向,不幸的是,我没有足够的声誉在 StackOverflow 上发表评论,因此必须创建一个答案