Skip to content

Instantly share code, notes, and snippets.

@fleetio
Forked from ryansch/hooks_controller.rb
Created October 21, 2011 03:30
Show Gist options
  • Save fleetio/1303033 to your computer and use it in GitHub Desktop.
Save fleetio/1303033 to your computer and use it in GitHub Desktop.
Rails Controller for Chargify Webhooks
# Add to the bottom of your application.rb file:
require 'digest/md5'
class Chargify::HooksController < ApplicationController
protect_from_forgery :except => :handle
skip_authorization_check # if using CanCan
before_filter :verify, :only => :handle
EVENTS = %w[ test signup_success signup_failure renewal_success renewal_failure payment_success
payment_failure billing_date_change subscription_state_change
subscription_product_change ].freeze
def handle
event = params[:event]
unless EVENTS.include? event
head :not_found and return
end
begin
convert_payload
self.send event
rescue Exception => e
Airbrake.notify(e)
head :unprocessable_entity and return
end
end
def test
Rails.logger.debug 'Chargify Webhook test worked :)'
head :ok
end
def signup_success
head :ok
end
def signup_failure
head :ok
end
def renewal_success
head :ok
end
def renewal_failure
head :ok
end
def payment_success
head :ok
end
def payment_failure
head :ok
end
def billing_date_change
head :ok
end
def subscription_state_change
head :ok
end
def subscription_product_change
head :ok
end
protected
def verify
if params[:signature].blank?
params[:signature] = request.headers["HTTP_X_CHARGIFY_WEBHOOK_SIGNATURE"]
end
unless Digest::MD5.hexdigest(CHARGIFY_CONFIG[:shared_key] + request.raw_post) == params[:signature]
render :nothing, :status => :forbidden
end
end
def convert_payload
if params[:payload].has_key? :transaction
@transaction = Chargify::Transaction.new params[:payload][:transaction]
end
if params[:payload].has_key? :subscription
@subscription = Chargify::Subscription.new params[:payload][:subscription]
end
end
end
# Add to your routes.rb file:
match '/chargify/hooks', :to => 'chargify/hooks#handle', :via => :post, :as => 'chargify_hooks'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment