鑑權與簽名
所有開放 API 請求需通過 HMAC-SHA256 簽名進行身份驗證。
簽名算法
| 項目 | 說明 |
|---|---|
| 算法 | HMAC-SHA256 |
| 簽名函數 | hash_hmac('sha256', payload, app_secret) |
| 簽名結果 | Hex 編碼(小寫) |
Payload 規範
- payload 為原始 JSON 字符串
- JSON 不進行排序
- 不進行格式化(不 pretty print)
- 不進行 urlencode
- 推薦使用壓縮後的單行 JSON
重要
JSON 字段順序、空格、換行必須與簽名時完全一致。簽名放在請求頭 x-chat-signature 中。
代碼示例
PHP
<?php
$payload =
'{"appid":"1b621280becdb0fa3d3e041ff69e1e1f","sbs":"1001","timestamp":1767772879,"ranstr":"4ad0faec14a58112","kefu_id":"10078","ip":""}';
$appSecret = 'YOUR_APP_SECRET';
$sign = hash_hmac('sha256', $payload, $appSecret);
echo $sign;
Python 3
import hmac
import hashlib
payload = '{"appid":"1b621280becdb0fa3d3e041ff69e1e1f","sbs":"1001","timestamp":1767772879,"ranstr":"4ad0faec14a58112","kefu_id":"10078","ip":""}'
app_secret = 'YOUR_APP_SECRET'
sign = hmac.new(
app_secret.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
print(sign)
Go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
)
func main() {
payload := `{"appid":"1b621280becdb0fa3d3e041ff69e1e1f","sbs":"1001","timestamp":1767772879,"ranstr":"4ad0faec14a58112","kefu_id":"10078","ip":""}`
appSecret := "YOUR_APP_SECRET"
mac := hmac.New(sha256.New, []byte(appSecret))
mac.Write([]byte(payload))
sign := hex.EncodeToString(mac.Sum(nil))
fmt.Println(sign)
}
Java (JDK 8+)
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class SignExample {
public static void main(String[] args) throws Exception {
String payload = "{\"appid\":\"1b621280becdb0fa3d3e041ff69e1e1f\",\"sbs\":\"1001\",\"timestamp\":1767772879,\"ranstr\":\"4ad0faec14a58112\",\"kefu_id\":\"10078\",\"ip\":\"\"}";
String appSecret = "YOUR_APP_SECRET";
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"));
byte[] hash = mac.doFinal(payload.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
System.out.println(sb.toString());
}
}
Node.js
const crypto = require('crypto')
const payload = '{"appid":"1b621280becdb0fa3d3e041ff69e1e1f","sbs":"1001","timestamp":1767772879,"ranstr":"4ad0faec14a58112","kefu_id":"10078","ip":""}'
const appSecret = 'YOUR_APP_SECRET'
const sign = crypto
.createHmac('sha256', appSecret)
.update(payload)
.digest('hex')
console.log(sign)