如何在Django中验证Shopify webhook?

aamkag61  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(163)

我如何验证从Shopify传入的webhook?Shopify提供了一个(Flask的)python实现,但我如何在Django/DRF中做这件事?

dldeef67

dldeef671#

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(...)函数验证请求。

# 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**用作

# 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)

相关问题