Rails集成Stripe时如何让指定webhook仅在定期付款时触发通知邮件
实现方案
核心逻辑通过Stripe事件对象自带的字段做双重校验,直接过滤首次订阅支付场景:
- 第一重校验
invoice.billing_reason字段:首次订阅生成的账单对应值为subscription_create,后续自动续费的周期性账单对应值为subscription_cycle,仅保留值为subscription_cycle的事件即可过滤绝大多数首次订阅场景 - 第二重校验关联PaymentIntent的
on_session属性:on_session为true代表是用户当前在前端页面主动发起的支付操作,on_session为false代表是Stripe后台自动发起的续费扣款,直接跳过on_session为true的事件即可覆盖剩余边界场景
以下是Rails项目中Webhook处理的参考代码:
# invoice.payment_action_required 事件处理 def handle_payment_action_required(event) invoice = event.data.object # 过滤非续费场景的账单 return unless invoice.billing_reason == 'subscription_cycle' # 过滤用户主动发起的支付场景 payment_intent = Stripe::PaymentIntent.retrieve(invoice.payment_intent) return if payment_intent.on_session # 原有通知邮件逻辑 UserMailer.with(invoice: invoice).payment_action_notify.deliver_later end # invoice.payment_failed 事件处理 def handle_payment_failed(event) invoice = event.data.object return unless invoice.billing_reason == 'subscription_cycle' payment_intent = Stripe::PaymentIntent.retrieve(invoice.payment_intent) return if payment_intent.on_session # 原有通知邮件逻辑 UserMailer.with(invoice: invoice).payment_failed_notify.deliver_later end
如果你使用的Stripe API版本较旧,
billing_reason字段可能命名为reason,对应调整字段名即可。如果业务中存在后台手动发起续费扣款需要发通知的场景,也可以按需将对应billing_reason的枚举值加入校验条件。
内容的提问来源于stack exchange,提问作者opensource-developer
相关产品推荐
相关产品推荐

