# Python调用Mefree.NET API

本指南介绍如何使用 **Python** 调用 Mefree.NET API，包括生成签名的方法、构建 HTTP 请求，以及调用示例。

***

#### **1. 签名规则概述**

Mefree.NET API 使用签名机制对请求进行身份验证。以下是签名规则的详细说明：

**1.1 签名字符串规则**

签名生成的格式如下：

```
sign = timestamp + method + requestPath
```

* **timestamp**：UTC 时间，格式为 ISO 8601，例如：`2024-11-26T12:34:56.789Z`。
* **method**：HTTP 方法，例如 `GET` 或 `POST`。
* **requestPath**：API 请求路径（包括查询参数），例如：
  * `/api/config`
  * `/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1`

**1.2 签名生成流程**

1. 拼接签名字符串，格式为 `timestamp + method + requestPath`。
2. 使用 **HMAC-SHA256** 算法，结合 API 的 **Secret Key** 对拼接字符串进行加密。
3. 将加密结果用 **Base64** 编码，生成最终的签名。

**1.3 请求头参数**

每次请求需要包含以下 HTTP 头：

* `Content-Type: application/json`
* `MF-ACCESS-KEY`: 您的 API Key。
* `MF-ACCESS-SIGN`: 生成的签名值。
* `MF-ACCESS-TIMESTAMP`: 当前的 UTC 时间戳。

***

#### **2. Python实现签名方法**

**2.1 签名生成函数**

以下代码展示了如何用 Python 生成 API 的签名：

```python
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')
```

**2.2 获取 UTC 时间戳**

```python
def get_utc_timestamp():
    """
    获取当前 UTC 时间戳 (ISO 8601 格式)
    """
    return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
```

***

#### **3. 通用请求方法**

使用 **requests** 库构建通用的 HTTP 请求方法。

```python
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 None
```

***

#### **4. 示例接口调用**

**4.1 获取账户信息**

**接口描述**：

* 请求路径：`/api/config`
* HTTP 方法：`GET`

**调用代码**：

```python
if __name__ == "__main__":
    response = send_request("GET", "/api/config")
    print("账户信息:", response)
```

***

**4.2 创建订单**

**接口描述**：

* 请求路径：`/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1`
* HTTP 方法：`POST`

**调用代码**：

```python
if __name__ == "__main__":
    request_path = "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1"
    response = send_request("POST", request_path)
    print("订单已创建:", response)
```

***

**4.3 查询订单状态**

**接口描述**：

* 请求路径：`/api/order/{pay_hash}`
* HTTP 方法：`GET`

**调用代码**：

```python
if __name__ == "__main__":
    pay_hash = "abcd1234"  # 替换为实际的 pay_hash
    request_path = f"/api/order/{pay_hash}"
    response = send_request("GET", request_path)
    print("订单状态:", response)
```

***

#### **5. 常见问题**

**5.1 签名无效 (401 Unauthorized)**

* 确认 `MF-ACCESS-KEY` 是否正确。
* 确保签名按照规则生成：
  * 拼接顺序为：`timestamp + method + requestPath`。
  * 时间戳格式是否为 UTC。
  * 使用正确的 `SECRET_KEY`。

**5.2 请求参数错误 (400 Bad Request)**

* 检查请求路径是否正确，尤其是查询参数是否完整。
* 确认 `Content-Type` 是否为 `application/json`。

**5.3 请求频率限制 (429 Too Many Requests)**

* 添加合理的请求间隔（例如每秒最多 2 次请求）。

***

#### **6. 总结**

通过本指南，您可以使用 Python 调用 Mefree.NET API，包括生成签名、构建请求以及解析响应数据。对于重要操作（如订单创建），建议添加重试机制，提升调用的可靠性。如有疑问，请联系 Mefree 官方支持团队。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mefree.net/zh/getting-started/how-to-buy-energy/python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
