Node.js 调用示例
Node.js 调用 CatFee.IO Rest API 示例
前提条件
示例代码
const axios = require('axios');
const crypto = require('crypto');
const API_KEY = 'your_api_key'; // 请替换为您的API Key
const API_SECRET = 'your_api_secret'; // 请替换为您的API Secret
const BASE_URL = 'https://api.catfee.io';
// 生成当前的时间戳(ISO 8601格式)
function generateTimestamp() {
return new Date().toISOString();
}
// 构建请求路径,包括查询参数
function buildRequestPath(path, queryParams) {
if (!queryParams || Object.keys(queryParams).length === 0) {
return path;
}
const queryString = new URLSearchParams(queryParams).toString();
return `${path}?${queryString}`;
}
// 使用 HMAC-SHA256 算法生成签名
function generateSignature(timestamp, method, requestPath) {
const signString = timestamp + method + requestPath;
return crypto.createHmac('sha256', API_SECRET)
.update(signString)
.digest('base64');
}
// 创建 HTTP 请求
async function createRequest(url, method, timestamp, signature) {
const headers = {
'Content-Type': 'application/json',
'CF-ACCESS-KEY': API_KEY,
'CF-ACCESS-SIGN': signature,
'CF-ACCESS-TIMESTAMP': timestamp
};
try {
const response = await axios({
url,
method,
headers,
});
return response.data;
} catch (error) {
console.error('Error: ', error.response ? error.response.data : error.message);
throw error;
}
}
async function main() {
const method = 'POST'; // 可以修改为 "GET", "PUT", "DELETE"
const path = '/v1/order';
// 示例:创建订单
const queryParams = {
quantity: '65000',
receiver: 'TRON_ADDRESS',
duration: '1h'
};
// 生成请求头
const timestamp = generateTimestamp();
const requestPath = buildRequestPath(path, queryParams);
const signature = generateSignature(timestamp, method, requestPath);
// 创建请求 URL
const url = BASE_URL + requestPath;
// 发送请求
try {
const response = await createRequest(url, method, timestamp, signature);
console.log('Response Data: ', response);
} catch (error) {
console.error('Request failed', error);
}
}
// 执行主函数
main();代码解析
注意事项
总结
Last updated