python 用于Shopify Webhook的HMAC验证的Python视图装饰器。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 用于Shopify Webhook的HMAC验证的Python视图装饰器。相关的知识,希望对你有一定的参考价值。

import hashlib, base64, hmac, json, settings

def shopify_webhook(f):
  """
  A decorator thats checks and validates a Shopify Webhook request.
  """

  def _hmac_is_valid(body, secret, hmac_to_verify):
    hash            = hmac.new(body, secret, 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:
      return HttpResponseBadRequest()

    # Verify the HMAC.
    if not _hmac_is_valid(request.body, settings.SHOPIFY_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

以上是关于python 用于Shopify Webhook的HMAC验证的Python视图装饰器。的主要内容,如果未能解决你的问题,请参考以下文章

Shopify 在 Scala 中验证 webhook 调用

接收不到shopify webhook 发送post请求

如何捕获 Shopify Webhook 发送的 HTTP POST 请求

卸载shopify应用程序的任何回调或设置

Shopify 订单网络挂钩

在 Shopify 上使用 ngrok 的 Django