Kar*_*arl 4 python django openssl webhooks
我正在尝试验证传入的 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
Run Code Online (Sandbox Code Playgroud)
这大致是我到目前为止使用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
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,由于我不正确的 Python 实现,哈希值永远不会明显匹配。
任何帮助/指针将不胜感激!
我相信它应该是这样的:
import hmac
import hashlib
digester = hmac.new(secret, request_body, hashlib.sha256)
calculated_signature = digester.hexdigest()
Run Code Online (Sandbox Code Playgroud)
一些注意事项:
str(json_data)等于请求正文。这几乎肯定会失败,因为 python 将使用repr它打印出内部字符串,这可能会留下一堆u"..."实际上不在响应中的虚假信息。 json.dumps不一定会做得更好,因为可能存在对 JSON 不重要但对 hmac 签名非常重要的空白差异。hmac 是你的朋友 :-)| 归档时间: |
|
| 查看次数: |
1760 次 |
| 最近记录: |