关于 stripe-integration
stripe-integration 是为开发者提供 Stripe 支付集成指导的技能,涵盖 API 选择、订单履行、订阅、密钥安全和测试。它强调通过 Webhook 和幂等键处理可靠支付,并建议在细节不确定时查阅 Stripe 文档。
主要功能
- 01按支付场景选择 Stripe API
- 02通过 Webhook 履行订单并同步订阅
- 03验证签名并处理重复事件
- 04使用幂等键避免重复创建
- 05管理密钥、沙盒与支付测试
适用场景
- 01为 Web 应用实现一次性支付或订阅
- 02处理延迟付款、Webhook 重试与事件顺序
- 03安全配置 Stripe 密钥并测试集成
MCP 相关
文档建议在需要确认 Stripe 细节时使用 Stripe MCP server 的 search_stripe_documentation 工具。Stripe MCP server 还可向 Agent 提供账户数据和文档搜索,并支持需确认的写入操作。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ davila7/ claude-code-templates --skill stripe-integration安装后在 Claude Code 中输入/stripe-integration确认已加载。
详细介绍
Stripe 集成
有关如何构建支付代码的指南,帮助避免订单丢失、重复扣款或密钥泄露。本指南遵循 Stripe 截至 2026 年 10 月的官方建议。涉及具体细节(参数、事件名称或 API 版本)时,请查阅
docs.stripe.com 或 Stripe MCP 服务的
search_stripe_documentation 工具,不要仅凭记忆作出判断。
版本
- 最新 API 版本:
2026-09-30.endive。请在客户端上显式固定此版本,这样账户默认版本更改时,响应格式就不会随之改变。 - 最新服务端 SDK:Node.js 23、Python 16、Ruby 20、PHP 22、Java 34、Go 87、.NET 53。请创建客户端实例;所有 SDK 中的全局密钥模式(
stripe.api_key = …、Stripe.setApiKey)均已弃用。 - 如需将现有集成迁移到较新版本,请先阅读 升级 API 版本。
// lib/stripe.ts
import Stripe from 'stripe';
export const stripe = new Stripe(process.env.STRIPE_API_KEY!, {
apiVersion: '2026-09-30.endive',
});
选择 API
| 构建内容 | 使用 |
|---|---|
| 一次性付款,简单产品 | Payment Links(无需代码)或 Checkout Sessions |
| Web 应用中的一次性付款 | Checkout Sessions(托管或嵌入式) |
| 自定义支付表单 | Checkout Sessions 搭配 ui_mode: 'custom' + Payment Element |
| 保存银行卡以供日后使用 | Setup Intents |
| 离线扣款(客户不在场) | 使用已保存支付方式的 Payment Intents |
| 订阅、席位、试用 | Billing API + Checkout mode: 'subscription' + Customer Portal |
| 新的按用量计费 | Metronome(Stripe 的用量平台),而非原始 Billing Meters |
| 市场或平台 | Connect、Accounts v2(/v2/core/accounts)、Stripe 托管式入驻 |
切勿使用 Charges API、Sources API、Tokens API、Card Element 或
plan 对象。这些均已弃用或属于旧版功能;请使用上表中的方案和 Prices。
规则
通过 Webhook 履行订单,切勿依赖成功页面
客户可能在成功页面加载前完成付款并关闭标签页。仅在 Webhook 处理程序中授予访问权限、发送电子邮件和写入订单。
- 处理
checkout.session.completed以及checkout.session.async_payment_succeeded。仅在session.payment_status !== 'unpaid'时履行订单。延迟付款方式(银行扣款)可能会在付款状态仍为未付款时发送completed。 - 对于这些失败情况,处理
checkout.session.async_payment_failed。 - 订阅需要处理
customer.subscription.created|updated|deleted、invoice.paid和invoice.payment_failed。续订、催款和取消只能通过这种方式通知你。 - 上线前必须配置 Webhook,不能等到上线后再处理。
验证每个 Webhook 的签名,并使用原始请求体
签名验证需要 Stripe 发送的确切字节。解析请求体的中间件会导致验证失败。
// Next.js App Router: app/api/stripe/webhook/route.ts
import Stripe from 'stripe';
import { stripe } from '@/lib/stripe';
export async function POST(req: Request) {
const body = await req.text(); // raw body, do not use req.json()
const signature = req.headers.get('stripe-signature');
if (!signature) return new Response('missing signature', { status: 400 });
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!,
);
} catch {
return new Response('invalid signature', { status: 400 });
}
switch (event.type) {
case 'checkout.session.completed':
case 'checkout.session.async_payment_succeeded': {
// Re-fetch instead of trusting the payload snapshot.
const session = await stripe.checkout.sessions.retrieve(event.data.object.id);
// fulfillOrder must be idempotent: the same event can arrive twice.
if (session.payment_status !== 'unpaid') await fulfillOrder(session.id);
break;
}
case 'checkout.session.async_payment_failed':
await markPaymentFailed(event.data.object.id);
break;
}
return new Response(null, { status: 200 });
}
- 在 Cloudflare Workers、Deno 或 Bun 上,使用
await stripe.webhooks.constructEventAsync(...)。 - 在 Express 中,仅在 Webhook 路由上挂载
express.raw({ type: 'application/json' }),并确保它位于任何全局express.json()之前。 - 在实时模式下,Stripe 最多会重试三天,而且可能多次投递同一事件,或以乱序投递事件。请确保
fulfillOrder具有幂等性(为已处理的事件 ID 或会话 ID 设置唯一约束),并根据对象的当前状态而非事件顺序作出判断。 - 尽快返回 2xx;将耗时任务移到队列中。
每次创建操作都使用幂等键
没有幂等键时,网络重试可能会创建第二笔扣款或订阅。
await stripe.paymentIntents.create(
{ amount: 2000, currency: 'usd', customer: customerId },
{ idempotencyKey: `order-${orderId}-charge` },
);
请根据你自己的记录(订单 ID、用户 ID + 操作)生成密钥,而不是每次尝试都生成随机值,否则重试时会使用新密钥。
让 Stripe 选择支付方式
不要传入 payment_method_types(即使是 ['card'] 也不行)。省略此参数即可启用动态支付方式,并在 Dashboard 中进行配置。如需缩小支付方式列表,可在 Payment Intents 和 Setup Intents 上使用 payment_method_configuration、excluded_payment_method_types 或 allowed_payment_method_types。唯一例外是 Terminal:payment_method_types: ['card_present']。
按 ID 将 Stripe 对象映射到你的记录
在你自己的记录中存储 Stripe Customer、Subscription 和 Checkout Session ID,并通过这些 ID 解析 Webhook 事件。将 metadata(例如 Session 上的 client_reference_id 或 metadata.orderId)用作备用映射,而非主要关联方式。
保持订阅状态同步
从数据库读取访问权限;数据库应由上述订阅 Webhook 更新。当决策取决于订阅状态时,重新从 Stripe 获取订阅。使用 Customer Portal 处理升级、降级、取消和银行卡更新,而不是自行构建这些页面。每个套餐创建一个 Product,仅为同一套餐的不同版本(按月、按年、按货币)关联多个 Price。不要基于原始 Payment Intents 构建续费循环;Billing 会处理重试和催款(在 Dashboard 中配置 Smart Retries 和邮件)。
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: stripeCustomerId,
line_items: [{ price: priceId, quantity: 1 }],
subscription_data: { trial_period_days: 14 },
success_url: `${baseUrl}/billing/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${baseUrl}/pricing`,
});
税费
automatic_tax: { enabled: true } 不会收取任何税费,也不会返回错误,除非账户已针对客户所在司法辖区完成有效的税务注册。告知任何人税务功能已启用前,请先检查注册情况。
密钥与安全
- 优先使用仅具备各服务所需权限的受限 API 密钥(
rk_),而不是完整的 Secret Key(sk_)。每个环境使用单独的密钥。 - 将密钥保存在平台的 Secret Store(Cloudflare 和 Vercel secrets、AWS Secrets Manager、GCP Secret Manager、Azure Key Vault)中。切勿将其放在源代码、客户端代码、移动应用、日志或错误消息中。仓库中与
[sr]k_live_匹配的字符串都是有效密钥:请立即轮换。 - 将 Webhook 签名密钥(
whsec_)视为 API 密钥。 - 添加提交前密钥扫描,检查
sk_和rk_字符串。 - 设置 Content-Security-Policy,在
script-src、frame-src和connect-src中允许https://*.stripe.com。 - 在 Connect OAuth 流程中,发送并验证随机
state值。
测试
- 使用 sandbox 开发;每位开发者或每个 CI 作业使用一个,而不是共用账户的测试模式。运行
stripe sandbox create即可创建一个,无需注册。 - 在本地转发事件:
stripe listen --forward-to localhost:3000/api/stripe/webhook(会输出要使用的whsec_),然后运行stripe trigger checkout.session.completed。 - 测试卡号:
4242 4242 4242 4242可成功付款,4000 0025 0000 3155需要 3D Secure,4000 0000 0000 9995会被拒绝(余额不足)。 - 使用测试时钟,让订阅经历续费和付款失败。
- 上线前,按 go-live checklist 逐项检查,并仅为你会处理的事件注册生产环境 Webhook 端点。
工具
- Stripe MCP 服务(
https://mcp.stripe.com,OAuth)可为 Agent 提供账户数据和文档搜索:npx claude-code-templates@latest --mcp devtools/stripe。 - 通过 MCP 执行写入和资金转移前,请先征求确认:
npx claude-code-templates@latest --setting permissions/stripe-mcp-confirm-writes。 - 注册公司:可通过 MCP(
atlas_company_formation)或 CLI 启动 Stripe Atlas(特拉华州 C Corp 或 LLC)(先运行stripe plugin install tools,然后运行stripe tools create_atlas_application)。Atlas 会验证每项信息;身份验证、付款、签名和提交都在 Stripe Dashboard 中完成。记录创始人对实体类型、股权和归属期的决定;切勿替用户做决定。 - Stripe 发布并维护自己的 Agent 技能(
npx skills add https://docs.stripe.com或stripe agent setup),包括stripe-best-practices和upgrade-stripe。
相关技能
适配良好的技能:nextjs-supabase-auth、nextjs-app-router-patterns、supabase-postgres-best-practices、api-security-best-practices