认证与签名
每个请求都必须携带下面四个请求头。缺少任意一个,或时间戳、随机串、签名不合法,请求都会被拒绝。
| 请求头 | 必填 | 说明 |
|---|---|---|
x-user-id | 是 | 用户 ID,在控制台「平台配置」页查看 |
x-timestamp | 是 | 秒级 Unix 时间戳,与服务器相差不超过 300 秒 |
x-nonce | 是 | 随机字符串,8–64 位;同一用户的同一个值 10 分钟内不能重复 |
x-signature | 是 | HMAC-SHA256 签名,小写十六进制 |
签名算法
把下面五段按顺序直接拼接,不需要分隔符。请求路径不包含域名和查询串。
method + path + userId + timestamp + nonce以 API 密钥作为 HMAC 密钥,对上面这串做 HMAC-SHA256,结果转成小写十六进制,放入 x-signature。
签名串里的 path 是完整请求路径,包含 /openapi 前缀,例如账号列表是 /openapi/account。
GET/openapi/account100117623801234f8b7c1a92e4d5ffae21时间戳与随机串
x-timestamp 使用秒级 Unix 时间,不要用毫秒;x-nonce 每次请求重新生成,长度 8–64 位,10 分钟内不可复用。
代码示例
bash
USER_ID="1001"
API_KEY="gxk_填写你的密钥"
METHOD="GET"
API_PATH="/openapi/account"
TS=$(date +%s)
NONCE=$(openssl rand -hex 12)
SIGN=$(printf '%s' "${METHOD}${API_PATH}${USER_ID}${TS}${NONCE}" \
| openssl dgst -sha256 -hmac "$API_KEY" -hex | awk '{print $NF}')
curl -s "https://gxbot.org${API_PATH}?page=1&pageSize=20" \
-H "x-user-id: ${USER_ID}" \
-H "x-timestamp: ${TS}" \
-H "x-nonce: ${NONCE}" \
-H "x-signature: ${SIGN}"js
import crypto from 'node:crypto'
const BASE = 'https://gxbot.org'
const userId = '1001'
const apiKey = 'gxk_填写你的密钥'
const method = 'GET'
const path = '/openapi/account'
const timestamp = String(Math.floor(Date.now() / 1000))
const nonce = crypto.randomBytes(12).toString('hex')
const signature = crypto
.createHmac('sha256', apiKey)
.update(method + path + userId + timestamp + nonce)
.digest('hex')
const res = await fetch(`${BASE}${path}?page=1&pageSize=20`, {
headers: {
'x-user-id': userId,
'x-timestamp': timestamp,
'x-nonce': nonce,
'x-signature': signature,
},
})
console.log(await res.json())python
import hashlib
import hmac
import secrets
import time
import requests
BASE = "https://gxbot.org"
USER_ID = "1001"
API_KEY = "gxk_填写你的密钥"
method, path = "GET", "/openapi/account"
timestamp = str(int(time.time()))
nonce = secrets.token_hex(12)
message = method + path + USER_ID + timestamp + nonce
signature = hmac.new(
API_KEY.encode(), message.encode(), hashlib.sha256
).hexdigest()
resp = requests.get(
BASE + path,
params={"page": 1, "pageSize": 20},
headers={
"x-user-id": USER_ID,
"x-timestamp": timestamp,
"x-nonce": nonce,
"x-signature": signature,
},
timeout=10,
)
print(resp.json())go
package main
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"time"
)
func main() {
const base = "https://gxbot.org"
const userID = "1001"
const apiKey = "gxk_填写你的密钥"
method, path := http.MethodGet, "/openapi/account"
timestamp := fmt.Sprint(time.Now().Unix())
buf := make([]byte, 12)
if _, err := rand.Read(buf); err != nil {
panic(err)
}
nonce := hex.EncodeToString(buf)
mac := hmac.New(sha256.New, []byte(apiKey))
mac.Write([]byte(method + path + userID + timestamp + nonce))
signature := hex.EncodeToString(mac.Sum(nil))
req, _ := http.NewRequest(method, base+path+"?page=1&pageSize=20", nil)
req.Header.Set("x-user-id", userID)
req.Header.Set("x-timestamp", timestamp)
req.Header.Set("x-nonce", nonce)
req.Header.Set("x-signature", signature)
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(resp.Status, string(body))
}java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static void main(String[] args) throws Exception {
String base = "https://gxbot.org";
String userId = "1001";
String apiKey = "gxk_填写你的密钥";
String method = "GET";
String path = "/openapi/account";
String timestamp = String.valueOf(Instant.now().getEpochSecond());
byte[] buf = new byte[12];
new SecureRandom().nextBytes(buf);
String nonce = HexFormat.of().formatHex(buf);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(apiKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] digest = mac.doFinal(
(method + path + userId + timestamp + nonce).getBytes(StandardCharsets.UTF_8)
);
String signature = HexFormat.of().formatHex(digest);
HttpRequest req = HttpRequest.newBuilder(URI.create(base + path + "?page=1&pageSize=20"))
.header("x-user-id", userId)
.header("x-timestamp", timestamp)
.header("x-nonce", nonce)
.header("x-signature", signature)
.GET()
.build();
HttpResponse<String> res = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.body());
}
}php
<?php
$base = 'https://gxbot.org';
$userId = '1001';
$apiKey = 'gxk_填写你的密钥';
$method = 'GET';
$path = '/openapi/account';
$timestamp = (string) time();
$nonce = bin2hex(random_bytes(12));
$signature = hash_hmac(
'sha256',
$method . $path . $userId . $timestamp . $nonce,
$apiKey
);
$ch = curl_init($base . $path . '?page=1&pageSize=20');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'x-user-id: ' . $userId,
'x-timestamp: ' . $timestamp,
'x-nonce: ' . $nonce,
'x-signature: ' . $signature,
],
]);
echo curl_exec($ch);rust
// Cargo.toml:
// hmac = "0.12" sha2 = "0.10" hex = "0.4" rand = "0.8"
// reqwest = { version = "0.12", features = ["blocking"] }
use hmac::{Hmac, Mac};
use rand::Rng;
use sha2::Sha256;
type HmacSha256 = Hmac<Sha256>;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let base = "https://gxbot.org";
let user_id = "1001";
let api_key = "gxk_填写你的密钥";
let method = "GET";
let path = "/openapi/account";
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_secs()
.to_string();
let nonce: String = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(24)
.map(char::from)
.collect();
let mut mac = HmacSha256::new_from_slice(api_key.as_bytes())?;
mac.update(format!("{method}{path}{user_id}{timestamp}{nonce}").as_bytes());
let signature = hex::encode(mac.finalize().into_bytes());
let body = reqwest::blocking::Client::new()
.get(format!("{base}{path}?page=1&pageSize=20"))
.header("x-user-id", user_id)
.header("x-timestamp", timestamp)
.header("x-nonce", nonce)
.header("x-signature", signature)
.send()?
.text()?;
println!("{body}");
Ok(())
}c
// 编译:cc main.c -lcurl -lcrypto -o main
#include <curl/curl.h>
#include <openssl/hmac.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static void hex_encode(const unsigned char *in, size_t len, char *out) {
static const char *digits = "0123456789abcdef";
for (size_t i = 0; i < len; i++) {
out[i * 2] = digits[in[i] >> 4];
out[i * 2 + 1] = digits[in[i] & 0x0f];
}
out[len * 2] = '\0';
}
int main(void) {
const char *base = "https://gxbot.org";
const char *user_id = "1001";
const char *api_key = "gxk_填写你的密钥";
const char *method = "GET";
const char *path = "/openapi/account";
long timestamp = time(NULL);
unsigned char raw[12];
FILE *urandom = fopen("/dev/urandom", "rb");
fread(raw, 1, sizeof(raw), urandom);
fclose(urandom);
char nonce[25];
hex_encode(raw, sizeof(raw), nonce);
char message[512];
snprintf(message, sizeof(message), "%s%s%s%ld%s",
method, path, user_id, timestamp, nonce);
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digest_len = 0;
HMAC(EVP_sha256(), api_key, (int) strlen(api_key),
(const unsigned char *) message, strlen(message),
digest, &digest_len);
char signature[EVP_MAX_MD_SIZE * 2 + 1];
hex_encode(digest, digest_len, signature);
char url[256], h_user[64], h_ts[64], h_nonce[64], h_sig[256];
snprintf(url, sizeof(url), "%s%s?page=1&pageSize=20", base, path);
snprintf(h_user, sizeof(h_user), "x-user-id: %s", user_id);
snprintf(h_ts, sizeof(h_ts), "x-timestamp: %ld", timestamp);
snprintf(h_nonce, sizeof(h_nonce), "x-nonce: %s", nonce);
snprintf(h_sig, sizeof(h_sig), "x-signature: %s", signature);
CURL *curl = curl_easy_init();
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, h_user);
headers = curl_slist_append(headers, h_ts);
headers = curl_slist_append(headers, h_nonce);
headers = curl_slist_append(headers, h_sig);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_perform(curl);
printf("\n");
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return 0;
}密钥安全
API 密钥等同于账号操作权限,只应保存在你的服务端。不要写进前端、App 或公开仓库;一旦泄露,立即在控制台重置密钥。
