签名和请求

本文将会介绍如何生成接口的签名。

此签名生成过程用于确保请求的真实性和完整性。它将API密钥、请求参数、时间戳和密钥结合在一起生成签名,确保请求未被篡改。生成的签名用于header 的 x-signature 参数的值。

简要说明

  • 在生成接口签名时,商家需要在waas lite 后台提前创建或获取api key 和 secret key。
  • Waas Lite 所有的接口都是以 post的方式请求。
  • 通过HTTP POST提交数据时,需要设置请求头 Content-Type: application/json,以指示服务器请求体的内容为JSON格式。

签名生成过程

  • 签名所需数据:

签名所需数据:apikey、请求体json数据、时间戳,这三个数据组成签名字符串;secret key 则作为密钥对数据进行签名。

  • 准备请求体:
$body = [
  'B' => 123,
  'a' => 'Astring',
  'F' => 1203.44,
  'c' => null,
  'g' => 0,
  'dd' => true,
  'array' => [['key' => 123, 'val' => null]],
];
  • 将请求体编码为 json 格式:
// body to json string
{"B":123,"a":"Astring","F":1203.44,"c":null,"g":0,"dd":true,"array":[{"key":123,"val":null}]}
  • 构建签名字符串:

将API密钥、请求体的JSON字符串和当前时间戳结合起来,形成一个用于签名的字符串,示例如下

$your_apikey = 'your_api_key';
$your_secret_key = 'your_secret_key';
$timestamp = time(); // 1755850012
$body_to_json = json_encode($body);
$string_to_signature = $your_apikey . $body_to_json . $timestamp;
// eg:
// your_api_key{"B":123,"a":"Astring","F":1203.44,"c":null,"g":0,"dd":true,"array":[{"key":123,"val":null}]}1755850012
  • 使用 HMAC-SHA256 算法和secret key 对数据进行签名,并将生成的二进制签名进行Base64编码。
$binary = hash_hmac('sha256', $string_to_signature, $your_secret_key, true);
$signature = base64_encode($binary);
// $signature is: 9fW9S9PA6A6LbMsGl/eck0C4/4OLxl7EBaskflei9Ig=
  • 设置请求头,发送请求时,确保请求头包含以下数据
x-apikey: your_api_key
x-timestamp: 1755850012
x-signatrue: 9fW9S9PA6A6LbMsGl/eck0C4/4OLxl7EBaskflei9Ig=

完整的请求示例:


// Full example 
$body = [
  'B' => 123,
  'a' => 'Astring',
  'F' => 1203.44,
  'c' => null,
  'g' => 0,
  'dd' => true,
  'array' => [['key' => 123, 'val' => null]],
];
$body_to_json = json_encode($body);
// output: {"B":123,"a":"Astring","F":1203.44,"c":null,"g":0,"dd":true,"array":[{"key":123,"val":null}]}

$your_apikey = 'your_api_key';
$your_secret_key = 'your_secret_key';

$timestamp = time();
//$timestamp example: 1755850012

$string_to_signature = $your_apikey.$body_to_json.$timestamp;
//output:  your_api_key{"B":123,"a":"Astring","F":1203.44,"c":null,"g":0,"dd":true,"array":[{"key":123,"val":null}]}1755850012

$binary = hash_hmac('sha256', $string_to_signature, $your_secret_key, true);
$signature = base64_encode($binary);
// output: 9fW9S9PA6A6LbMsGl/eck0C4/4OLxl7EBaskflei9Ig=

$headers = [
  'Content-Type: application/json',  // Indicates that the request body is in JSON format
  'x-apikey: ' . $your_api_key,
  'x-timestamp: ' . $timestamp,
  'x-signature: ' . $signature,
];

$ch = curl_init('[https://example.com/api](https://example.com/api)');  // API URL
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_to_json);  // Request body
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);  // Request headers
$response = curl_exec($ch);  // Execute the request and get the response
curl_close($ch);