首页 > 解决方案 > 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

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

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 等效项(假设有一个),我将不胜感激。

标签: javascriptphp

解决方案


最简单的等价物应该是:

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

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

所以提供的秘密应该已经是十六进制,否则hex2bin会抛出异常


推荐阅读