Koudoku Webhook完全指南:订阅Stripe事件实现支付失败自动通知(4个核心事件)

原创2026-10-13 23:52:171,690 阅读
文章标签:后端

Koudoku Webhook完全指南:订阅Stripe事件实现支付失败自动通知(4个核心事件)

Koudoku 是为 Rails 应用提供健壮订阅功能的开源引擎,内置 Stripe 支付、价格表与订阅管理页面。本文聚焦 Koudoku 的 Webhook(Stripe 事件)机制,教你用 4 个核心事件实现支付失败自动通知、扣款成功记录、争议处理与取消订阅同步,帮助新手快速搭建完整的订阅生命周期自动化。

为什么 Rails 订阅项目离不开 Webhook?

在 Stripe 支付场景中,扣款、退款、争议大多发生在后台,用户的浏览器并没有打开你的网站。此时只有 **Webhook(服务器到服务器的事件推送)**能告诉你"刚刚发生了什么"。

Koudoku 内置了 Webhook 支持:

# config/routes.rb(Koudoku 引擎内部路由)
mount StripeEvent::Engine => '/webhooks'

💡 部署后,只需在 Stripe Dashboard 的 Webhook 设置中,把事件端点指向你应用的 /koudoku/webhooks 即可。

4 个核心 Stripe 事件:支付失败通知的关键

Koudoku 的 Subscription 关注点 预留了 3 个 Webhook 回调方法,配合 1 个"取消订阅"事件,正好构成 4 个核心场景:

Stripe 事件 含义 Subscription 回调方法
charge.failed 💳 扣款失败(卡过期、余额不足) charge_failed
invoice.payment_succeeded ✅ 扣款成功,可拿到金额 payment_succeeded(amount)
charge.dispute.created ⚠️ 用户发起争议(拒付) charge_disputed
customer.subscription.deleted ❌ 用户在 Stripe 侧取消订阅 直接调用 subscription_owner 逻辑

其中 charge.failed 就是实现"支付失败自动通知"的核心事件——一旦扣款失败,Stripe 立即推送事件,你的应用可以马上给用户发邮件提醒换卡,避免被动流失。

一键接入:两种订阅 Stripe 事件的方式

方式一:在 Koudoku 配置文件中订阅(推荐)

Koudoku 安装生成器会生成 config/initializers/koudoku.rb(模板见 koudoku.rb 模板),其中已预留注释:

# you can subscribe to additional webhooks here
# we use stripe_event under the hood and you can subscribe using the
# stripe_event syntax on the config object:
# config.subscribe 'charge.failed', Koudoku::ChargeFailed

直接写入即可(官方 README 示例):

# config/initializers/koudoku.rb
Koudoku.setup do |config|
  config.subscriptions_owned_by = :user
  config.stripe_publishable_key = ENV['STRIPE_PUBLISHABLE_KEY']
  config.stripe_secret_key = ENV['STRIPE_SECRET_KEY']

  # add webhooks
  config.subscribe 'charge.failed', YourChargeFailed
end

方式二:用 stripe_event 的 events.subscribe 块式语法

仓库自带的示例 config/initializers/stripe_event.rb 完整演示了 4 个核心事件的写法:

StripeEvent.configure do |events|
  # 支付失败:查找订阅并触发回调
  events.subscribe 'charge.failed' do |event|
    stripe_id = event.data.object['customer']
    subscription = ::Subscription.find_by_stripe_id(stripe_id)
    subscription.charge_failed
  end

  # 支付成功:记录金额
  events.subscribe 'invoice.payment_succeeded' do |event|
    stripe_id = event.data.object['customer']
    amount = event.data.object['total'].to_f / 100.0
    subscription = ::Subscription.find_by_stripe_id(stripe_id)
    subscription.payment_succeeded(amount)
  end

  # 争议创建
  events.subscribe 'charge.dispute.created' do |event|
    stripe_id = event.data.object['customer']
    subscription = ::Subscription.find_by_stripe_id(stripe_id)
    subscription.charge_disputed
  end

  # 订阅被删除:同步取消本地数据
  events.subscribe 'customer.subscription.deleted' do |event|
    stripe_id = event.data.object['customer']
    subscription = ::Subscription.find_by_stripe_id(stripe_id)
    subscription.subscription_owner.try(:cancel)
  end
end

在你的 Subscription 模型中实现通知逻辑

Koudoku 设计得很巧妙:Webhook 处理器只负责"找到订阅并调用方法",真正的业务逻辑由你覆写回调方法完成。这些方法定义在 app/concerns/koudoku/subscription.rb:

# 在你的 app/models/subscription.rb 中覆写(默认是空实现)
class Subscription < ActiveRecord::Base
  include Koudoku::Subscription

  # 💌 支付失败:发提醒邮件,引导用户更换卡片
  def charge_failed
    subscription_owner.notify_payment_failed!
  end

  # ✅ 扣款成功:记录营收指标
  def payment_succeeded(amount)
    Subscription.record_payment!(self, amount)
  end

  # ⚠️ 争议:标记订阅,进入人工审核流程
  def charge_disputed
    subscription_owner.notify_dispute!(self)
  end
end

prepare_for_* / finalize_* 这类模板方法用于前台交互(升级、降级、取消),而上面 3 个方法专属于 Webhook 回调,两者互不干扰。

配置清单与常见坑点

3 步完成部署 ✅

  1. Gemfile 中加入 gem 'koudoku',执行 rails g koudoku:install user && rake db:migrate
  2. Stripe Dashboard 创建 Webhook 端点,URL 指向生产环境的 /koudoku/webhooks
  3. 在 config/initializers/koudoku.rb 或 stripe_event.rb 中订阅 4 个事件,并覆写回调方法

常见坑点 ⚠️

  • 旧版 webhooks_api_key 必须删除:0.0.12 起 Koudoku 不再用 API key 保护 Webhook,配置文件中若残留该行会直接抛错(见 lib/koudoku.rb 与 CHANGELOG.md)
  • Stripe 密钥走环境变量:默认读取 STRIPE_PUBLISHABLE_KEY 与 STRIPE_SECRET_KEY,不要把密钥硬编码进版本库
  • 本地调试:可以用 Stripe CLI 把事件转发到本地,确认 charge.failed 等事件真的到达 /koudoku/webhooks
  • 回调方法别抛异常:Webhook 请求失败时 Stripe 会重试,建议把邮件发送等 I/O 操作放入异步队列

总结

Koudoku 的 Webhook 机制 = stripe_event 事件引擎 + 3 个预留回调方法,覆盖了订阅业务中最关键的 4 个自动化场景。掌握 charge.failed(支付失败自动通知)、invoice.payment_succeeded(扣款成功记录)、charge.dispute.created(争议处理)和 customer.subscription.deleted(取消同步)后,你的 Rails 订阅系统就能真正做到"支付事件不再失联"。

📎 参考文件:config/initializers/stripe_event.rb · app/concerns/koudoku/subscription.rb · config/routes.rb

登录后查看全文
koudoku