我如何验证从Shopify传入的webhook?Shopify提供了一个(Flask的)python实现,但我如何在Django/DRF中做这件事?
dldeef671#
在settings.py文件中设置这两个变量
settings.py
# settings.py SHOPIFY_HMAC_HEADER = "HTTP_X_SHOPIFY_HMAC_SHA256" SHOPIFY_API_SECRET = "5f6b6_my_secret"
然后,创建一个verify webhook函数,它接受Django请求作为参数
# utils.py import base64 import hashlib import hmac from django.conf import settings from django.core.handlers.wsgi import WSGIRequest def verify_shopify_webhook(request: WSGIRequest): shopify_hmac_header = request.META.get(settings.SHOPIFY_HMAC_HEADER) encoded_secret = settings.SHOPIFY_API_SECRET.encode("utf-8") digest = hmac.new( encoded_secret, request.body, digestmod=hashlib.sha256, ).digest() computed_hmac = base64.b64encode(digest) return hmac.compare_digest(computed_hmac, shopify_hmac_header.encode("utf-8"))
然后,创建一个接受传入webhook的视图,并使用verify_shopify_webhook(...)函数验证请求。
verify_shopify_webhook(...)
# views.py from django.http import HttpResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf import csrf_exempt from .utils import verify_shopify_webhook @method_decorator(csrf_exempt, name="dispatch") class ShopifyWebhookView(View): def post(self, request, *args, **kwargs): verified = verify_shopify_webhook(request=request) return HttpResponse(status=200 if verified else 403)
如果使用Django REST Framework,还可以将**APIView**用作
APIView
# views.py from rest_framework.views import APIView from rest_framework.response import Response from .utils import verify_shopify_webhook class ShopifyWebhookView(APIView): def post(self, request, *args, **kwargs): verified = verify_shopify_webhook(request=request) return Response(status=200 if verified else 403)
1条答案
按热度按时间dldeef671#
在
settings.py
文件中设置这两个变量然后,创建一个verify webhook函数,它接受Django请求作为参数
然后,创建一个接受传入webhook的视图,并使用
verify_shopify_webhook(...)
函数验证请求。如果使用Django REST Framework,还可以将**
APIView
**用作