Django Shopify Webhook HMAC Verify

Borhan Tipu
2 min readMay 28, 2020

In this article, I will show you how you can verify Shopify Webhook Hmac in a Django Application.

In Shopify:
Go to Settings > Notifications > Webhook
1. Create a Webhook
2. Add Webhook URL

Create Webhook

You can use ngrok for development and testing purpose

SHOPIFY_WEBHOOK_SIGNED_KEY

After adding the webhook URL you will find a Signed Key for webhook just below of the Webhook URL list.

In Django:
Add a variable in settings.py file

SHOPIFY_WEBHOOK_SIGNED_KEY = env.str('SHOPIFY_WEBHOOK_SIGNED_KEY', '')

Then in your views.py file,
I used django-rest-framework views, response, and status.

from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response
import hmac
import hashlib
import base64
def computed_hmac(secret, body):
hash_code = hmac.new(secret.encode('utf-8'), body, hashlib.sha256)
return base64.b64encode(hash_code.digest()).decode()
def verify_hmac(secret, body, shopify_hmac):
return computed_hmac(secret, body) == shopify_hmac
@csrf_exempt
@api_view(['POST'])
def api_view_webhook(request):
# get hmac from shopify webhook request
shopify_hmac = request.headers.get('X-Shopify-Hmac-Sha256')
if verify_hmac(settings.SHOPIFY_WEBHOOK_SIGNED_KEY, request.body, shopify_hmac):
print('valid')
return Response(status=status.HTTP_200_OK)
else:
print('invalid')
return Response(status=status.HTTP_400_BAD_REQUEST)

In your urls.py file,

from .views import api_view_webhookurlpatterns = [
path('webhook/', api_view_webhook, name='api_view_webhook'),
]

If verify_hmac is True then it will print “valid” in terminal console otherwise it will print “invalid”.
That’s it.

Visit: imtipu.me

Contact if you need any help with Django and Shopify
Skype: me@imtipu.me

Email: me@imtipu.me

Thanks.

--

--