DEV Community

loading...

Discussion on: Efficent webhook handling with Ruby on Rails

Collapse
mihaibb profile image
Mihai

Here's another approach that you might want to consider:

# controllers/webhooks/stripe_controller.rb

class Webhooks::StripeController < ApplicationController
  before_action :authorize_request!

  def handler
    payload = request.request_parameters # this will parse the body to json if content type is json


    # 1. Save the event and process in background
    save_event_for_the_record_and_process_later
    # 2. Process now
    process_now(payload)
  end

  private

    # Save events in db or other system so you can process event in background
    # and also to have a record of what you actually got from stripe.
    # It might be helful to debug future issues.
    def save_event_for_the_record(payload)
      event = Webhooks::StripeEvent.new(payload: payload)

      if event.save
        event.process_later
        head(:ok)
      else
        head :unprocessable_entity
      end
    end

    def process_now(payload)
      case payload['event']
      when ....

      end
    end

    def authorize_request!
      # validate request ...
    end
end

Forem Open with the Forem app