Node.js 调用 Mefree.NET API
Last updated
npm install axios crypto dayjsconst 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]");
}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;
}
}(async () => {
const response = await sendRequest("GET", "/api/config");
console.log("账户信息:", response);
})();(async () => {
const requestPath = "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1";
const response = await sendRequest("POST", requestPath);
console.log("订单已创建:", response);
})();(async () => {
const payHash = "abcd1234"; // 替换为实际的 pay_hash
const requestPath = `/api/order/${payHash}`;
const response = await sendRequest("GET", requestPath);
console.log("订单状态:", response);
})();