PHP将简单的3行JavaScript转换为等效的PHP



我收到了几行JavaScript,需要将其转换为等效的PHP。作为一名JavaScript开发人员,我正在努力解决这个问题。以下是我提供的JavaScript示例:

const crypto = require('crypto')
const secret_in_hex = Buffer.from(secret, 'hex');
const hash = crypto.createHmac('sha512', secret_in_hex)
.update(body)
.digest('hex')
// Compare hash with the received X-Onfleet-Signature in raw bytes

我使用API在PHP中设置Webhook接收器的文档提到:

Each webhook request contains a signature from Onfleet in X-Onfleet-Signature header. To authenticate the webhook request received on your webhook server, you will need to validate against this header. To validate against X-Onfleet-Signature, you will need to compare its value with an HMAC you have generated using the hexadecimal format of your webhook secrets and the full body of the webhook POST request in raw bytes.

我假设我将使用hash_hmac函数,可能还有bin2hex函数,但在这一点上完全被难住了,如果有人能向我展示与上述JavaScript等效的PHP(假设有(,我将不胜感激。

最简单的等价物应该是:

$secretInHex = hex2bin($secret);
$hash = hash_hmac('sha512', $body, $secretInHex);

您应该注意,hex2bin函数不会将十六进制数转换为二进制数,而是对十六进制编码的二进制字符串进行解码

因此,提供的秘密应该已经是十六进制,否则hex2bin将抛出异常

最新更新