Created
September 25, 2020 19:46
-
-
Save bearded-avenger/22f930351f4da6e5c3d46b9a3fee6c6e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class TenantWebhooksBraintreeController < ApplicationController | |
protect_from_forgery :except => :process_webhook | |
skip_before_action :verify_authenticity_token | |
before_action :verify_event | |
require 'pp' | |
def process_webhook | |
case @event.kind | |
when 'subscription_went_active' | |
WebhookServicesBraintree::SubscriptionWentActive.new({event:@event, site: @site}).call | |
when 'subscription_charged_successfully' | |
WebhookServicesBraintree::SubscriptionChargedSuccessfully.new({event:@event, site: @site}).call | |
when 'subscription_charged_unsuccessfully' | |
WebhookServicesBraintree::SubscriptionChargedUnsuccessfully.new({event:@event, site: @site}).call | |
when 'subscription_went_past_due' | |
WebhookServicesBraintree::SubscriptionWentPastDue.new({event:@event, site: @site}).call | |
when 'subscription_canceled' | |
WebhookServicesBraintree::SubscriptionCancelled.new({event:@event, site: @site}).call | |
when 'subscription_expired' | |
WebhookServicesBraintree::SubscriptionExpired.new({event:@event, site: @site}).call | |
when 'subscription_trial_ended' | |
WebhookServicesBraintree::SubscriptionTrialEnded.new({event:@event, site: @site}).call | |
else | |
Rails.logger.warn "Unhandled Webhook #{@event.kind}" | |
end | |
@site.braintree_webhook_events.create({event: @event.kind, subscription:@site.subscriptions.find_by_braintree_id(@event.subscription.id), payload: @event.to_json }) | |
render status: :ok, json: 'success' | |
end | |
private | |
def verify_event | |
@site = Site.find_by_subdomain!(request.subdomains.last) | |
gateway ||= Braintree::Gateway.new( | |
environment: Rails.env.production? ? :production : :sandbox, | |
merchant_id: @site.plugin_option('paypal','braintree_merchant_id'), | |
public_key: @site.plugin_option('paypal','braintree_public_key'), | |
private_key: @site.plugin_option('paypal','braintree_private_key') | |
) | |
@event = gateway.webhook_notification.parse(request.params['bt_signature'], request.params['bt_payload']) | |
rescue ActiveRecord::RecordNotFound, Braintree::InvalidSignature => e | |
head 403 | |
return | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment