[英]Shopify Webhooks Hmac Python verification fails
我正在嘗試驗證從 Shopify 收到的 webhook,但 Hmac 驗證失敗。
def verify_webhook(data, hmac_header):
digest = hmac.new(SECRET.encode('utf-8'), data, hashlib.sha256).digest()
computed_hmac = base64.b64encode(digest)
return hmac.compare_digest(computed_hmac, hmac_header.encode('utf-8'))
@app.route('/productCreation', methods=['POST'])
def productCreation():
data = request.data
verified = verify_webhook(
data, request.headers.get('X-Shopify-Hmac-SHA256'))
if(verified):
return ("Success", 200)
return("Integrity error", 401)
獲取錯誤為
hash = hmac.new(SECRET.encode('utf-8'), body.encode('utf-8'), hashlib.sha256)
AttributeError: 'bytes' object has no attribute 'encode'
有人能幫忙嗎? 我正在為此開發 Flask 應用程序。
您收到一個屬性錯誤,這意味着您的body對象不是字符串(encode() 用於類似字符串的對象),如錯誤消息中所述,它是一個類似“字節”的對象。 卸下.encode('utf-8')
從體。
使用Shopify 的 Flask 示例時,我遇到了同樣的錯誤
from flask import Flask, request, abort
import hmac
import hashlib
import base64
app = Flask(__name__)
SECRET = 'hush'
def verify_webhook(data, hmac_header):
digest = hmac.new(SECRET, data.encode('utf-8'), hashlib.sha256).digest()
computed_hmac = base64.b64encode(digest)
return hmac.compare_digest(computed_hmac, hmac_header.encode('utf-8'))
@app.route('/webhook', methods=['POST'])
def handle_webhook():
data = request.get_data()
verified = verify_webhook(data, request.headers.get('X-Shopify-Hmac-SHA256'))
if not verified:
abort(401)
# process webhook payload
# ...
return ('', 200)
為了讓它工作,我必須通過以下方式修改 verify_webhook:
最終代碼
from flask import Flask, request, abort
import hmac
import hashlib
import base64
app = Flask(__name__)
SECRET = 'hush'
def verify_webhook(data, hmac_header):
digest = hmac.new(SECRET.encode('utf-8'), data, hashlib.sha256).digest()
computed_hmac = base64.b64encode(digest)
return hmac.compare_digest(computed_hmac, hmac_header.encode('utf-8'))
@app.route('/webhook', methods=['POST'])
def handle_webhook():
data = request.get_data()
verified = verify_webhook(data, request.headers.get('X-Shopify-Hmac-SHA256'))
if not verified:
abort(401)
# process webhook payload
# ...
return ('', 200)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.