Python调用Mefree.NET API
Last updated
import hmac
import hashlib
import base64
from datetime import datetime, timezone
def generate_signature(timestamp, method, request_path, secret_key):
"""
生成 Mefree API 的签名
:param timestamp: 当前 UTC 时间戳 (ISO 8601 格式)
:param method: HTTP 方法 (GET/POST)
:param request_path: API 请求路径(含参数)
:param secret_key: API 的 Secret Key
:return: 签名字符串 (Base64 编码)
"""
# 拼接待签名字符串
string_to_sign = timestamp + method + request_path
# 使用 HMAC-SHA256 生成签名
signature = hmac.new(
secret_key.encode('utf-8'),
string_to_sign.encode('utf-8'),
hashlib.sha256
).digest()
# 返回 Base64 编码的签名
return base64.b64encode(signature).decode('utf-8')def get_utc_timestamp():
"""
获取当前 UTC 时间戳 (ISO 8601 格式)
"""
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')import requests
BASE_URL = "https://api.mefree.net" # Mefree API 基础地址
API_KEY = "your_api_key" # 替换为您的 API Key
SECRET_KEY = "your_secret_key" # 替换为您的 Secret Key
def send_request(method, request_path):
"""
发起 API 请求
:param method: HTTP 方法 (GET/POST)
:param request_path: API 请求路径(含参数)
:return: 响应内容
"""
try:
# 获取当前 UTC 时间戳
timestamp = get_utc_timestamp()
# 生成签名
signature = generate_signature(timestamp, method, request_path, SECRET_KEY)
# 构造请求头
headers = {
"Content-Type": "application/json",
"MF-ACCESS-KEY": API_KEY,
"MF-ACCESS-SIGN": signature,
"MF-ACCESS-TIMESTAMP": timestamp,
}
# 构造完整 URL
url = BASE_URL + request_path
# 发起请求
if method == "GET":
response = requests.get(url, headers=headers)
elif method == "POST":
response = requests.post(url, headers=headers, json={}) # POST 请求无 body 数据
# 返回响应内容
return response.json()
except Exception as e:
print(f"请求失败: {e}")
return Noneif __name__ == "__main__":
response = send_request("GET", "/api/config")
print("账户信息:", response)if __name__ == "__main__":
request_path = "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1"
response = send_request("POST", request_path)
print("订单已创建:", response)if __name__ == "__main__":
pay_hash = "abcd1234" # 替换为实际的 pay_hash
request_path = f"/api/order/{pay_hash}"
response = send_request("GET", request_path)
print("订单状态:", response)