我一直在寻找一种用Python和Flask实现selly.gg商家网站中的HMAC验证的方法。
所以,selly的开发文档给出了以下示例来验证HMAC签名(使用PHP和ruby):https://developer.selly.gg/?php#signing-validating (代码如下:)
PHP:
<?php
$signature = hash_hmac('sha512', json_encode($_POST), $secret);
if hash_equals($signature, $signatureFromHeader) {
// Webhook is valid
}
?>
红宝石:
signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha512'), secret, payload.to_json)
is_valid_signature = ActiveSupport::SecurityUtils.secure_compare(request.headers['X-Selly-Signature'], signature)
目前我所了解的是:它们不使用base64进行编码(就像shopify和其他一些平台一样),而是使用SHA-512。它将秘密代码与json响应数据一起编码,最后请求头是“X-Selly-Signature”。
我已经编写了以下代码(基于Shopify用于HMAC签名的代码 https://help.shopify.com/en/api/getting-started/webhooks):
SECRET = "secretkeyhere"
def verify_webhook(data, hmac_header):
digest = hmac.new(bytes(SECRET, 'ascii'), bytes(json.dumps(data), 'utf8'), hashlib.sha512).hexdigest()
return hmac.compare_digest(digest, hmac_header)
try:
responsebody = request.json #line:22
status = responsebody['status']#line:25
except Exception as e:
print(e)
return not_found()
print("X Selly sign: " + request.headers.get('X-Selly-Signature'))
verified = verify_webhook(responsebody, request.headers.get('X-Selly-Signature'))
print(verified)
然而,Selly有一个Webhook模拟器,即使具有正确的密钥和有效请求,verify_webhook也将始终返回False。我尝试联系Selly支持,但他们不能为我提供更多帮助。
您可以在以下地址测试Webhook模拟器: https://selly.io/dashboard/{your账户}/developer/webhook/simulate