integrallis / stripe_event

Stripe webhook integration for Rails applications.
https://rubygems.org/gems/stripe_event
MIT License
841 stars 107 forks source link

Filtering for only live events #33

Closed anark closed 9 years ago

anark commented 10 years ago

From the stripe webhook documentation(https://stripe.com/docs/webhooks)

With application webhooks, it's important to note that while only test webhooks will be sent to development applications, both live and test webhooks will be sent to production applications. We recommend that you check the livemode of the webhook before processing events.

However I am having a lot of trouble filtering out testmode webhooks when using stripe_event. I am using the following event_retriever

class EventRetriever
  def call(params)
    secret_key = Shop.find_by_stripe_id!(params[:user_id]).stripe_access_token
    event = Stripe::Event.retrieve(params[:id], secret_key)

    # add user id for shop selection
    event.user_id = params[:user_id]
    event
  end
end

Does anyone have any ideas on how to filter for only livemode webhooks using stripe_event for a stripe_connect application?

Thank You

cowholio4 commented 10 years ago

I just check for livemode before processing.


# config/initializers/stripe.rb

StripeEvent.event_retriever = lambda do |params|
  return Stripe::Event.construct_from(params.deep_symbolize_keys) unless params[:livemode] 

  api_key = Account.find_by!(stripe_user_id: params[:user_id]).api_key
  Stripe::Event.retrieve(params[:id], api_key)
end

StripeEvent.configure do |events|

  events.subscribe 'charge.failed' do |event|
    next unless event.livemode
    # Define subscriber behavior based on the event object
    event.class       #=> Stripe::Event
    event.type        #=> "charge.failed"
    event.data.object #=> #<Stripe::Charge:0x3fcb34c115f8>
  end

  events.all do |event|
    # Handle all event types - logging, etc.
  end
end
rmm5t commented 10 years ago

Since we're already talking about a Stripe Connect application, this could be more easily done in the customized event_retriever than having to build out a new config option and associated tests.

Of course this still requires that the backend skips the webhook callbacks if the event is nil, but that's a much smaller code change to maintain.

See my comment on https://github.com/integrallis/stripe_event/pull/36#issuecomment-48727086 which suggests building a way to reject (or ignore) certain webhooks.

For example:

StripeEvent.event_retriever = lambda do |params|
  return nil if Rails.env.production && !params[:livemode]
  # your regular event retriever stuff...
end
rmm5t commented 10 years ago

See #38 for an implementation that would allow for the example snippet that I pasted in my comment above.

invisiblefunnel commented 9 years ago

Closing. See #38.