Michael Lombardo Michael Lombardo - 2 months ago 9
Ruby Question

How to call handler methods in an initializer? creating webhooks

I want to receive stripe web-hooks live and in order to do that I have to use an initializer. Using Stripe_events gem. Im not too familiar with initializers, but I'm here to learn!

-I want my

event
(webhook) to get called with the handler_method.

My initializers/stripe.rb

Rails.configuration.stripe = {
:publishable_key => ENV['STRIPE_PUBLISHABLE_KEY'],
:secret_key => ENV['STRIPE_SECRET_KEY']

}

Stripe.api_key = Rails.configuration.stripe[:secret_key]


StripeEvent.configure do |events|
events.subscribe 'charge.succeeded', ReservationsController.new
events.all = AllEvents.new



end


As you can see I set events.all = AllEvents.new

I want to call all of the events into this one stripe_handler. Based on what the event.type is Ex.
'charge.succeeded'


if event.type == 'charge.succeeded'

etc........

end


in app/stripe_handlers/all_events.rb

class AllEvents
def call(event)

if event.type == 'charge.succeeded'

reservation = Reservation.find_by_transaction_id(event.object.id)
reservation.update_attributes pay_completed: true

# reservation = Reservation.find_by_transaction_id
elsif event.type == 'customer.created'


elsif event.type == 'account.application.deauthorized'

# look out for account.updated and check if the account ID is unknown

end
end
end


All in all, I want to send the events.all values to the handler_methods where I can make actions for each webhook.

Answer

I wanted to put this in comments but it's too big for a comment. After quickly reading the documentation here, I have written down below of my understanding of how to use the stripe_event gem.

So, initializers/stripe.rb you need something like the code block below. All you need to do is call events.subscribe in the configure block with the name of the event and an instance of class which would handle that event. You don't need to handle all the events using just one object.

StripeEvent.configure do |events|
    events.subscribe 'charge.succeeded', ChargeSucceeded.new
    event.subscribe 'customer.created', CustomerCreated.new
    event.subscribe 'account.application.deauthorized', Deauthorised.new
end

Then the classes which handle the events would look something like this:

class ChargeSucceeded
  def call(event)
    #Code to handle event 'charge.succeeded'
  end
end

class CustomerCreated
  def call(event)
    #Code to handle event 'customer.created'
  end
end

class Deauthorised
  def call(event)
    #Code to handle event 'account.application.deauthorized'
  end
end