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

新Stripe账号直接传测试卡号报错,旧Secret key可正常使用

新Stripe账号测试卡号直接调用API报错的原因及解决办法
  • 新老账号的权限规则差异
    Stripe后续更新了安全政策,禁止直接向API发送信用卡卡号(哪怕是测试环境的卡号),必须通过Stripe官方的前端工具(比如Elements、Stripe.js)生成测试令牌(Token)或支付方式(PaymentMethod)后,再将对应的ID传给后端调用API。
    你的旧账号是在这个政策生效前创建的,获得了遗留权限豁免,所以使用旧Secret Key时还能直接传测试卡号调用API,而新账号必须遵守新的安全规则。

  • 新账号的正确测试流程
    想要在新账号下完成测试,必须按照安全流程来:

    1. 前端集成Stripe Elements组件,用来收集测试卡号(比如4242424242424242这类)
    2. 通过Stripe.js生成对应的Token或PaymentMethod,拿到它们的ID
    3. 后端接收这个ID,用新的Secret Key调用Stripe API,使用ID来创建Charge或SetupIntent,不能直接传卡号

简单代码示例

前端(生成Token)

<script src="https://js.stripe.com/v3/"></script>
<script>
  const stripe = Stripe('你的公钥');
  const elements = stripe.elements();
  const cardElement = elements.create('card');
  cardElement.mount('#card-element');

  document.getElementById('pay-btn').addEventListener('click', async () => {
    const { token, error } = await stripe.createToken(cardElement);
    if (!error) {
      fetch('/create-charge', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ tokenId: token.id })
      });
    }
  });
</script>

后端(Node Express处理)

const stripe = require('stripe')('你的新Secret Key');
const express = require('express');
const app = express();
app.use(express.json());

app.post('/create-charge', async (req, res) => {
  try {
    const charge = await stripe.charges.create({
      amount: 1000, // 金额单位为分,这里是10美元
      currency: 'usd',
      source: req.body.tokenId,
      description: '测试订单'
    });
    res.json({ success: true, charge });
  } catch (err) {
    res.json({ success: false, error: err.message });
  }
});

内容的提问来源于stack exchange,提问作者sumanth.js

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:52:24