Skip to content

Instantly share code, notes, and snippets.

@csaunders
Created November 21, 2013 15:45
Show Gist options
  • Save csaunders/7583983 to your computer and use it in GitHub Desktop.
Save csaunders/7583983 to your computer and use it in GitHub Desktop.
require 'openssl'
require 'base64'
class WebhooksController < ApplicationController
skip_before_filter :verify_authenticity_token
before_filter :verify_webhook, :fetch_shop
def create
case topic
when 'orders/fulfilled'
job = OrderShipmentJob
when 'orders/cancelled'
job = OrderCancellationJob
when 'orders/create'
init_values = params.except(:controller, :action).merge(shop: @shop).symbolize_keys
order = Order.new(init_values)
order.save
when 'app/uninstalled'
job = AppUninstalledJob
end
Resque.enqueue(job, @shop.id, params.except(:controller, :action, :format)) if job
head :ok
end
private
def verify_webhook
request.body.rewind
data = request.body.read
unless valid_webhook?(data, env['HTTP_X_SHOPIFY_HMAC_SHA256'])
head :unauthorized
end
end
def valid_webhook?(data, expected_hmac)
digest = OpenSSL::Digest::Digest.new('sha256')
calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest(digest, GoogleTrustedShopifyStores::Settings::KEYS['application_secret'], data)).strip
calculated_hmac == expected_hmac
end
def fetch_shop
@shop = Shop.find_by_domain(request.headers['x-shopify-shop-domain'])
end
def topic
request.headers['X-SHOPIFY-TOPIC']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment