StripeEvent is built on the ActiveSupport::Notifications API. Incoming webhook requests are authenticated by retrieving the event object from Stripe[1]. Define subscriber blocks to handle one, many, or all event types.
# Gemfile
gem 'stripe_event'
# config/routes.rb
mount StripeEvent::Engine => '/my-chosen-path' # provide a custom path
# config/initializers/stripe.rb
Stripe.api_key = ENV['STRIPE_API_KEY'] # Set your api key
StripeEvent.setup do
subscribe 'charge.failed' do |event|
# Define subscriber behavior based on the event object
event.class #=> Stripe::Event
event.type #=> "charge.failed"
event.data #=> { ... }
end
subscribe 'customer.created', 'customer.updated' do |event|
# Handle multiple event types
end
subscribe do |event|
# Handle all event types - logging, etc.
end
end
If you have built an application that has multiple Stripe accounts--say, each of your customers has their own--you may want to define your own way of retrieving events from Stripe (e.g. perhaps you want to use the user_id parameter from the top level to detect the customer for the event, then grab their specific API key). You can do this:
StripeEvent.event_retriever = lambda do |params|
secret_key = Account.find_by_stripe_user_id(params[:user_id]).secret_key
Stripe::Event.retrieve(params[:id], secret_key)
end
During development it may be useful to skip retrieving the event from Stripe, and deal with the params hash directly. Just remember that the data has not been authenticated.
StripeEvent.event_retriever = lambda { |params| params }
The RailsApps project by Daniel Kehoe has released an example Rails 3.2 app with recurring billing using Stripe. The application uses StripeEvent to handle customer.subscription.deleted
events.
This button sends an example event to your webhook urls, including an id
of evt_00000000000000
. To confirm that Stripe sent the webhook, StripeEvent attempts to retrieve the event details from Stripe using the given id
. In this case the event does not exist and StripeEvent responds with 401 Unauthorized
. Instead of using the 'Test Webhooks' button, trigger webhooks by using the Stripe Dashboard to create test payments, customers, etc.
MIT License. Copyright 2012-2013 Integrallis Software.