import hashlib
import hmac
import base64
import time
import requests
from urllib.parse import urlencode
API_KEY = "your_api_key" # 请替换为您的API Key
API_SECRET = "your_api_secret" # 请替换为您的API Secret
BASE_URL = "https://api.catfee.io"
def generate_timestamp():
"""生成当前的时间戳(ISO 8601格式)"""
return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())
def build_request_path(path, query_params):
"""构建请求路径,包括查询参数"""
if not query_params:
return path
query_string = urlencode(query_params)
return f"{path}?{query_string}"
def generate_signature(timestamp, method, request_path):
"""生成签名"""
sign_string = timestamp + method + request_path
return hmac_sha256(sign_string, API_SECRET)
def hmac_sha256(data, secret):
"""使用 HMAC-SHA256 算法生成签名"""
return base64.b64encode(hmac.new(secret.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).digest()).decode()
def create_request(url, method, timestamp, signature):
"""创建 HTTP 请求"""
headers = {
"Content-Type": "application/json",
"CF-ACCESS-KEY": API_KEY,
"CF-ACCESS-SIGN": signature,
"CF-ACCESS-TIMESTAMP": timestamp,
}
if method == "POST":
response = requests.post(url, headers=headers)
elif method == "GET":
response = requests.get(url, headers=headers)
elif method == "PUT":
response = requests.put(url, headers=headers)
elif method == "DELETE":
response = requests.delete(url, headers=headers)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
return response
def main():
method = "POST" # 可以修改为 "GET", "PUT", "DELETE" 等方法
path = "/v1/order"
# 示例:创建订单
query_params = {
"quantity": "65000",
"receiver": "TRON_ADDRESS",
"duration": "1h"
}
# 生成请求头
timestamp = generate_timestamp()
request_path = build_request_path(path, query_params)
signature = generate_signature(timestamp, method, request_path)
# 创建请求 URL
url = BASE_URL + request_path
# 发送请求
response = create_request(url, method, timestamp, signature)
# 打印响应
print("Response Code:", response.status_code)
print("Response Body:", response.text)
# 处理可能的错误信息
if response.status_code != 200:
print("Error:", response.json())
if __name__ == "__main__":
main()
此示例展示了如何使用 Python 调用 CatFee.IO Rest API,利用 HMAC-SHA256 签名确保请求的安全性。您可以根据需要调整代码,支持 GET
、POST
、PUT
和 DELETE
等 HTTP 方法。