使用 Flask 进行 Shopify Webhook HMAC 验证

Shopify Webhook HMAC Validation With Flask

我正在尝试验证收到的 Webhook 是否来自 Shopify。他们有 this 文档,但它不起作用(出现类型错误)。

这是我目前所拥有的。它不会产生任何错误,但 verify_webhook 函数总是 returns false。

from flask import Flask, request, abort
import hmac
import hashlib
import base64

app = Flask(__name__)

SECRET = '...'


def verify_webhook(data, hmac_header):    
    digest = hmac.new(SECRET.encode('utf-8'), data, hashlib.sha256).digest()
    genHmac = base64.b64encode(digest)

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


@app.route('/', methods=['POST'])
def hello_world(request):
    print('Received Webhook...')

    data = request.get_data()
    hmac_header = request.headers.get('X-Shopify-Hmac-SHA256')
    verified = verify_webhook(data, hmac_header)
    
    if not verified:
        return 'Integrity of request compromised...', 401
    
    print('Verified request...')


if __name__ == '__main__':
    app.run()

我做错了什么?

答案:

from flask import Flask, request, abort
import hmac
import hashlib
import base64

app = Flask(__name__)

SECRET = '...'


def verify_webhook(data, hmac_header):    
    digest = hmac.new(SECRET.encode('utf-8'), data, hashlib.sha256).digest()
    genHmac = base64.b64encode(digest)

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


@app.route('/', methods=['POST'])
def hello_world(request):
    print('Received Webhook...')

    data = request.data # NOT request.get_data() !!!!!
    hmac_header = request.headers.get('X-Shopify-Hmac-SHA256')
    verified = verify_webhook(data, hmac_header)
    
    if not verified:
        return 'Integrity of request compromised...', 401
    
    print('Verified request...')


if __name__ == '__main__':
    app.run()

问题在 data = request.get_data() 行。