Stripe 支付集成指南
什么是 Stripe?
Stripe 是全球领先的在线支付处理平台,专为 SaaS 和互联网企业设计。
核心优势:
- 全球覆盖 - 支持 135+ 种货币,覆盖 195+ 个国家
- 安全合规 - PCI DSS Level 1 认证,保障支付安全
- 开发友好 - 提供完善的 API 和 SDK
- 费率透明 - 标准费率 2.9% + $0.30/笔
为什么选择 Stripe?
- 适合独立开发者(无需复杂资质)
- 完善的文档和 API(开发体验好)
- 与 Vercel 等平台无缝集成
- 支持订阅、一次性付款等多种模式
第一步:注册 Stripe 账户
1.1 访问 Stripe 官网
打开浏览器访问:https://stripe.com 或 https://dashboard.stripe.com
1.2 创建账户
点击 "Start now" 或 "Sign up" 按钮
↓
填写邮箱地址
↓
设置密码
↓
完成邮箱验证
↓
登录后台
提示: Stripe 提供测试模式,在完成身份验证前可以使用 Sandbox(测试环境)进行开发
1.3 完成身份验证
登录后,Stripe 会要求填写以下信息:
第1步: 选择账户类型
- 个人 (Individual)
- 公司 (Company)
第2步: 填写基本信息
- 姓名
- 地址
- 电话号码
第3步: 提供银行账户信息(可选)
- 用于收款提现
- 需要验证银行账户
注意: 在 Live 模式(生产环境)启用前需要完成验证,Sandbox 模式(测试环境)无需验证
第二步:理解 Sandbox vs Live 模式
2.1 什么是 Sandbox 模式?
Stripe 提供两种模式:
| 模式 | 用途 | 资金 | 需要验证? |
|---|---|---|---|
| Sandbox (测试模式) | 开发测试 | 虚拟资金,测试卡号 | 不需要 |
| Live (生产模式) | 正式收款 | 真实资金,真实交易 | 需要 |
2.2 切换模式
在 Stripe Dashboard 右上角,可以看到模式切换开关:
Test mode (测试模式) ⟷ Live mode (生产模式)
推荐开发流程:
第1步: 在 Sandbox 模式下开发测试
↓
第2步: 确保所有功能正常
↓
第3步: 切换到 Live 模式
↓
第4步: 进行真实交易
第三步:获取 API 密钥
3.1 找到密钥位置
- 登录 Stripe Dashboard
- 点击左侧菜单 “Developers”
- 选择 “API keys”
3.2 密钥类型
| 密钥类型 | 格式 | 用途 |
|---|---|---|
| Publishable key | pk_test_xxx / pk_live_xxx | 前端使用,可公开 |
| Secret key | sk_test_xxx / sk_live_xxx | 后端使用,必须保密 |
安全提示: Secret key 绝对不能暴露在前端代码或 GitHub 仓库中!
3.3 配置环境变量
在项目根目录创建 .env.local 文件:
# Stripe 测试环境密钥
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_xxx
STRIPE_SECRET_KEY=sk_test_xxx
# Stripe 生产环境密钥(上线时替换)
# NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_xxx
# STRIPE_SECRET_KEY=sk_live_xxx
第四步:安装 Stripe SDK
4.1 安装依赖
# 安装 Stripe Node.js SDK
npm install stripe
# 安装 Stripe React 组件(可选)
npm install @stripe/stripe-js @stripe/react-stripe-js
4.2 初始化 Stripe
后端初始化 (Node.js/Next.js API):
// lib/stripe.js
import Stripe from 'stripe';
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2023-10-16',
});
前端初始化:
// lib/stripe-client.js
import { loadStripe } from '@stripe/stripe-js';
export const stripePromise = loadStripe(
process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
);
第五步:创建支付流程
5.1 创建 Checkout Session (推荐)
API 路由 (pages/api/checkout.js):
import { stripe } from '@/lib/stripe';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: '产品名称',
description: '产品描述',
},
unit_amount: 1999, // 金额单位是分,1999 = $19.99
},
quantity: 1,
},
],
mode: 'payment', // 'payment' 一次性付款, 'subscription' 订阅
success_url: `${req.headers.origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/cancel`,
});
res.status(200).json({ sessionId: session.id, url: session.url });
} catch (error) {
res.status(500).json({ error: error.message });
}
}
5.2 前端调用支付
// components/CheckoutButton.jsx
import { stripePromise } from '@/lib/stripe-client';
export default function CheckoutButton() {
const handleCheckout = async () => {
const response = await fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
});
const { url } = await response.json();
// 跳转到 Stripe 支付页面
window.location.href = url;
};
return (
<button onClick={handleCheckout}>
立即购买
</button>
);
}
第六步:处理 Webhook
6.1 什么是 Webhook?
Webhook 是 Stripe 主动通知你的服务器支付状态变化的方式。
6.2 创建 Webhook 端点
API 路由 (pages/api/webhook.js):
import { stripe } from '@/lib/stripe';
import { buffer } from 'micro';
export const config = {
api: { bodyParser: false },
};
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).end();
}
const buf = await buffer(req);
const sig = req.headers['stripe-signature'];
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
let event;
try {
event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
} catch (err) {
console.error(`Webhook Error: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// 处理不同事件类型
switch (event.type) {
case 'checkout.session.completed':
const session = event.data.object;
// 处理支付成功逻辑
console.log('支付成功:', session.id);
break;
case 'payment_intent.succeeded':
console.log('付款意图成功');
break;
default:
console.log(`未处理的事件类型: ${event.type}`);
}
res.status(200).json({ received: true });
}
6.3 配置 Webhook
- 在 Stripe Dashboard 进入 “Developers” → “Webhooks”
- 点击 “Add endpoint”
- 输入你的 Webhook URL:
https://yourdomain.com/api/webhook - 选择要监听的事件(如
checkout.session.completed) - 复制 Webhook Secret 到环境变量
测试卡号
在 Sandbox 模式下使用以下测试卡号:
| 卡号 | 说明 |
|---|---|
4242 4242 4242 4242 | 成功支付 |
4000 0000 0000 0002 | 卡被拒绝 |
4000 0000 0000 9995 | 余额不足 |
- 有效期:任意未来日期(如 12/34)
- CVC:任意3位数字(如 123)
- 邮编:任意5位数字(如 12345)
常见问题
Q: 中国开发者可以使用 Stripe 吗?
A: 可以,但需要注意:
- 需要有海外银行账户(如香港账户)
- 或使用 Stripe Atlas 注册美国公司
- 部分功能可能受限
Q: 如何处理退款?
A: 使用 Stripe API:
const refund = await stripe.refunds.create({
payment_intent: 'pi_xxx',
amount: 1000, // 可选,部分退款
});
Q: 费用如何计算?
A: 标准费率:
- 国际卡:2.9% + $0.30
- 订阅额外费用:0.5%
- 货币转换:1%