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

Stripe集成未自动跳转至支付页面问题咨询

Stripe支付会话创建后无法自动跳转的问题解决

问题原因

你用fetch调用后端接口时,浏览器的fetch API默认不会自动跟随303重定向来跳转页面——它只会接收重定向响应的内容,不会触发浏览器的页面跳转。后端返回的303重定向只有在直接通过浏览器访问该接口(比如表单提交)时才会自动跳转,AJAX/fetch调用不适用这种方式。

解决方案

方案1:后端返回会话URL,前端主动跳转(官方推荐)

修改后端代码,不再返回重定向响应,而是返回包含支付链接的JSON数据:

@app.post('/create-checkout-session')
async def create_checkout_session(request: Request):
    data = await request.json()
    price_id = data['price_id']
    try:
        checkout_session = stripe.checkout.Session.create(
            line_items=[
                {
                    'price': price_id,
                    'quantity': 1,
                },
            ],
            mode='subscription',
            success_url='http://localhost:3000' + '?success=true',
            cancel_url='http://localhost:3000' + '?canceled=true',
        )
    except Exception as e:
        print(e)
        return {"error": str(e)}, 400
    return {"url": checkout_session.url}

然后修改前端代码,获取返回的URL并手动跳转:

fetch("{backend}/create-checkout-session", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    credentials: "include",
    body: JSON.stringify({ price_id: "price_1P3O6zRsJS40xuhRCkN4vrML" }),
  })
  .then(response => response.json())
  .then(data => {
    if (data.url) {
      window.location.href = data.url; // 跳转到Stripe支付页面
    } else if (data.error) {
      // 处理错误逻辑
      console.error(data.error);
    }
  })
  .catch(error => console.error('请求出错:', error));

方案2:前端提取重定向头跳转(不推荐)

如果不想修改后端,可以在前端获取响应的Location头,然后跳转:

fetch("{backend}/create-checkout-session", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    credentials: "include",
    body: JSON.stringify({ price_id: "price_1P3O6zRsJS40xuhRCkN4vrML" }),
    redirect: 'manual' // 手动处理重定向
  })
  .then(response => {
    if (response.status === 303) {
      const checkoutUrl = response.headers.get('Location');
      if (checkoutUrl) {
        window.location.href = checkoutUrl;
      }
    } else {
      // 处理其他响应情况
    }
  })
  .catch(error => console.error('请求出错:', error));

官方预期实现方式

Stripe官方推荐前端通过AJAX获取支付会话URL,然后主动跳转的方式,这种方式让前端能更好地控制支付流程(比如在跳转前添加加载状态、处理错误),而依赖后端重定向只适用于传统表单提交的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:45:54