Skip to content

Instantly share code, notes, and snippets.

@mikker
Created December 18, 2023 08:48
Show Gist options
  • Save mikker/9405c9dc473d07ddfeefec95b38284c0 to your computer and use it in GitHub Desktop.
Save mikker/9405c9dc473d07ddfeefec95b38284c0 to your computer and use it in GitHub Desktop.
Homegrown StripeEvents handling
# app/models/stripe_events/account_updated.rb
module StripeEvents
class AccountUpdated
def call(event)
# do your thing
Rails.logger.debug(event.data.object)
end
end
end
# app/controllers/stripe_events_controller.rb
#
# route like
# post("/stripe_events", to: "stripe_events#create")
class StripeEventsController < ApplicationController
skip_before_action :verify_authenticity_token
def create
if signed_event = contruct_event
handle_event(signed_event)
end
head(:ok)
rescue Stripe::SignatureVerificationError => e
logger.error(e)
head(:bad_request)
end
private
def contruct_event
payload = request.body.read
signature = request.env["HTTP_STRIPE_SIGNATURE"]
secrets = Array(Rails.application.credentials.stripe_signing_secret)
secrets.each_with_index do |secret, i|
return Stripe::Webhook.construct_event(
payload,
signature,
secret
)
rescue Stripe::SignatureVerificationError
raise if i == secrets.size - 1
next
end
end
def handle_event(event)
return unless handler = handler_for(event.type)
handler.call(event)
end
def handler_for(type)
case type
when "account.updated"
StripeEvents::AccountUpdated.new
when "setup_intent.succeeded"
StripeEvents::SetupIntentSucceeded.new
when "charge.refunded"
StripeEvents::ChargeRefunded.new
else
# and so on ...
#
# default handler goes here
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment