name: stripe-patterns description: Stripe支付集成模式。用于实施支付流程、处理Webhook或处理订阅时。路由到现有模式并提供支付测试的证据模板。
Stripe模式技能
目的
指导安全和一致的Stripe集成。路由到现有支付模式并提供测试证据模板。
适用场景
- 创建或修改结账流程
- 实施Stripe webhooks
- 处理订阅或发票
- 测试支付功能
- 处理退款或争议
规范代码参考
配置
- 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