How to setup mandatory webhooks for a public Shopify app in your Django application

from django.views.decorators.csrf import csrf_exempt
import hmac
import hashlib
import base64

API_SECRET_KEY = 'shpss_xxx'

def _verify_webhook(data, hmac_header):
digest = hmac.new(API_SECRET_KEY.encode('utf-8'), data, digestmod=hashlib.sha256).digest()
computed_hmac = base64.b64encode(digest)

return hmac.compare_digest(computed_hmac, hmac_header.encode('utf-8'))


@csrf_exempt
def customer_data_request(request):
verified = _verify_webhook(request.body, request.headers['X-Shopify-Hmac-SHA256'])
if not verified:
return HttpResponse('Unauthorized', status=401)
# Process webhook payload
# ...
return HttpResponse('Authorized', status=200)


@csrf_exempt
def customer_data_erasure(request):
verified = _verify_webhook(request.body, request.headers['X-Shopify-Hmac-SHA256'])
if not verified:
return HttpResponse('Unauthorized', status=401)
# Process webhook payload
# ...
return HttpResponse('Authorized', status=200)


@csrf_exempt
def shop_data_erasure(request):
verified = _verify_webhook(request.body, request.headers['X-Shopify-Hmac-SHA256'])
if not verified:
return HttpResponse('Unauthorized', status=401)
# Process webhook payload
# ...
return HttpResponse('Authorized', status=200)
from django.urls import repath
from . import views

urlpatterns = [
re_path(r'^webhook/customers/data-request$', views.customer_data_request, name='customer_data_request'),
re_path(r'^webhook/customers/redact$', views.customer_data_erasure, name='customer_data_erasure'),
re_path(r'^webhook/shop/redact$', views.shop_data_erasure, name='shop_data_erasure')
]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store