在Django中创建Stripe结账会话时出现404页面未找到错误
Django集成Stripe创建结账会话时出现404错误求助
我正在开发首个Django集成Stripe的项目,目前遇到无法解决的问题:尝试创建结账会话引导用户跳转至支付页面时,出现404页面未找到错误。
相关代码
views.py
class ProductLandingPageView(TemplateView): template_name = "landing.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") context = super(ProductLandingPageView, self).get_context_data(**kwargs) context.update({ "product": product, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLISHABLE_KEY }) return context class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs["pk"] product = Product.objects.get(id=product_id) YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( line_items=[ { # Provide the exact Price ID (for example, pr_1234) of the product you want to sell 'price': '{{product.price}}', 'quantity': 1, }, ], metadata={ "product_id": product.id }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return redirect(checkout_session.url, code=303)
urls.py
urlpatterns = [ path('', ProductLandingPageView.as_view(), name='landing'), path('success/', SuccessView.as_view(), name='success'), path('cancel/', CancelView.as_view(), name='cancel'), path('create-checkout-session/<pk>', CreateCheckoutSessionView.as_view(), name='create-checkout-session'), ]
结账按钮所在模板代码
<body> <section> <div class="product"> <div class="description"> <h3>{{product.name}}</h3> <h5>${{product.price}}</h5> </div> </div> <form action="/create-checkout-session" method="POST"> <button type="submit" id="checkout-button">Checkout</button> </form> </section> {% csrf_token %} </body> <script type="text/javascript"> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; var stripe = Stripe("{{ STRIPE_PUBLISHABLE_KEY }}"); var checkoutButton = document.getElementById("checkout-button"); checkoutButton.addEventListener("click", function () { fetch("{% url 'create-checkout-session' pk=product.id %}", { method: "POST", headers: { 'X-CSRFToken': csrftoken } }) .then(function (response) { return response.json(); }) .then(function (session) { return stripe.redirectToCheckout({ sessionId: session.id }); }) .then(function (result) { if (result.error) { alert(result.error.message); } }) .catch(function (error) { console.error("Error:", error); }); }); </script> </html>
错误表现
点击结账按钮后触发404页面未找到错误,请求的URL无法被Django路由匹配。
问题排查与修复方案
1. 补充URL路径转换器
urls.py中create-checkout-session/<pk>未指定参数类型,Django无法正确识别路径参数,需修改为:
path('create-checkout-session/<int:pk>', CreateCheckoutSessionView.as_view(), name='create-checkout-session'),
2. 修正模板form的action路径
模板中form的action指向无参数的/create-checkout-session,即使JS逻辑正确,form默认提交也会触发404,建议修改为带参数的URL:
<form action="{% url 'create-checkout-session' pk=product.id %}" method="POST">
若不需要form的默认提交行为,可直接移除form标签,仅保留按钮。
3. 修复Stripe价格参数的语法错误
views.py中'price': '{{product.price}}'是Django模板语法,在Python代码中不会被解析,会直接传递无效字符串给Stripe,需改为直接引用Python变量:
'price': product.price, # 注意:此处必须传入Stripe平台生成的Price ID(如pr_xxxxxx),而非金额数值
4. 调整视图返回类型以匹配前端期望
当前视图返回redirect到Stripe页面,但前端JS期望接收JSON格式的session ID,需修改视图返回JSON响应:
from django.http import JsonResponse class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs["pk"] product = Product.objects.get(id=product_id) YOUR_DOMAIN = "http://127.0.0.1:8000" try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': product.price, 'quantity': 1, }, ], metadata={ "product_id": product.id }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return JsonResponse({'sessionId': checkout_session.id}) except Exception as e: return JsonResponse({'error': str(e)}, status=400)
完成以上修改后,即可解决404错误,并正常跳转至Stripe支付页面。
内容的提问来源于stack exchange,提问作者KipronoKirui
相关产品推荐
相关产品推荐

