跳至主要内容
簽名生成
1. 初始化配置與參數
2. 整合簽名參數
3. 排序並拼接參數
4. 計算請求體
5. 構建簽名字串
6. 編碼與生成簽名
7. 生成簽名

Python

1 import hmac
2 import hashlib
3 import json
4 import uuid
5 from datetime import datetime, timezone
6 from urllib.parse import quote
7 import base64
8
9 # Initialize Configuration and Parameters
10 optional_api_endpoint = "<api_endpoint>"
11 app_key = "<your_app_key>"
12 app_secret = "<your_app_secret>"
13
14 # Request URI
15 uri = '/trading/accounts/list'
16
17 # Signature Header
18 headers = {
19 'x-app-key': app_key,
20 'x-signature-algorithm': 'HMAC-SHA256',
21 'x-signature-version': '1.0',
22 'x-signature-nonce': uuid.uuid4().hex,
23 'x-timestamp': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
24 'host': optional_api_endpoint,
25 'Content-Type': 'application/json'
26 }
27
28 query_params = {
29 }
30
31 body_params = {
32 }
33
34
35 def generate_signature(uri, query_params, body_params, headers, app_secret):
36 query_params = query_params or {}
37 # Integrate signature parameters
38 params_dict = query_params.copy()
39 # The signature algorithm must match the hash function below and is refreshed in place
40 headers['x-signature-algorithm'] = 'HMAC-SHA256'
41 # Parameters in the Signature Header excluding the x-signature parameter.
42 params_dict.update({
43 'x-app-key': headers['x-app-key'],
44 'x-signature-algorithm': headers['x-signature-algorithm'],
45 'x-signature-version': headers['x-signature-version'],
46 'x-signature-nonce': headers['x-signature-nonce'],
47 'x-timestamp': headers['x-timestamp'],
48 'host': headers['host']
49 })
50
51 # Sort the dictionary from small to large according to the parameter's key
52 sorted_params = sorted(params_dict.items())
53 # Concatenate the sorted parameters into a string
54 param_string = '&'.join([f"{k}={v}" for k, v in sorted_params])
55
56 # Calculate the SHA256 of the request body (if any)
57 body_sha256 = ""
58 if body_params is not None:
59 body_json = json.dumps(body_params, ensure_ascii=False, separators=(',', ':'))
60 body_sha256 = hashlib.sha256(body_json.encode()).hexdigest().upper()
61
62 # Build the sign string
63 sign_string = f"{uri}&{param_string}{'&' + body_sha256 if body_sha256 else ''}"
64
65 # Encode Request Elements
66 encoded_sign_string = quote(sign_string, safe='')
67
68 # Generating Signature
69 # base64(HMAC-SHA256(Part 1 + "&", Part 2))
70 secret = f"{app_secret}&"
71 signature = hmac.new(
72 secret.encode(),
73 encoded_sign_string.encode(),
74 hashlib.sha256
75 ).digest()
76
77 sign_string = base64.b64encode(signature).decode('utf-8')
78 print(f"Signature: {sign_string}")
79 return sign_string
80
簽名生成
透過 HMAC-SHA256 演算法和金鑰計算雜湊值,再對其進行 base64 編碼,得到最終簽名,該簽名用於 API 請求的身份驗證與防篡改驗證
7 Steps
建立並驗證 Token
這段程式碼用於建立並驗證 API 存取令牌(Token),透過呼叫令牌建立介面生成令牌,檢查介面驗證令牌狀態,確保令牌有效可用,為後續 API 操作提供安全存取憑證
5 Steps
下第一筆訂單
快速開始:設定憑證、配置訂單詳情、生成簽名,完成您的第一筆訂單。
7 Steps