将请求数据转换成json字符串,注意加上参数:
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
JSON_UNESCAPED_SLASHES:不要编码 /
JSON_UNESCAPED_UNICODE:以字面编码多字节 Unicode 字符(默认是编码成 \uXXXX)。
本代码写于Laravel框架,其他框架根据实际情况获取请求头和请求数据
/**
* @param array $data webHook请求数据
* @param array $header webhook请求头
* @throws BusinessException 验证错误抛出异常
*/
protected function checkSignature(array $data, array $header)
{
$secret = 'xxxxxxwebhook设置的secret秘钥xxxxxx';
if (!empty($header['x-hub-signature-256'][0])) {
$signature = $header['x-hub-signature-256'][0];
$hash = "sha256=" . hash_hmac('sha256', json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $secret);
if (strcmp($signature, $hash) != 0) {
throw new BusinessException('异常!' . $hash . '!=' . $signature);
}
} else {
throw new BusinessException('异常!');
}
}