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

通过Stripe提交测试交易后success.html出现404错误的排查方法

Django + Stripe 支付成功后重定向404问题排查

问题描述

我在Django Web项目中使用Stripe执行测试交易,Stripe交易已成功完成,但重定向到success.html页面时出现404错误。已检查views.py和urls.py的语法,与学习平台提供的源码一致,推测可能是遗漏了Stripe API的更新内容,或是存在未发现的小错误,请问该如何开始排查?

相关views.py代码

from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from . models import Product, OrderDetail
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, HttpResponseNotFound
import stripe
import json

# Create your views here.


def index(request):
    products = Product.objects.all()
    print(products)
    return render(request, 'myapp/index.html', {'products': products})


def detail(request, id):
    product = Product.objects.get(id=id)
    stripe_publishable_key = settings.STRIPE_PUBLISHABLE_KEY
    return render(request, 'myapp/detail.html', {'product': product, 'stripe_publishable_key': stripe_publishable_key})


@csrf_exempt
def create_checkout_session(request, id):
    request_data = json.loads(request.body)
    product = Product.objects.get(id=id)
    stripe.api_key = settings.STRIPE_SECRET_KEY
    stripe.PaymentIntent.create(
        amount=int(product.price * 100),
        currency='usd',
        payment_method_types=['card'],
    )
    checkout_session = stripe.checkout.Session.create(
        customer_email=request_data['email'],
        payment_method_types=['card'],
        line_items=[
            {
                'price_data': {
                    'currency': 'usd',
                    'product_data': {
                        'name': product.name,
                    },
                    'unit_amount': int(product.price * 100)
                },
                'quantity': 1,
            }
        ],
        mode='payment',
        success_url=request.build_absolute_uri(reverse('success')) +
        "?session_id={CHECKOUT_SESSION_ID}",
        cancel_url=request.build_absolute_uri(reverse('failed')),
    )

    print(checkout_session)

    order = OrderDetail(
        customer_email=request_data['email'],
        product=product,
        stripe_payment_intent=checkout_session['payment_intent'],
        amount=int(product.price)
    )

   # checkout_session.payment_intent = intent
    order.save()

    return JsonResponse({'sessionId': checkout_session.id})


def payment_success_view(request):
    session_id = request.GET.get('session_id')
    if not session_id:
        return HttpResponseNotFound()

    stripe.api_key = settings.STRIPE_SECRET_KEY
    session = stripe.checkout.Session.retrieve(session_id)
    order = get_object_or_404(
        OrderDetail, stripe_payment_intent=session.payment_intent)
    order.has_paid = True
    order.save()

    return render(request, 'myapp/success.html', {'order': order},)


def payment_failed_view(request):
    return render(request, 'myapp/failed.html')

排查步骤

  • 确认URL路由配置
    检查urls.py中payment_success_view的name是否为success,因为success_url里使用了reverse('success'),如果name不匹配会生成错误URL,触发404。正确的路由配置示例:

    # 项目urls.py或app的urls.py
    from django.urls import path
    from . import views
    
    urlpatterns = [
        # ... 其他路由
        path('success/', views.payment_success_view, name='success'),
        path('failed/', views.payment_failed_view, name='failed'),
    ]
    

    同时确保app的urls.py已被项目主urls.py正确包含。

  • 验证success_url生成结果
    在create_checkout_session函数中添加打印语句,查看生成的success_url是否正确:

    success_url = request.build_absolute_uri(reverse('success')) + "?session_id={CHECKOUT_SESSION_ID}"
    print("Generated Success URL:", success_url)  # 新增打印
    

    查看控制台输出的URL是否符合预期,检查域名、端口、路径是否存在拼写错误。

  • 检查Stripe后台的Session记录
    登录Stripe后台,进入「支付」->「Checkout Sessions」,找到对应测试交易的Session,查看success_url字段的值是否与你生成的一致。如果Stripe端的URL错误,重定向必然失败。

  • 移除多余的PaymentIntent创建代码
    当前代码中手动创建了PaymentIntent,但Stripe Checkout Session会自动生成对应的PaymentIntent,手动创建的实例属于冗余代码,可能导致数据关联混乱,建议删除stripe.PaymentIntent.create(...)这一段代码。

  • 确认success.html模板存在
    检查myapp/templates/myapp/success.html文件是否存在,路径和文件名是否完全匹配(Django对模板路径大小写敏感)。

  • 查看浏览器网络请求日志
    打开浏览器开发者工具的「网络」面板,完成支付后观察重定向请求,查看请求的URL是否正确、是否携带session_id参数,以及服务器返回404的具体原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:50:14