SuperAPI AI 工具集

adding-stripe

编程与开发

查看项目

更新于 10-16 02:41

技能介绍

用途 该技能适用于用户提出添加支付、账单、订阅或 Stripe 集成需求时使用,帮助在 Web 应用中接入 Stripe 支付能力。

主要能力

  • 集成 Stripe 支付,包括结账会话(Checkout Sessions)、Webhook 和客户门户(Customer Portal)。
  • 支持订阅模式(subscription)与一次性支付(payment)。
  • 提供定价页面 UI 的搭建思路,通过计划卡片调用结账 API 路由。

使用方式

  1. 安装 SDK: npm install stripe @stripe/stripe-js

  2. 添加环境变量: STRIPE_SECRET_KEY=sk_test_... NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_...

  3. 创建 Stripe 客户端模块,新建 lib/stripe.ts: import Stripe from "stripe"; export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: "2024-12-18.acacia", });

  4. 创建结账 API 路由,创建 Stripe Checkout 会话: const session = await stripe.checkout.sessions.create({ mode: "subscription", // or "payment" for one-time payment_method_types: ["card"], line_items: [{ price: priceId, quantity: 1 }], success_url: ${origin}/success?session_id={CHECKOUT_SESSION_ID}, cancel_url: ${origin}/pricing, customer_email: userEmail, }); return redirect(session.url!);

  5. 创建 Webhook 处理程序,在 /api/webhooks/stripe 创建 POST 端点:

    • 使用 stripe.webhooks.constructEvent 验证 Webhook 签名。
    • 处理关键事件:checkout.session.completed、customer.subscription.updated、customer.subscription.deleted、invoice.payment_failed。
    • 用订阅状态更新数据库。
  6. 添加客户门户(可选):创建端点重定向到 stripe.billingPortal.sessions.create,让用户管理订阅。

  7. 添加定价页面 UI:创建带计划卡片的定价页面,调用结账 API 路由。

适用场景 适用于需要在 Web 应用中添加支付、账单、订阅或 Stripe 集成的开发场景,尤其是使用 Next.js 风格环境变量与 API 路由的项目。

限制与注意事项

  • 始终验证 Webhook 签名,绝不信任未验证的负载。
  • 本地 Webhook 测试使用 Stripe CLI:stripe listen --forward-to localhost:3000/api/webhooks/stripe。
  • 在用户数据库中存储 Stripe 客户 ID,避免创建重复客户。
  • 使用 stripe.prices.list 动态获取价格,而不是硬编码。
  • 资料未提供具体收费、价格、平台支持范围或效果保证等信息。