跳至主要内容

簽名生成

⚠️ 合約與現貨的簽名方式不同

本頁說明的是合約 API(f-api)。現貨 API(s-api)使用不同的待簽名串,請參見現貨:簽名生成。把現貨的簽名程式碼用在合約上(或反過來)是導致 invalid signature 最常見的原因。

合約(本頁)現貨
待簽名串X#path[#query][#body]X#METHOD#path[#query][#body]
X(請求頭部分)validate-appkey=..&validate-timestamp=..(2 項)validate-algorithms=..&validate-appkey=..&validate-recvwindow=..&validate-timestamp=..(4 項)
待簽名串是否包含 HTTP 方法否是(大寫)
必填請求頭appkey、timestamp、signaturealgorithms、appkey、recvwindow、timestamp、signature

待簽名串不包含域名,因此兩個生產域名使用相同的簽名。

1. 請求頭​

請求頭必填說明
validate-appkey是你的 API key
validate-timestamp是發送請求時的 Unix 時間,單位為毫秒(13 位)
validate-signature是按下文計算出的簽名
validate-recvwindow否有效時間窗口,單位為毫秒。預設 5000;大於 60000 的值按 60000 處理。不參與待簽名串
validate-algorithms否簽名演算法,預設 HmacSHA256(建議不發送此請求頭)。如發送,須以該演算法簽名;無法識別的名稱按 HmacSHA256 處理。不參與待簽名串

如 validate-timestamp 與伺服器時間的差值大於 recvwindow,請求會被拒絕。

⛔ 不要發送 validate-signversion

不支援此請求頭。帶上它的請求會以 invalid signature 或 HTTP 400 失敗。

2. 構建待簽名串​

original = X + "#" + path [+ "#" + query] [+ "#" + body]
X = "validate-appkey=" + appkey + "&validate-timestamp=" + timestamp
  • X —— 只包含這兩項,且順序固定,請求頭名稱不帶任何前綴。即使你發送了 validate-algorithms 或 validate-recvwindow,也不要加入這裏。
  • path —— 實際發送的請求路徑,以 /az/future/... 開頭,不含域名,也不含 ?。例如:/az/future/trade/v1/order/create。
  • query —— 僅當 URL 帶有查詢參數時加入:按 key 的 ASCII 順序排序(大寫字母排在小寫字母之前),以 key=value 形式用 & 連接。使用未編碼的值(伺服器以解碼後的值簽名;傳輸中的 a%2Cb 按 a,b 簽名)。同一個 key 出現多次時,只取第一個值。參數一律以 key=value 形式發送(不要有不帶 = 的 key)。
  • body —— 僅當請求帶有請求體時加入:與實際發送完全相同的請求體字串,逐位元組一致。不排序、不重新格式化、不做 URL 解碼。application/json 與 application/x-www-form-urlencoded 請求體同樣適用。空物件 {} 也是請求體,必須拼接。
  • 不存在的部分連同其 # 一併省略——待簽名串絕不能以 # 結尾。
請求包含待簽名串
無查詢參數、無請求體X#path
僅查詢參數X#path#query
僅請求體X#path#body
查詢參數和請求體X#path#query#body

3. 計算簽名​

signature = hex( HMAC-SHA256( key = secretKey, message = original ) )

除非你在 validate-algorithms 中指定了其他支援的演算法,否則使用 HMAC-SHA256。secretKey 字串按原樣使用(UTF-8)。輸出為小寫或大寫的 hex(不是 Base64),放入 validate-signature 請求頭。

4. 測試向量​

請用以下數值檢驗你的實現。你的程式碼必須產生完全相同的 original 和 signature。

appKey : 3976eb88-76d0-4f6e-a6b2-a57980770085
secretKey : bc6630d0231fda5cd98794f52c4998659beda290
timestamp : 1641446237201

帶查詢參數的 GET —— GET /az/future/user/v1/balance/detail?coin=usdt

original : validate-appkey=3976eb88-76d0-4f6e-a6b2-a57980770085&validate-timestamp=1641446237201#/az/future/user/v1/balance/detail#coin=usdt
signature : 4b9bb7601ae3dd2b1134ee5f8458715c2616fa2a9c0b96fc5899bbe4a5d4e255

帶 JSON 請求體的 POST —— POST /az/future/trade/v1/order/create

body : {"symbol":"btc_usdt","orderSide":"BUY","orderType":"LIMIT","positionSide":"LONG","origQty":"0.001","price":"70000","timeInForce":"GTC"}
original : validate-appkey=3976eb88-76d0-4f6e-a6b2-a57980770085&validate-timestamp=1641446237201#/az/future/trade/v1/order/create#{"symbol":"btc_usdt","orderSide":"BUY","orderType":"LIMIT","positionSide":"LONG","origQty":"0.001","price":"70000","timeInForce":"GTC"}
signature : 419cf02089398befb70e74e34f7039f40a73baad9421730dab9fa5cc6f8d78af

