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

创建Stripe客户门户会话时遇CORS错误及请求URL识别失败

问题排查与解决方案

核心错误原因

  • CORS错误:前端通过AJAX(XMLHttpRequest/fetch/axios)请求后端接口,后端返回302重定向到Stripe客户门户URL,但billing.stripe.com未配置允许http://localhost:2200的跨域访问,浏览器拦截了该跨域重定向请求。
  • Stripe无效请求错误:前端错误地对Stripe生成的会话URL发起POST请求,而该URL是供用户在浏览器中直接访问的页面地址,并非Stripe API接口,因此Stripe返回URL无法识别的错误。

修复步骤

1. 修改后端代码,返回会话URL而非直接重定向

将后端的重定向逻辑改为返回JSON格式的会话URL,让前端自行处理跳转:

static async stripe_create_customer_portal_session(req, res) {
  try {
    // 注意:当前每次调用都新建客户不符合业务逻辑,后续需替换为用户已关联的Stripe客户ID
    const customer = await stripe.customers.create({})

    const session = await stripe.billingPortal.sessions.create({
      customer: customer.id,
      return_url: process.env.HOST_URL,
    });

    // 返回会话URL给前端
    res.json({ url: session.url });
  
  } catch (err) {
    console.error(err);
    res.status(500).json(error_res());
  }
}

2. 前端调整请求逻辑,收到URL后跳转

前端发起请求后,获取返回的URL,通过window.location.href跳转到Stripe客户门户:

// 示例:fetch实现
fetch('/user/stripe/create_customer_portal_session')
  .then(res => res.json())
  .then(data => {
    window.location.href = data.url;
  })
  .catch(err => console.error(err));

3. 优化客户关联逻辑(重要)

当前代码每次调用接口都会新建Stripe客户,不符合实际业务场景。需将系统用户与对应的Stripe客户ID关联存储(如存入数据库),调用门户会话时使用已有的客户ID:

// 示例:从当前用户信息中获取已关联的Stripe客户ID
const stripeCustomerId = req.user.stripe_customer_id;
const session = await stripe.billingPortal.sessions.create({
  customer: stripeCustomerId,
  return_url: process.env.HOST_URL,
});

内容的提问来源于stack exchange,提问作者Bear Bile Farming is Torture

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 16:05:37