【问题标题】:Webhook handling with background job?使用后台作业处理 Webhook?
【发布时间】:2017-06-30 13:20:48
【问题描述】:

我只是想知道我一般如何处理来自第三方 API 的 webhook。

就我而言,我需要处理来自 Stripe 的 Webhooks。

所以我用

  • StripeEvent 处理和监听webhook handlers的入口。它提供了一个易于使用的界面来处理来自 Stripe 的事件。

主要实现是:

到目前为止一切正常。

但是,让我们假设

  • 在 webhook 处理程序中处理复杂的小逻辑
  • 侦听许多 webhook 请求

在这种情况下,我觉得我需要考虑使用后台工作

Best practices in stripe doc

如果您的 webhook 脚本执行复杂的逻辑或进行网络调用,则脚本可能会在 Stripe 看到其完整执行之前超时。出于这个原因,您可能希望通过返回 2xx HTTP 状态代码让您的 webhook 端点立即确认收到,>然后执行其其余职责。

这是我的代码, 我只是想知道我应该捆绑哪个部分并入队?

StripeEvent.event_retriever = lambda do |params|
  return nil if StripeWebhook.exists?(stripe_id: params[:id])
  StripeWebhook.create!(stripe_id: params[:id])

  return Stripe::Event.construct_from(params.deep_symbolize_keys) if Rails.env.test? # fetching the event from Stripe API

  return Stripe::Event.retrieve(params[:id])
end

StripeEvent.configure do |events|
  events.subscribe 'invoice.created', InvoiceCreated.new # handling the invoice.created event in service object
  events.subscribe 'invoice.payment_succeeded', InvoicePaymentSucceeded.new
 ...
end

【问题讨论】:

  • 我猜都是

标签: ruby-on-rails stripe-payments webhooks


【解决方案1】:

简短的回答,只需将Stripe::Event 实例序列化为带有Marshal::dump 的字符串,然后使用Marshal::load 在后台工作人员中反序列化回Stripe::Event 即可。

我们还希望使用我们的delayed_job 系统在后台处理 webhook 请求,该系统将作业存储在数据库表中,并将作业参数存储在字符串列中。

为此,我们首先需要将Stripe::Event 序列化为StripeEvent.configure 块中的字符串:

# event is an instance of Stripe::Event
serialized_event = Marshal::dump(event)

然后我们将后台作业排队而不是同步处理它,将我们的序列化事件作为字符串传递到它的存储位置(在我们的例子中是数据库表)以等待被处理。

然后我们的后台工作代码可以将它读回的字符串反序列化为Stripe::Event

event = Marshal::load(serialized_event)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    相关资源
    最近更新 更多