Last active
August 29, 2015 14:14
-
-
Save shihweilo/cb81888f6e302c458838 to your computer and use it in GitHub Desktop.
Django view decorator for the HMAC verification of a Shopify Webhook.
This file contains 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
# modified from https://gist.github.com/gavinballard/8513270 | |
from functools import wraps | |
import hashlib | |
import base64 | |
import hmac | |
import json | |
from django.conf import settings | |
def shopify_webhook(f): | |
""" | |
A decorator that checks and validates a Shopify Webhook request. | |
""" | |
def _hmac_is_valid(body, secret, hmac_to_verify): | |
hash_ = hmac.new(secret, body, hashlib.sha256) | |
hmac_calculated = base64.b64encode(hash_.digest()) | |
return hmac_calculated == hmac_to_verify | |
@wraps(f) | |
def wrapper(request, *args, **kwargs): | |
# Try to get required headers and decode the body of the request. | |
try: | |
webhook_topic = request.META['HTTP_X_SHOPIFY_TOPIC'] | |
webhook_hmac = request.META['HTTP_X_SHOPIFY_HMAC_SHA256'] | |
webhook_data = json.loads(request.body) | |
except AttributeError: | |
return HttpResponseBadRequest() | |
# Verify the HMAC. | |
if not _hmac_is_valid(request.body, settings.SHOPIFY_APP_API_SECRET, webhook_hmac): | |
return HttpResponseForbidden() | |
# Otherwise, set properties on the request object and return. | |
request.webhook_topic = webhook_topic | |
request.webhook_data = webhook_data | |
return f(request, *args, **kwargs) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment