Created
December 18, 2023 08:48
-
-
Save mikker/9405c9dc473d07ddfeefec95b38284c0 to your computer and use it in GitHub Desktop.
Homegrown StripeEvents handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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