PHP 中的请求签名
本文介绍了 PHP 中 请求签名 的示例实现。
# 依赖项
生成签名不需要任何外部依赖项。
# 示例
以下简单示例实现了 请求签名 指南中描述的算法。最重要的是使用 hash_hmac
函数,并使用合适的 sha256
算法,以正确的顺序给出参数:method
、url
、timestamp
、body
。
method
参数应以大写字母提供,uri
应仅包含 URL 中的路径,而不是完整的 URL 地址。完整的 URL 地址应转换为 /webhook?a=1
。
如果算法正常工作,它应该生成与以下给出的签名相同的签名:56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762
,以下列参数为准
-
apiSecret=SECRET
-
method=POST
-
uri=http://demo.example.com/webhook?a=1
-
timestamp=1563276169752
-
body=['a' => 1]
<?php
$secret = 'SECRET';
function generateSignature($apiSecret, $method, $url, $timestamp, $body)
{
$parsedUrl = parse_url($url);
$uri = $parsedUrl['path'] ?? '';
if (isset($parsedUrl['query'])) {
$uri .= '?' . $parsedUrl['query'];
}
$data = $method . $uri . $timestamp;
if ($body) {
$data .= json_encode($body);
}
$hmac = hash_hmac('sha256', $data, $apiSecret);
return $hmac;
}
$expectedSignature = '56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762';
$generatedSignature = generateSignature(
'SECRET',
'POST',
'http://demo.example.com/webhook?a=1',
'1563276169752',
['a' => 1]
);
echo $expectedSignature === $generatedSignature ? 'true' : 'false';
# 用法
运行
php index.php
上述代码应在控制台中打印 true
。