Go语言调用 Mefree.NET API
Last updated
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"time"
)
// 生成签名
func generateSignature(timestamp, method, requestPath, secretKey string) string {
message := timestamp + method + requestPath
h := hmac.New(sha256.New, []byte(secretKey))
h.Write([]byte(message))
signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
return signature
}
// 获取当前 UTC 时间戳(ISO 8601 格式)
func getUtcTimestamp() string {
return time.Now().UTC().Format("2006-01-02T15:04:05.000Z")
}package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
// 配置基础信息
const (
BASE_URL = "https://api.mefree.net"
API_KEY = "your_api_key" // 替换为您的 API Key
SECRET_KEY = "your_secret_key" // 替换为您的 Secret Key
)
// 发送 API 请求
func sendRequest(method, requestPath string) ([]byte, error) {
// 获取当前 UTC 时间戳
timestamp := getUtcTimestamp()
// 生成签名
signature := generateSignature(timestamp, method, requestPath, SECRET_KEY)
// 构造请求
client := &http.Client{}
url := BASE_URL + requestPath
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
// 添加请求头
req.Header.Add("Content-Type", "application/json")
req.Header.Add("MF-ACCESS-KEY", API_KEY)
req.Header.Add("MF-ACCESS-SIGN", signature)
req.Header.Add("MF-ACCESS-TIMESTAMP", timestamp)
// 发送请求
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// 读取响应
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
}
return body, nil
}func main() {
response, err := sendRequest("GET", "/api/config")
if err != nil {
fmt.Println("请求失败:", err)
return
}
fmt.Println("账户信息:", string(response))
}func main() {
requestPath := "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1"
response, err := sendRequest("POST", requestPath)
if err != nil {
fmt.Println("请求失败:", err)
return
}
fmt.Println("订单已创建:", string(response))
}func main() {
payHash := "abcd1234" // 替换为实际的 pay_hash
requestPath := fmt.Sprintf("/api/order/%s", payHash)
response, err := sendRequest("GET", requestPath)
if err != nil {
fmt.Println("请求失败:", err)
return
}
fmt.Println("订单状态:", string(response))
}