# 使用API购买

本指南将帮助您快速上手如何连接并使用 Mefree.NET 的REST API。

***

#### **1. 准备工作**

**1.1 注册并获取 API 密钥**

1. 登录Mefree.NET的电报机器人（[@SuperXCoinBot](https://t.me/SuperXCoinBot)）。
2. 进入 **个人中心** 界面，点击 **API购买**：
   * 保存 API KEY(API ACCESS KEY)。
   * 保存秘钥(API SECRET)。

**1.2 工具准备**

* **测试工具**：Postman、Curl 或命令行工具。
* **开发环境**：Python（推荐使用 `requests` 库），或其他支持 HTTP 请求的编程语言。

**1.3 文档参考**

访问 [Mefree.NET官方API文档](/zh/api/config.md) 获取更详细的接口说明。

***

#### **2. API 基础知识**

**2.1 Base URL**

* **生产环境**：`https://api.mefree.net`

**2.2 API Headers**

所有请求需要添加以下 HTTP 头信息：

```plaintext
Content-Type: application/json
MF-ACCESS-KEY: 您的API Key
MF-ACCESS-SIGN: 请求签名（见后续签名规则）
MF-ACCESS-TIMESTAMP: 当前时间戳
```

**2.3 时间戳格式**

`MF-ACCESS-TIMESTAMP` 需使用 ISO 8601 格式的 UTC 时间，例如：`2023-01-01T12:00:00.000Z`。

**2.4 签名规则**

签名用于验证请求身份，生成签名的步骤：

1. 拼接待签名字符串：

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

   * `timestamp`：`MF-ACCESS-TIMESTAMP` 的值。
   * `method`：HTTP 方法（如 GET、POST）。
   * `requestPath`：请求的路径, :warning: **注意：如果有query参数一定要带上**

   （如 `/api/config`、`/api/order?quantity=65000&period=1&target_address=Txxx...7n`）。
2. 使用 HMAC-SHA256 算法和 API 的 Secret Key 对签名字符串进行哈希处理。
3. 将结果用 Base64 编码，得到最终签名值。

***

#### **3. 快速请求示例**

以下是使用 Python 连接 Mefree API 的示例代码。

**3.1 准备代码环境**

确保已安装 `requests` 和 `datetime` 库：

```bash
pip install requests
```

**3.2 查询账户余额**

**请求说明**：

* URL: `GET /api/config`
* 功能：获取账户信息。

**代码实现：**

```python
import requests
import time
import base64
import hmac
import json
from datetime import datetime

# API 配置信息
BASE_URL = "https://api.mefree.net"
API_KEY = "your_api_key"
SECRET_KEY = "your_secret_key"

# 签名生成函数
def generate_signature(timestamp, method, request_path, secret_key):
    message = f"{timestamp}{method}{request_path}"
    mac = hmac.new(secret_key.encode('utf-8'), message.encode('utf-8'), digestmod='sha256')
    return base64.b64encode(mac.digest()).decode()

# 当前 UTC 时间戳
timestamp = datetime.utcnow().isoformat(timespec='milliseconds') + 'Z'

# 设置请求信息
method = "GET"
request_path = "/api/config"
url = BASE_URL + request_path
body = None  # GET 请求无需 Body

# 生成签名
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,
}

# 发起请求
response = requests.get(url, headers=headers)
if response.status_code == 200:
    print("账户信息：", response.json())
else:
    print("请求失败：", response.status_code, response.text)
```

**3.3 下单交易示例**

**请求说明**：

* URL: `POST /api/order`
* 功能：购买能量。

**代码实现：**

```python

# 生成签名
timestamp = datetime.utcnow().isoformat(timespec='milliseconds') + 'Z'
method = "POST"
request_path = "/api/order?quantity=65000&target_address=TDYk....4rnPfkdPZ&period=1"
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,
}

# 发起请求
response = requests.post(BASE_URL + request_path, headers=headers, json=body)
if response.status_code == 200:
    print("订单已创建：", response.json())
else:
    print("请求失败：", response.status_code, response.text)
```

***

#### **4. 常见问题与解决方法**

1. **HTTP 状态码 401 Unauthorized**：
   * 检查 `MF-ACCESS-KEY`、`MF-ACCESS-SIGN` 是否正确。
   * 确保 API 密钥权限已启用。
2. **HTTP 状态码 400 Bad Request**：
   * 检查请求参数是否正确（如交易对、价格、数量等）。
3. **签名错误**：
   * 确保时间戳使用 UTC 时间，并严格按照签名规则生成签名。

***

#### **5. 后续操作**

* 阅读 [Mefree API 文档](/zh/api/config.md)，熟悉更多功能接口（如获取订单详情，可用能量等）。
* 根据需求，扩展 API 的集成功能，开发私有能量交易系统。

通过本指南，您已完成连接Mefree API 的基本操作。祝您一切顺利！


---

# 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/buy-energy-by-api-quickstart.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.
