discourse-subscriptions/app/controllers/hooks_controller.rb

71 lines
1.9 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
module DiscourseSubscriptions
class HooksController < ::ApplicationController
2020-01-14 04:58:34 -05:00
include DiscourseSubscriptions::Group
skip_before_action :verify_authenticity_token, only: [:create]
def create
2020-01-12 19:10:06 -05:00
begin
payload = request.body.read
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
webhook_secret = SiteSetting.discourse_subscriptions_webhook_secret
2020-01-12 19:10:06 -05:00
event = ::Stripe::Webhook.construct_event(payload, sig_header, webhook_secret)
2020-01-12 19:10:06 -05:00
rescue JSON::ParserError => e
2020-01-14 02:46:48 -05:00
render_json_error e.message
2020-01-12 19:10:06 -05:00
return
rescue Stripe::SignatureVerificationError => e
2020-01-14 02:46:48 -05:00
render_json_error e.message
2020-01-12 19:10:06 -05:00
return
end
2020-01-14 04:58:34 -05:00
case event[:type]
2020-01-24 23:06:05 -05:00
when 'customer.subscription.updated'
customer = Customer.find_by(
customer_id: event[:data][:object][:customer],
product_id: event[:data][:object][:plan][:product]
)
if customer && subscription_completion?(event)
user = ::User.find(customer.user_id)
group = plan_group(event[:data][:object][:plan])
group.add(user) if group
end
2020-01-14 04:58:34 -05:00
when 'customer.subscription.deleted'
customer = Customer.find_by(
2020-01-24 23:06:05 -05:00
customer_id: event[:data][:object][:customer],
product_id: event[:data][:object][:plan][:product]
2020-01-14 04:58:34 -05:00
)
if customer
customer.delete
2020-01-14 18:20:21 -05:00
user = ::User.find(customer.user_id)
2020-01-24 23:06:05 -05:00
group = plan_group(event[:data][:object][:plan])
2020-01-14 18:20:21 -05:00
group.remove(user) if group
2020-01-14 04:58:34 -05:00
end
end
head 200
end
private
def subscription_completion?(event)
subscription_complete?(event) && previously_incomplete?(event)
end
def subscription_complete?(event)
event.dig(:data, :object, :status) == 'complete'
end
def previously_incomplete?(event)
event.dig(:data, :previous_attributes, :status) == 'incomplete'
end
end
end