Module: BetterAuth::Stripe::Routes::StripeWebhook

Defined in:
lib/better_auth/stripe/routes/stripe_webhook.rb

Class Method Summary collapse

Class Method Details

.endpoint(config) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/better_auth/stripe/routes/stripe_webhook.rb', line 9

def endpoint(config)
  BetterAuth::Endpoint.new(path: "/stripe/webhook", method: "POST", disable_body: true) do |ctx|
    signature = ctx.headers["stripe-signature"]
    raise BetterAuth::APIError.new("BAD_REQUEST", message: BetterAuth::Stripe::ERROR_CODES.fetch("STRIPE_SIGNATURE_NOT_FOUND")) if signature.to_s.empty?

    raise BetterAuth::APIError.new("INTERNAL_SERVER_ERROR", message: BetterAuth::Stripe::ERROR_CODES.fetch("STRIPE_WEBHOOK_SECRET_NOT_FOUND")) if config[:stripe_webhook_secret].to_s.empty?

    payload = ctx.raw_body.to_s.empty? ? ctx.body : ctx.raw_body
    event = begin
      client = BetterAuth::Plugins.stripe_client(config)
      webhooks = client.webhooks if client.respond_to?(:webhooks)
      unless webhooks
        raise BetterAuth::APIError.new("BAD_REQUEST", message: BetterAuth::Stripe::ERROR_CODES.fetch("FAILED_TO_CONSTRUCT_STRIPE_EVENT"))
      end

      if webhooks.respond_to?(:construct_event_async)
        webhooks.construct_event_async(payload, signature, config[:stripe_webhook_secret])
      elsif webhooks.respond_to?(:construct_event)
        webhooks.construct_event(payload, signature, config[:stripe_webhook_secret])
      else
        raise BetterAuth::APIError.new("BAD_REQUEST", message: BetterAuth::Stripe::ERROR_CODES.fetch("FAILED_TO_CONSTRUCT_STRIPE_EVENT"))
      end
    rescue BetterAuth::APIError
      raise
    rescue
      raise BetterAuth::APIError.new("BAD_REQUEST", message: BetterAuth::Stripe::ERROR_CODES.fetch("FAILED_TO_CONSTRUCT_STRIPE_EVENT"))
    end
    raise BetterAuth::APIError.new("BAD_REQUEST", message: BetterAuth::Stripe::ERROR_CODES.fetch("FAILED_TO_CONSTRUCT_STRIPE_EVENT")) unless event
    begin
      BetterAuth::Plugins.stripe_handle_event(ctx, event)
    rescue
      raise BetterAuth::APIError.new("BAD_REQUEST", message: BetterAuth::Stripe::ERROR_CODES.fetch("STRIPE_WEBHOOK_ERROR"))
    end
    ctx.json({success: true})
  end
end