我正在尝试验证传入的 webhook,到目前为止,生成的哈希与 API 生成的测试哈希不匹配。
文档列出了以下 Ruby 示例,但我使用的是 Python/Django,因此任何帮助"转换"此功能将不胜感激!
拼音函数
# request_signature - the signature sent in Webhook-Signature
# request_body - the JSON body of the webhook request
# secret - the secret for the webhook endpoint
require "openssl"
digest = OpenSSL::Digest.new("sha256")
calculated_signature = OpenSSL::HMAC.hexdigest(digest, secret, request_body)
if calculated_signature == request_signature
# Signature ok!
else
# Invalid signature. Ignore the webhook and return 498 Token Invalid
end
这大致是我到目前为止使用 https://docs.python.org/3/library/hashlib.html 自己整理的内容。
蟒蛇尝试
import hashlib
secret = "xxxxxxxxxxxxxxxxxx"
json_data = {json data}
h = hashlib.new('sha256')
h.update(secret)
h.update(str(json_data))
calculated_signature = h.hexdigest()
if calculated_signature == webhook_signature:
do_something()
else:
return 498
当我运行上述内容时,由于我的 Python 实现不正确,哈希显然永远不会匹配。
任何帮助/指示将不胜感激!
我相信
应该是这样的:
import hmac
import hashlib
digester = hmac.new(secret, request_body, hashlib.sha256)
calculated_signature = digester.hexdigest()
一些注意事项:
- 使用实际的请求正文。 不要依赖
str(json_data)
等于请求正文。 这几乎肯定会失败,因为 python 将使用repr
打印出内部字符串,这可能会留下一堆实际上不在响应中的虚假u"..."
。json.dumps
不一定会做得更好,因为可能存在对 JSON 无关紧要但对 HMAC 签名非常重要的空格差异。 -
hmac
是你的朋友:-)