Class: Spree::StripeWebhooksController

Inherits:
BaseController
  • Object
show all
Defined in:
app/controllers/spree/stripe_webhooks_controller.rb

Instance Method Summary collapse

Instance Method Details

#handlerObject



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
45
# File 'app/controllers/spree/stripe_webhooks_controller.rb', line 11

def handler
  sig_header = request.env['HTTP_STRIPE_SIGNATURE']
  payload = request.body.read

  event = Stripe::Webhook.construct_event(
    payload, sig_header, @stripe_configuration.preferred_webhook_secret
  )

  if event.present? && (%w[customer.subscription.updated customer.subscription.deleted].include? event.type)
    subscription = Spree::StripeSubscription.create_or_update_subscription(event)
    subscription.register_webhook_event(event)
  elsif event.present? && (%w[subscription_schedule.updated].include? event.type)
    subscription = Spree::StripeSubscription.update_subscription_schedule(event)
    subscription.register_webhook_event(event) if subscription.present?
  elsif event.present? && (%w[invoice.paid].include? event.type)
    subscription = Spree::StripeSubscription.create_or_update_invoice(event)
    subscription.register_webhook_event(event) if subscription.present?
  else
    Rails.logger.warn "Unhandled event type: #{event&.type}"
  end

  render json: { success: true }, status: :ok
rescue JSON::ParserError => e
  # Invalid payload
  Rails.logger.error e
  render json: { success: false }, status: :not_found
rescue Stripe::SignatureVerificationError => e
  # invalid signature
  Rails.logger.error e
  render json: { success: false }, status: :not_found
rescue ActiveRecord::RecordNotFound => e
  # Either StripeCustomer or StripePlan doesn't exist in our records
  Rails.logger.error e
  render json: { success: false }, status: :ok
end