Stripe支付开发:如何编写API获取Token并完成收款?
Stripe 无UI端收款API实现指南
先澄清几个核心概念
- 不要直接接收原始卡片信息:这会触发最严格的PCI SAQ D合规要求,成本高且风险大,Stripe官方强烈推荐用前端Elements组件处理卡片信息,后端仅接收生成的Token。但如果业务必须后端直接处理卡片信息,需先评估合规成本。
- Token vs Setup Intent:Token是卡片信息的一次性安全凭证,用于单次收款;Setup Intent是用于验证并保存支付方式到客户账户,供后续重复收款使用,单次收款不需要用它。
步骤1:环境准备
- 安装对应语言的Stripe SDK,以Node.js为例:
npm install stripe - 从Stripe后台获取Secret Key(测试环境用
sk_test_xxx,生产环境用sk_live_xxx)。
步骤2:后端生成卡片Token(合规风险提示:仅在满足PCI SAQ D时使用)
编写API接收卡片信息,调用Stripe Tokens API生成安全Token:
const stripe = require('stripe')('你的Stripe Secret Key'); const express = require('express'); const app = express(); app.use(express.json()); // 生成卡片Token的API app.post('/api/create-card-token', async (req, res) => { const { cardNumber, expMonth, expYear, cvc } = req.body; try { const token = await stripe.tokens.create({ card: { number: cardNumber, exp_month: expMonth, exp_year: expYear, cvc: cvc, }, }); res.status(200).json({ tokenId: token.id }); } catch (error) { res.status(400).json({ error: error.message }); } });
步骤3:创建Payment Intent完成收款
拿到Token后,调用Payment Intent API完成收款:
// 处理收款的API app.post('/api/process-payment', async (req, res) => { const { tokenId, amount, currency } = req.body; // amount单位为最小货币单位,比如1000代表10 USD / 1000 CNY try { const paymentIntent = await stripe.paymentIntents.create({ amount: parseInt(amount), currency: currency || 'usd', payment_method: tokenId, confirm: true, // 立即确认并执行收款 automatic_payment_methods: { enabled: true }, }); res.status(200).json({ success: true, paymentIntentId: paymentIntent.id, status: paymentIntent.status }); } catch (error) { res.status(400).json({ success: false, error: error.message, code: error.code }); } }); app.listen(3000, () => console.log('Server running on port 3000'));
关于Setup Intent的补充
如果需要保存客户的支付方式供后续收款,才需要使用Setup Intent:
- 先创建Setup Intent并确认支付方式(验证卡片有效性)
- 将验证后的支付方式关联到客户账户
- 后续收款时直接使用该支付方式创建Payment Intent
示例代码(仅核心逻辑):
// 创建Setup Intent const setupIntent = await stripe.setupIntents.create({ customer: '客户ID', payment_method: tokenId, confirm: true, }); // 后续收款时使用保存的支付方式 const paymentIntent = await stripe.paymentIntents.create({ amount: 1000, currency: 'usd', customer: '客户ID', payment_method: setupIntent.payment_method, confirm: true, });
内容的提问来源于stack exchange,提问作者katie77
相关产品推荐
相关产品推荐

