# Node.js 调用 Mefree.NET API

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

***

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

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

Mefree.NET API 使用签名机制验证身份，请确保按照以下规则生成签名：

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`
2. 使用 **HMAC-SHA256** 算法，结合 API 的 **Secret Key** 对拼接字符串进行加密。
3. 将加密结果用 **Base64** 编码，得到最终的签名值。

***

**1.2 请求头参数**

每个请求必须包含以下 HTTP 头：

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

***

#### **2. 环境准备**

确保您的开发环境已安装 **Node.js** 和 **npm**。以下是需要安装的依赖包：

```bash
npm install axios crypto dayjs
```

***

#### **3. 签名生成方法**

以下是基于 **Node.js** 的签名生成方法：

```javascript
const crypto = require("crypto");
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
dayjs.extend(utc);

/**
 * 生成签名
 * @param {string} timestamp - UTC 时间戳
 * @param {string} method - HTTP 方法 (GET/POST)
 * @param {string} requestPath - 请求路径
 * @param {string} secretKey - API 的 Secret Key
 * @returns {string} 签名字符串
 */
function generateSignature(timestamp, method, requestPath, secretKey) {
  const stringToSign = `${timestamp}${method}${requestPath}`;
  const hmac = crypto.createHmac("sha256", secretKey);
  hmac.update(stringToSign);
  return hmac.digest("base64");
}

/**
 * 获取当前 UTC 时间戳 (ISO 8601 格式)
 * @returns {string} UTC 时间戳
 */
function getUtcTimestamp() {
  return dayjs.utc().format("YYYY-MM-DDTHH:mm:ss.SSS[Z]");
}
```

***

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

以下代码展示了一个通用的 HTTP 请求函数，使用 **axios** 库发起 API 调用。

```javascript
const axios = require("axios");

// 配置基础信息
const BASE_URL = "https://api.mefree.net"; // Mefree API 基础地址
const API_KEY = "your_api_key"; // 替换为您的 API Key
const SECRET_KEY = "your_secret_key"; // 替换为您的 Secret Key

/**
 * 发送 API 请求
 * @param {string} method - HTTP 方法 (GET/POST)
 * @param {string} requestPath - 请求路径（包括参数）
 * @returns {object} 响应数据
 */
async function sendRequest(method, requestPath) {
  try {
    // 获取当前 UTC 时间戳
    const timestamp = getUtcTimestamp();

    // 生成签名
    const signature = generateSignature(timestamp, method, requestPath, SECRET_KEY);

    // 构造请求头
    const headers = {
      "Content-Type": "application/json",
      "MF-ACCESS-KEY": API_KEY,
      "MF-ACCESS-SIGN": signature,
      "MF-ACCESS-TIMESTAMP": timestamp,
    };

    // 构造完整 URL
    const url = `${BASE_URL}${requestPath}`;

    // 发起请求
    const response = await axios({
      method,
      url,
      headers,
    });

    // 返回响应数据
    return response.data;
  } catch (error) {
    console.error("请求失败：", error.response?.data || error.message);
    return null;
  }
}
```

***

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

**5.1 获取账户信息**

**接口描述**：

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

**调用代码**：

```javascript
(async () => {
  const response = await sendRequest("GET", "/api/config");
  console.log("账户信息：", response);
})();
```

***

**5.2 创建订单**

**接口描述**：

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

**调用代码**：

```javascript
(async () => {
  const requestPath = "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1";
  const response = await sendRequest("POST", requestPath);
  console.log("订单已创建：", response);
})();
```

***

**5.3 查询订单状态**

**接口描述**：

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

**调用代码**：

```javascript
(async () => {
  const payHash = "abcd1234"; // 替换为实际的 pay_hash
  const requestPath = `/api/order/${payHash}`;
  const response = await sendRequest("GET", requestPath);
  console.log("订单状态：", response);
})();
```

***

#### **6. 常见问题**

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

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

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

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

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

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

***

#### **7. 总结**

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