跳到主内容
大鹏云 大鹏云 DAPENG CLOUD
首页 · 帮助中心 · API 开发文档 · API 开发者文档(三):签名示例代码(PHP / Python / Node.js)

API 开发者文档(三):签名示例代码(PHP / Python / Node.js)

PHP 签名示例

<?php
$accessKey = 'AKID8F2C4A91B7D34E6F0A1C2B3D';
$secret    = '在此填入你的 64 位 Secret';
$timestamp = (string) time();
$body      = json_encode(array('product_id' => 3, 'cycle' => 'month'), JSON_UNESCAPED_UNICODE);
$signingKey = hash('sha256', $secret);                     // Secret 的 SHA-256 十六进制
$signature  = hash_hmac('sha256', $timestamp . "\n" . $body, $signingKey);
$ch = curl_init('https://www.dapengcloud.com/api.php/v1/order/create');
curl_setopt_array($ch, array(
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $body,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => array(
        'Content-Type: application/json; charset=utf-8',
        'X-Access-Key: ' . $accessKey,
        'X-Timestamp: '  . $timestamp,
        'X-Signature: '  . $signature,
    ),
));
$response = curl_exec($ch);
curl_close($ch);
echo $response;

Python 3 签名示例

import hashlib, hmac, json, time, requests
access_key = "AKID8F2C4A91B7D34E6F0A1C2B3D"
secret     = "在此填入你的 64 位 Secret"
url        = "https://www.dapengcloud.com/api.php/v1/order/create"
body = json.dumps({"product_id": 3, "cycle": "month"}, separators=(",", ":"), ensure_ascii=False)
ts   = str(int(time.time()))
signing_key = hashlib.sha256(secret.encode("utf-8")).hexdigest()
signature   = hmac.new(signing_key.encode("utf-8"), (ts + "\n" + body).encode("utf-8"), hashlib.sha256).hexdigest()
resp = requests.post(url, data=body.encode("utf-8"), headers={
    "Content-Type": "application/json; charset=utf-8",
    "X-Access-Key": access_key,
    "X-Timestamp": ts,
    "X-Signature": signature,
})
print(resp.status_code, resp.text)

Node.js 签名示例

const crypto = require('crypto');
const https  = require('https');
const accessKey = 'AKID8F2C4A91B7D34E6F0A1C2B3D';
const secret    = '在此填入你的 64 位 Secret';
const body      = JSON.stringify({ product_id: 3, cycle: 'month' });
const ts        = String(Math.floor(Date.now() / 1000));
const signingKey = crypto.createHash('sha256').update(secret).digest('hex');
const signature  = crypto.createHmac('sha256', signingKey).update(ts + '\n' + body).digest('hex');
const req = https.request('https://www.dapengcloud.com/api.php/v1/order/create', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
    'X-Access-Key': accessKey,
    'X-Timestamp': ts,
    'X-Signature': signature,
    'Content-Length': Buffer.byteLength(body),
  },
}, res => {
  let data = '';
  res.on('data', c => data += c);
  res.on('end', () => console.log(res.statusCode, data));
});
req.write(body);
req.end();

GET 请求签名说明

GET 请求签名:无请求体时,payload 为 timestamp + "\n"。例如 hmac_sha256(sha256(secret), "1761000000\n")。

三段示例均遵循同一流程:先用 SHA-256 计算 Secret 的十六进制哈希作为 HMAC 密钥,再对「时间戳 + 换行符 + 原始请求体」计算 HMAC-SHA256,最后将 Access Key、时间戳、签名放入请求头。
这篇文章对你有帮助吗?