编辑代码

<?php
// 设置字符编码
header('Content-Type: text/html; charset=utf-8');

// 密钥参数
$ak = ""; // 此处填写您的ak
$sk = ""; // 此处填写您的sk

// terminalId可用UUID生成,每个客户端每次发送请求不需要变化
$terminal_id = bin2hex(random_bytes(16));

// 当请求体为空,使用"{}"作为默认payload进行签名计算
$default_empty_payload = "{}";

// content-type
$ct = "application/json; charset=utf-8";

// ************* 步骤 1:准备签名计算相关参数 *************
$host = "api-smbcloud.tplinkcloud.com.cn";
$endpoint = "https://" . $host;
$algorithm = "HmacSHA256";
$timestamp = time();
$nonce = bin2hex(random_bytes(16));
$method = "POST";
// 请求路径,根据具体接口进行替换
$path = "/tums/open/resource/v1/getPagedRootRegions";
$payload = json_encode(array("start" => 0, "limit" => 10, "needDevNum" => 0));

// ************* 步骤 2:拼接待签名字符串 *************
$hashed_request_payload = hash_hmac("sha256", $payload, "", true);
$credential_scope = $method . " " . $path . " " . "tp-link_request";
$string_to_sign = $algorithm . "\n" .
                  $timestamp . "\n" .
                  $credential_scope . "\n" .
                  $hashed_request_payload;

// ************* 步骤 3:计算签名 *************
function sign($key, $msg) {
    return hash_hmac("sha256", $msg, $key, true);
}
$secret_date = sign($sk, $timestamp);
$secret_service = sign($secret_date, $path);
$secret_signing = sign($secret_service, "tp-link");
$signature = hash_hmac("sha256", $string_to_sign, $secret_signing);

// ************* 步骤 4:拼接 Authorization *************
$authorization = "Timestamp=" . $timestamp . "," .
                 "Nonce=" . $nonce . "," .
                 "AccessKey=" . $ak . "," .
                 "Signature=" . bin2hex($signature) . "," .
                 "TerminalId=" . $terminal_id;

// 打印Authorization头部
echo "Authorization: " . $authorization . "\n";

// 打印CURL命令
echo 'curl -X POST ' . $endpoint . $path .
     ' -H "X-Authorization: ' . $authorization . '"' .
     ' -H "Content-Type: ' . $ct . '"' .
     ' -H "Host: ' . $host . '"' .
     " -d '" . $payload . "'\n";
?>