name: stripe-integrationdescription: “精通 Stripe 支付处理集成构建稳健、符合 PCI 标准的支付流程包括结账、订阅、Webhook 和退款。”risk: criticalsource: communitydate_added: “2026-02-27”Stripe 集成精通 Stripe 支付处理集成构建稳健、符合 PCI 标准的支付流程包括结账、订阅、Webhook 和退款。何时不要使用本技能任务与 Stripe 集成无关你需要本范围之外的领域或工具说明明确目标、约束和所需输入。应用相关最佳实践并验证结果。提供可操作的步骤和验证方法。如需详细示例打开resources/implementation-playbook.md。何时使用本技能在 Web/移动应用中实现支付处理搭建订阅计费系统处理一次性支付和周期性扣款处理退款和争议管理客户支付方式为欧洲支付实现 SCA强客户认证使用 Stripe Connect 构建市场支付流程核心概念1. 支付流程结账会话托管Stripe 托管的支付页面极低的 PCI 合规负担实现最快支持一次性支付和周期性支付支付意向自定义 UI完全控制支付 UI需要 Stripe.js 以满足 PCI 合规实现更复杂更好的定制选项设置意向保存支付方式在不扣款的情况下收集支付方式用于订阅和未来支付需要客户确认2. Webhook关键事件payment_intent.succeeded支付完成payment_intent.payment_failed支付失败customer.subscription.updated订阅变更customer.subscription.deleted订阅取消charge.refunded退款已处理invoice.payment_succeeded订阅支付成功3. 订阅组成部分商品你在卖什么价格多少钱、多久一次订阅客户的周期性支付发票每个计费周期生成4. 客户管理创建和管理客户记录存储多个支付方式跟踪客户元数据管理账单信息快速开始importosimportstripe stripe.api_keyos.environ[STRIPE_SECRET_KEY]# 创建结账会话sessionstripe.checkout.Session.create(payment_method_types[card],line_items[{price_data:{currency:usd,product_data:{name:Premium Subscription,},unit_amount:2000,# $20.00recurring:{interval:month,},},quantity:1,}],modesubscription,success_urlhttps://yourdomain.com/success?session_id{CHECKOUT_SESSION_ID},cancel_urlhttps://yourdomain.com/cancel,)# 将用户重定向到 session.urlprint(session.url)支付实现模式模式 1一次性支付托管结账defcreate_checkout_session(amount,currencyusd):创建一次性支付的结账会话。try:sessionstripe.checkout.Session.create(payment_method_types[card],line_items[{price_data:{currency:currency,product_data:{name:Purchase,images:[https://example.com/product.jpg],},unit_amount:amount,# 金额以分为单位},quantity:1,}],modepayment,success_urlhttps://yourdomain.com/success?session_id{CHECKOUT_SESSION_ID},cancel_urlhttps://yourdomain.com/cancel,metadata{order_id:order_123,user_id:user_456})returnsessionexceptstripe.error.StripeErrorase:# 处理错误print(fStripe error:{e.user_message})raise模式 2自定义支付意向流程defcreate_payment_intent(amount,currencyusd,customer_idNone):为自定义结账 UI 创建支付意向。intentstripe.PaymentIntent.create(amountamount,currencycurrency,customercustomer_id,automatic_payment_methods{enabled:True,},metadata{integration_check:accept_a_payment})returnintent.client_secret# 发送到前端# 前端JavaScript const stripe Stripe(pk_test_...); const elements stripe.elements(); const cardElement elements.create(card); cardElement.mount(#card-element); const {error, paymentIntent} await stripe.confirmCardPayment( clientSecret, { payment_method: { card: cardElement, billing_details: { name: Customer Name } } } ); if (error) { // 处理错误 } else if (paymentIntent.status succeeded) { // 支付成功 } 模式 3创建订阅defcreate_subscription(customer_id,price_id):为客户创建订阅。try:subscriptionstripe.Subscription.create(customercustomer_id,items[{price:price_id}],payment_behaviordefault_incomplete,payment_settings{save_default_payment_method:on_subscription},expand[latest_invoice.payment_intent],)return{subscription_id:subscription.id,client_secret:subscription.latest_invoice.payment_intent.client_secret}exceptstripe.error.StripeErrorase:print(fSubscription creation failed:{e})raise模式 4客户门户defcreate_customer_portal_session(customer_id):创建门户会话让客户管理订阅。sessionstripe.billing_portal.Session.create(customercustomer_id,return_urlhttps://yourdomain.com/account,)returnsession.url# 将客户重定向到这里Webhook 处理安全的 Webhook 端点importosfromflaskimportFlask,requestimportstripe appFlask(__name__)endpoint_secretos.environ[STRIPE_WEBHOOK_SECRET]app.route(/webhook,methods[POST])defwebhook():payloadrequest.data sig_headerrequest.headers.get(Stripe-Signature)try:eventstripe.Webhook.construct_event(payload,sig_header,endpoint_secret)exceptValueError:# 无效的载荷returnInvalid payload,400exceptstripe.error.SignatureVerificationError:# 无效的签名returnInvalid signature,400# 处理事件ifevent[type]payment_intent.succeeded:payment_intentevent[data][object]handle_successful_payment(payment_intent)elifevent[type]payment_intent.payment_failed:payment_intentevent[data][object]handle_failed_payment(payment_intent)elifevent[type]customer.subscription.deleted:subscriptionevent[data][object]handle_subscription_canceled(subscription)returnSuccess,200defhandle_successful_payment(payment_intent):处理支付成功。customer_idpayment_intent.get(customer)amountpayment_intent[amount]metadatapayment_intent.get(metadata,{})# 更新你的数据库# 发送确认邮件# 履行订单print(fPayment succeeded:{payment_intent[id]})defhandle_failed_payment(payment_intent):处理支付失败。errorpayment_intent.get(last_payment_error,{})print(fPayment failed:{error.get(message)})# 通知客户# 更新订单状态defhandle_subscription_canceled(subscription):处理订阅取消。customer_idsubscription[customer]# 更新用户访问权限# 发送取消邮件print(fSubscription canceled:{subscription[id]})Webhook 最佳实践importhashlibimporthmacdefverify_webhook_signature(payload,signature,secret):手动验证 Webhook 签名。expected_sighmac.new(secret.encode(utf-8),payload,hashlib.sha256).hexdigest()returnhmac.compare_digest(signature,expected_sig)defhandle_webhook_idempotently(event_id,handler):确保 Webhook 只被处理一次。# 检查事件是否已处理ifis_event_processed(event_id):return# 处理事件try:handler()mark_event_processed(event_id)exceptExceptionase:log_error(e)# Stripe 会重试失败的 Webhookraise客户管理defcreate_customer(email,name,payment_method_idNone):创建 Stripe 客户。customerstripe.Customer.create(emailemail,namename,payment_methodpayment_method_id,invoice_settings{default_payment_method:payment_method_id}ifpayment_method_idelseNone,metadata{user_id:12345})returncustomerdefattach_payment_method(customer_id,payment_method_id):将支付方式关联到客户。stripe.PaymentMethod.attach(payment_method_id,customercustomer_id)# 设为默认stripe.Customer.modify(customer_id,invoice_settings{default_payment_method:payment_method_id})deflist_customer_payment_methods(customer_id):列出客户的所有支付方式。payment_methodsstripe.PaymentMethod.list(customercustomer_id,typecard)returnpayment_methods.data退款处理defcreate_refund(payment_intent_id,amountNone,reasonNone):创建退款。refund_params{payment_intent:payment_intent_id}ifamount:refund_params[amount]amount# 部分退款ifreason:refund_params[reason]reason# duplicate, fraudulent, requested_by_customerrefundstripe.Refund.create(**refund_params)returnrefunddefhandle_dispute(charge_id,evidence):用证据更新争议。stripe.Dispute.modify(charge_id,evidence{customer_name:evidence.get(customer_name),customer_email_address:evidence.get(customer_email),shipping_documentation:evidence.get(shipping_proof),customer_communication:evidence.get(communication),})测试# 使用测试模式密钥importos stripe.api_keyos.environ[STRIPE_SECRET_KEY]# 测试卡号TEST_CARDS{success:4242424242424242,declined:4000000000000002,3d_secure:4000002500003155,insufficient_funds:4000000000009995}deftest_payment_flow():测试完整支付流程。# 创建测试客户customerstripe.Customer.create(emailtestexample.com)# 创建支付意向intentstripe.PaymentIntent.create(amount1000,currencyusd,customercustomer.id,payment_method_types[card])# 使用测试卡确认confirmedstripe.PaymentIntent.confirm(intent.id,payment_methodpm_card_visa# 测试支付方式)assertconfirmed.statussucceeded资源references/checkout-flows.md详细的结账实现references/webhook-handling.mdWebhook 安全与处理references/subscription-management.md订阅生命周期references/customer-management.md客户与支付方式处理references/invoice-generation.md发票与计费assets/stripe-client.py生产就绪的 Stripe 客户端封装assets/webhook-handler.py完整的 Webhook 处理器assets/checkout-config.json结账配置模板最佳实践始终使用 Webhook不要只依赖客户端确认幂等性幂等地处理 Webhook 事件错误处理优雅地处理所有 Stripe 错误测试模式上线前用测试密钥充分测试元数据使用元数据将 Stripe 对象关联到你的数据库监控跟踪支付成功率和错误PCI 合规绝不在服务器上处理原始卡数据SCA 就绪为欧洲支付实现 3D Secure常见陷阱不验证 Webhook始终验证 Webhook 签名遗漏 Webhook 事件处理所有相关的 Webhook 事件硬编码金额使用分/最小货币单位没有重试逻辑为 API 调用实现重试忽略测试模式用测试卡测试所有边界情况局限性仅当任务与上述范围明确匹配时使用本技能。不要将输出视为环境特定验证、测试或专家审查的替代品。如果缺少必要的输入、权限、安全边界或成功标准请停下来询问澄清。