【问题标题】:Generate Signature for API call with php使用 php 为 API 调用生成签名
【发布时间】:2014-09-03 20:35:28
【问题描述】:

我有一个 API 文档。在创建请求的签名时遇到问题。我有以下关于如何创建签名的程序。有人可以通过以下过程的示例帮助我:

生成签名创建签名

Create the canonical zed query string that you need later in this procedure:
    Sort the UTF-8 query string components by parameter name with natural byte ordering. The parameters can come from the GET URI or from the POST body (when Content-Type is application/x-www-form-urlencoded).
    URL encode the parameter name and values
    Concatinate name and values to a single string (eg. var1value1var2value2)
Calculate an RFC 2104-compliant HMAC with the string you just created, your API Access Key as the key, and SHA1 as the hash algorithm.
Make the resulting value base64 encoded.
Use the Resulting value as the value of the Signature request parameter

编辑:

这是文档中的示例输出:

https://domain.com/api.php?action=checkDomain&version=20090622&keyId=123456 &name=glo0000w.com&signature=fvatTFVwRNF1cyH%2Fj%2Flaig8QytY%3D

以下是我尝试做的,但没有成功

<?php  
$sig = urlencode('actioncheckDomainversion20090622keyId123456nameglo0000w.com');
$sig = hash_hmac('sha1', $sig, '123456');
$sig = base64_encode($sig);
?>

有人可以帮我实现用php生成签名的程序吗?谢谢。

【问题讨论】:

  • 您遗漏了“将结果值设为 base64 编码”。 $sig = base64_encode($sig);
  • 与您之前提出的问题重复
  • @RocketHazmat 我添加了它,但仍然出现错误:签署 UPL-TYQTSBHIYGRFHKXEPJNPELGY 的请求错误

标签: php api


【解决方案1】:

首先,您没有像应有的那样按键对参数进行排序。

$p = array(
    'action' => 'checkDomain',
    'version' => '20090622',
    'keyId' => 123456,
    'name' => 'glo0000w.com',
);

ksort($p);
$string = '';
foreach($p as $oneKey=>$oneValue)
    $string .= urlencode($oneKey) . urlencode($oneValue);

您的另一个问题是您致电hash_hmac()。默认情况下,它返回一个十六进制字符串,并且在 base64 编码中没有意义。此外,生成的输出比示例要长得多。我很确定这是一个错误。

相反,您想使用可选的第四个参数per the hash_hmac docs 和base64 编码那个 值来生成二进制输出:

$hash = hash_hmac('sha1', $string, '123456', true);
$sig = base64_encode($hash);

最后,我怀疑您可能使用了错误的访问密钥进行签名。您使用了keyId 值,它总是不同于accessKey。 (可能在示例中除外。)

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 2011-03-27
    • 2023-01-12
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2014-04-06
    • 2020-07-19
    相关资源
    最近更新 更多