5. 程式碼示例​

每個示例都會查詢餘額(帶查詢參數的 GET)並下一張限價單(帶 JSON 請求體的 POST)。請先設定環境變數 AZ_API_KEY 和 AZ_SECRET_KEY。每個示例都會輸出 original,方便你對照上述規則。

⚠️ 示例會真實下單

示例預設連接沙盒環境(https://f-api.az-qa2.xyz);沙盒與生產環境的 API key 不同。如要在生產環境執行,請設定 AZ_HOST=https://f-api.azverse.xyz,並先調整 price / origQty。訂單為只做 Maker(GTX),不會立即成交;執行後請自行撤單。

所有示例的關鍵規則:請求體只序列化一次,對該字串簽名,並發送同一個字串。

Python​

import hashlib
import hmac
import json
import os
import time
from urllib.parse import urlencode

import requests

HOST = os.getenv("AZ_HOST", "https://f-api.az-qa2.xyz") # sandbox; production: https://f-api.azverse.xyz
API_KEY = os.environ["AZ_API_KEY"]
SECRET_KEY = os.environ["AZ_SECRET_KEY"]


def signed_request(method, path, params=None, payload=None):
timestamp = str(int(time.time() * 1000)) # milliseconds (13 digits)

# Futures: header part has ONLY appkey + timestamp, and there is NO method segment
original = f"validate-appkey={API_KEY}&validate-timestamp={timestamp}#{path}"

query = ""
if params:
items = sorted(params.items()) # sort by key (ASCII order)
original += "#" + "&".join(f"{k}={v}" for k, v in items) # un-encoded values
query = "?" + urlencode(items) # URL-encoded on the wire

body = None
if payload is not None:
body = json.dumps(payload, separators=(",", ":")) # serialize ONCE
original += "#" + body # sign exactly the string you send

signature = hmac.new(SECRET_KEY.encode(), original.encode(), hashlib.sha256).hexdigest()
print("original :", original)

headers = {
"Content-Type": "application/json",
"validate-appkey": API_KEY,
"validate-timestamp": timestamp, # the SAME timestamp used in `original`
"validate-signature": signature,
}
# send the signed string itself (as UTF-8 bytes), NOT json=payload (requests would re-serialize it)
data = None if body is None else body.encode("utf-8")
resp = requests.request(method, HOST + path + query, headers=headers, data=data)
return resp.json()


# GET with query parameters
print(signed_request("GET", "/az/future/user/v1/balance/detail", params={"coin": "usdt"}))

# POST with JSON body: place a post-only limit order
print(signed_request("POST", "/az/future/trade/v1/order/create", payload={
"symbol": "btc_usdt",
"orderSide": "BUY",
"orderType": "LIMIT",
"positionSide": "LONG",
"origQty": "0.001", # pass decimals as strings to keep their exact text
"price": "70000",
"timeInForce": "GTX", # post-only: never fills immediately
}))

JavaScript (Node.js 18+)​

// Node.js 18+ (built-in fetch and crypto). Save as sign.mjs and run: node sign.mjs
import crypto from 'node:crypto';

const HOST = process.env.AZ_HOST || 'https://f-api.az-qa2.xyz'; // sandbox; production: https://f-api.azverse.xyz
const API_KEY = process.env.AZ_API_KEY;
const SECRET_KEY = process.env.AZ_SECRET_KEY;

async function signedRequest(method, path, params, payload) {
const timestamp = String(Date.now()); // milliseconds (13 digits)

// Futures: header part has ONLY appkey + timestamp, and there is NO method segment
let original = `validate-appkey=${API_KEY}&validate-timestamp=${timestamp}#${path}`;

let query = '';
if (params && Object.keys(params).length) {
const keys = Object.keys(params).sort(); // sort by key (ASCII order)
original += '#' + keys.map((k) => `${k}=${params[k]}`).join('&'); // un-encoded values
query = '?' + keys.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`).join('&');
}

let body;
if (payload !== undefined) {
body = JSON.stringify(payload); // serialize ONCE
original += '#' + body; // sign exactly the string you send
}

const signature = crypto.createHmac('sha256', SECRET_KEY).update(original).digest('hex');
console.log('original :', original);

const resp = await fetch(HOST + path + query, {
method,
headers: {
'Content-Type': 'application/json',
'validate-appkey': API_KEY,
'validate-timestamp': timestamp, // the SAME timestamp used in `original`
'validate-signature': signature,
},
body, // the signed string itself
});
return resp.json();
}

// GET with query parameters
console.log(await signedRequest('GET', '/az/future/user/v1/balance/detail', { coin: 'usdt' }));

// POST with JSON body: place a post-only limit order
console.log(await signedRequest('POST', '/az/future/trade/v1/order/create', null, {
symbol: 'btc_usdt',
orderSide: 'BUY',
orderType: 'LIMIT',
positionSide: 'LONG',
origQty: '0.001', // pass decimals as strings to keep their exact text
price: '70000',
timeInForce: 'GTX', // post-only: never fills immediately
}));

Java (11+)​

// Java 11+ (no third-party dependency). Save as Sign.java and run: java Sign.java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Sign {
static final String HOST = System.getenv().getOrDefault("AZ_HOST", "https://f-api.az-qa2.xyz"); // sandbox; production: https://f-api.azverse.xyz
static final String API_KEY = System.getenv("AZ_API_KEY");
static final String SECRET_KEY = System.getenv("AZ_SECRET_KEY");
static final HttpClient HTTP = HttpClient.newHttpClient();

static String hmacSha256Hex(String secret, String data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
StringBuilder hex = new StringBuilder();
for (byte b : mac.doFinal(data.getBytes(StandardCharsets.UTF_8))) {
hex.append(String.format("%02x", b));
}
return hex.toString();
}

static String signedRequest(String method, String path, Map<String, String> params, String body) throws Exception {
String timestamp = String.valueOf(System.currentTimeMillis()); // milliseconds (13 digits)

// Futures: header part has ONLY appkey + timestamp, and there is NO method segment
StringBuilder original = new StringBuilder("validate-appkey=" + API_KEY + "&validate-timestamp=" + timestamp + "#" + path);

String query = "";
if (params != null && !params.isEmpty()) {
TreeMap<String, String> sorted = new TreeMap<>(params); // sort by key (ASCII order)
original.append("#").append(sorted.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue()) // un-encoded values
.collect(Collectors.joining("&")));
query = "?" + sorted.entrySet().stream()
.map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "="
+ URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8).replace("+", "%20"))
.collect(Collectors.joining("&"));
}
if (body != null) {
original.append("#").append(body); // sign exactly the string you send
}

String signature = hmacSha256Hex(SECRET_KEY, original.toString());
System.out.println("original : " + original);

HttpRequest request = HttpRequest.newBuilder(URI.create(HOST + path + query))
.header("Content-Type", "application/json")
.header("validate-appkey", API_KEY)
.header("validate-timestamp", timestamp) // the SAME timestamp used in `original`
.header("validate-signature", signature)
.method(method, body == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
.build();
return HTTP.send(request, HttpResponse.BodyHandlers.ofString()).body();
}

public static void main(String[] args) throws Exception {
// GET with query parameters
System.out.println(signedRequest("GET", "/az/future/user/v1/balance/detail", Map.of("coin", "usdt"), null));

// POST with JSON body: place a post-only limit order (GTX never fills immediately).
// Build the JSON string ONCE (by hand or with your JSON library) and use it for both signing and sending.
String body = "{\"symbol\":\"btc_usdt\",\"orderSide\":\"BUY\",\"orderType\":\"LIMIT\",\"positionSide\":\"LONG\","
+ "\"origQty\":\"0.001\",\"price\":\"70000\",\"timeInForce\":\"GTX\"}";
System.out.println(signedRequest("POST", "/az/future/trade/v1/order/create", null, body));
}
}

curl + openssl (bash)​

#!/usr/bin/env bash
# Requires: bash, openssl, curl. Export AZ_API_KEY / AZ_SECRET_KEY first.
HOST="${AZ_HOST:-https://f-api.az-qa2.xyz}" # sandbox; production: https://f-api.azverse.xyz
PATH_="/az/future/trade/v1/order/create"
BODY='{"symbol":"btc_usdt","orderSide":"BUY","orderType":"LIMIT","positionSide":"LONG","origQty":"0.001","price":"70000","timeInForce":"GTX"}'
TS=$(( $(date +%s) * 1000 )) # milliseconds (13 digits)

# Futures: header part has ONLY appkey + timestamp, and there is NO method segment
ORIGINAL="validate-appkey=${AZ_API_KEY}&validate-timestamp=${TS}#${PATH_}#${BODY}"
SIGNATURE=$(printf '%s' "$ORIGINAL" | openssl dgst -sha256 -hmac "$AZ_SECRET_KEY" | awk '{print $NF}')
echo "original : $ORIGINAL"

curl -sS -X POST "${HOST}${PATH_}" \
-H 'Content-Type: application/json' \
-H "validate-appkey: ${AZ_API_KEY}" \
-H "validate-timestamp: ${TS}" \
-H "validate-signature: ${SIGNATURE}" \
--data-raw "$BODY"
echo

6. 仍然收到 invalid signature?​

輸出你的 original 字串,按上述規則逐段比對,然後逐項查閱簽名常見錯誤。