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

如何解决Next.js集成Stripe时出现的CORS错误?

Next.js集成Stripe解决CORS错误方案

核心问题分析

你遇到的CORS错误本质是前端直接发起了对Stripe API的跨域请求,但Stripe的API仅允许后端服务调用(需使用服务端秘钥),前端直接请求必然触发CORS拦截。另外,跳转Stripe支付页无需AJAX请求,直接通过浏览器URL导航即可。

标准解决方案(完全规避CORS)

这是官方推荐的安全实现流程:

  • 前端发起POST请求到你的Next.js API路由 /api/checkout_sessions
  • 在该API路由的后端代码中,用Stripe服务端秘钥调用Stripe API创建支付会话:
    // pages/api/checkout_sessions.js
    import Stripe from 'stripe';
    
    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
    
    export default async function handler(req, res) {
      if (req.method === 'POST') {
        try {
          const session = await stripe.checkout.sessions.create({
            line_items: [
              {
                price: 'price_xxxxxx', // 替换为你的Stripe价格ID
                quantity: 1,
              },
            ],
            mode: 'payment',
            success_url: `${req.headers.origin}/success`,
            cancel_url: `${req.headers.origin}/cancel`,
          });
    
          res.status(200).json({ url: session.url });
        } catch (err) {
          res.status(err.statusCode || 500).json(err.message);
        }
      } else {
        res.setHeader('Allow', 'POST');
        res.status(405).end('Method Not Allowed');
      }
    }
    
  • 前端拿到返回的url后,直接通过浏览器导航跳转,而非AJAX请求:
    // 前端代码示例
    const createCheckoutSession = async () => {
      const response = await fetch('/api/checkout_sessions', { method: 'POST' });
      const data = await response.json();
      window.location.href = data.url; // 直接跳转,无CORS问题
    };
    

关于rewrites的配置(非必要,仅特殊场景参考)

如果因特殊需求必须通过前端代理请求Stripe API(强烈不推荐,会泄露服务端秘钥),可在next.config.js中配置如下:

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/stripe/:path*',
        destination: 'https://api.stripe.com/:path*', // 固定Stripe API地址,动态路径由:path*匹配
        headers: {
          'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
        },
      },
    ];
  },
};

module.exports = nextConfig;

⚠️ 注意:此方案会将Stripe服务端秘钥暴露在前端打包代码中,存在严重安全风险,禁止在生产环境使用。

额外排查点

  • 确认Stripe服务端秘钥未出现在前端代码中,所有Stripe API调用必须在Next.js API路由(后端环境)执行
  • 检查前端是否误将Stripe会话URL作为AJAX请求地址,正确做法是直接跳转该URL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:45:35