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

React电商集成Stripe支付遇API密钥未提供错误,求解决方案

Stripe支付认证错误解决建议

核心问题分析

你遇到的错误本质是后端Stripe实例没有正确加载Secret Key,同时前端存在不必要且错误的密钥传递操作。

具体解决步骤

1. 修复后端环境变量配置

你的后端代码用process.env.STRIPE_KEY初始化Stripe,但大概率这个环境变量没被正确读取,或者值不对:

  • 确认STRIPE_KEY的值是Stripe的Secret Key(以sk_test_开头,而非前端的pk_test_公钥)
  • 确保Node.js能读取到这个环境变量:
    • 如果用.env文件,需要安装dotenv包并在项目入口文件顶部添加:
      require('dotenv').config();
      
    • 临时验证:在后端初始化Stripe前添加日志,检查变量是否存在:
      console.log('Stripe Key:', process.env.STRIPE_KEY); // 应输出sk_test_开头的字符串,而非undefined
      const stripe = require("stripe")(process.env.STRIPE_KEY);
      

2. 移除前端错误的请求头

前端完全不需要给后端传递Stripe密钥,这不仅没用,还存在安全风险(若误传Secret Key会导致泄露)。修改前端请求代码,删掉Authorization头:

const makeRequest = async () => {
  try{
    const res = await userRequest.post("/checkout/payment",{
      tokenId: stripeToken.id,
      amount: 500,
    }) // 移除第三个参数中的headers配置
    navigate("/success", {data:res.data})
  } catch{}
}

3. (可选)升级到Stripe推荐的Payment Intents API

你当前使用的stripe.charges.create是旧版API,Stripe现在推荐使用Payment Intents处理支付,更适配现代支付流程,避免潜在兼容性问题。示例代码:

// 后端替换charges.create为paymentIntents.create
router.post("/payment", async (req, res) => {
  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount: req.body.amount,
      currency: "usd",
      payment_method: req.body.tokenId,
      confirm: true,
    });
    res.status(200).json(paymentIntent);
  } catch (stripeErr) {
    res.status(500).json(stripeErr);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:55:42