name: stripe-patterns description: Stripe支付集成模式。在实现支付流程、处理Webhook或处理订阅时使用。提供现有模式的路线图以及支付测试的证据模板。
Stripe模式技能
目的
指导安全、一致的Stripe集成。提供现有支付模式的路线图以及测试用的证据模板。
适用场景
在以下情况下调用此技能:
- 创建或修改结账流程
- 实现Stripe Webhook
- 处理订阅或发票
- 测试支付功能
- 处理退款或争议
规范代码参考
配置
- Stripe客户端工厂:
lib/stripe-config.ts- 使用
createStripeClient()以保持API版本一致 - 切勿硬编码API密钥
- 使用
API路由
- 结账会话:
app/api/payments/create-checkout-session/route.ts - Webhook处理器:
app/api/payments/webhook/route.ts
助手函数
- 支付助手:
utils/data/payments/(使用RLS上下文) - 订阅助手:
utils/data/subscriptions/ - 发票助手:
utils/data/invoices/
关键规则
测试模式安全检查表
在进行任何支付工作之前:
- [ ] 验证
STRIPE_SECRET_KEY以sk_test_开头 - [ ] 确认测试Webhook密钥 (
whsec_...来自Stripe CLI) - [ ] 仅使用测试卡号 (4242…)
- [ ] 开发中切勿使用生产密钥
幂等性检查表
对于Webhook处理器:
- [ ] 在处理前存储事件ID
- [ ] 检查重复事件
- [ ] 使用数据库事务
- [ ] 即使在幂等性跳过时也返回200 OK
// 幂等Webhook模式
await withSystemContext(prisma, "webhook", async (client) => {
// 检查是否已处理
const existing = await client.webhook_events.findUnique({
where: { stripe_event_id: event.id },
});
if (existing) {
console.log(`跳过重复事件: ${event.id}`);
return;
}
// 处理并记录
await client.webhook_events.create({
data: {
stripe_event_id: event.id,
event_type: event.type,
processed_at: new Date(),
},
});
});
Webhook签名验证
始终验证Webhook签名:
import { stripe } from "@/lib/stripe-config";
const signature = request.headers.get("stripe-signature");
const event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET,
);
常见模式
创建结账会话
import { createStripeClient } from "@/lib/stripe-config";
import { withUserContext } from "@/lib/rls-context";
export async function createCheckout(userId: string, priceId: string) {
const stripe = createStripeClient();
// 存储用户上下文以处理成功
const session = await stripe.checkout.sessions.create({
mode: "subscription",
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/success?session_id={{CHECKOUT_SESSION_ID}}`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/pricing`,
metadata: { userId },
});
return session;
}
处理订阅事件
// Webhook事件类型要处理
const SUBSCRIPTION_EVENTS = [
"customer.subscription.created",
"customer.subscription.updated",
"customer.subscription.deleted",
"invoice.payment_succeeded",
"invoice.payment_failed",
];
Linear的证据模板
完成支付工作时,附加此证据块:
**支付测试证据**
- [ ] 测试模式已验证 (`sk_test_` 密钥)
- [ ] Webhook签名验证已测试
- [ ] 幂等性已测试(重复事件处理)
- [ ] 成功流程已测试(卡号4242...)
- [ ] 失败流程已测试(卡号4000000000000002)
- [ ] 订阅生命周期已测试(创建/更新/取消)
**测试结果:**
- 结账会话: [session_id]
- Webhook事件处理: [count]
- 订阅状态: [active/cancelled]
权威参考
- Stripe配置:
lib/stripe-config.ts - Webhook路由:
app/api/payments/webhook/route.ts - 支付测试:
__tests__/payments/ - Stripe文档: https://stripe.com/docs