Golang Guide for calling Mefree.NET API

This guide provides detailed instructions on how to use Go (Golang) to interact with the Mefree.NET API, including generating signatures, building requests, and handling API responses.


1. Signature Rules Overview

Mefree.NET API uses a signature-based authentication mechanism. The signature is generated as follows:

1.1 Signature String Rules

The signature string is constructed in the following format:

sign = timestamp + method + requestPath
  • timestamp: UTC time in ISO 8601 format (e.g., 2024-11-26T12:34:56.789Z).

  • method: HTTP method, such as GET or POST.

  • requestPath: API request path (including query parameters), for example:

    • /api/config

    • /api/order?quantity=65000&target_address=TRON_ADDRESS&period=1

1.2 Signature Generation Process

  1. Concatenate timestamp, method, and requestPath into a string.

  2. Use the HMAC-SHA256 algorithm to hash the concatenated string with your API Secret Key.

  3. Encode the resulting hash using Base64 to generate the signature.

1.3 Required HTTP Headers

Each API request must include the following headers:

  • Content-Type: application/json

  • MF-ACCESS-KEY: Your API Key.

  • MF-ACCESS-SIGN: The generated signature.

  • MF-ACCESS-TIMESTAMP: Current UTC timestamp.


2. Implementing Signature in Go

2.1 Signature Generation Function

Here’s how to generate the signature in Go:

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
)

// GenerateSignature generates a Base64-encoded HMAC-SHA256 signature
func GenerateSignature(timestamp, method, requestPath, secretKey string) string {
	// Create the string to sign
	stringToSign := timestamp + method + requestPath

	// Create a new HMAC by defining the hash type and the secret key
	h := hmac.New(sha256.New, []byte(secretKey))
	h.Write([]byte(stringToSign))

	// Compute the HMAC and encode it in Base64
	signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
	return signature
}

3. Constructing API Requests

3.1 Configuration

Define your API configuration:

package main

// API Configuration
const BaseURL = "https://api.mefree.net" // Mefree API base URL
const APIKey = "your_api_key"        // Replace with your actual API Key
const SecretKey = "your_secret_key"  // Replace with your actual Secret Key

3.2 General HTTP Request Function

Here’s a reusable function to make API requests:

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

// SendRequest sends an HTTP request to the Mefree API
func SendRequest(method, requestPath string) (int, string, error) {
	// Get current UTC timestamp in ISO 8601 format
	timestamp := time.Now().UTC().Format("2006-01-02T15:04:05.000Z")

	// Generate the signature
	signature := GenerateSignature(timestamp, method, requestPath, SecretKey)

	// Create the request
	url := BaseURL + requestPath
	req, err := http.NewRequest(method, url, nil)
	if err != nil {
		return 0, "", err
	}

	// Set headers
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("MF-ACCESS-KEY", APIKey)
	req.Header.Set("MF-ACCESS-SIGN", signature)
	req.Header.Set("MF-ACCESS-TIMESTAMP", timestamp)

	// Send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return 0, "", err
	}
	defer resp.Body.Close()

	// Read the response
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, "", err
	}

	return resp.StatusCode, string(body), nil
}

4. API Call Examples

4.1 Fetch Account Information

Endpoint: /api/config HTTP Method: GET

Code Example:

package main

import "fmt"

func main() {
	// Fetch account information
	requestPath := "/api/config"
	statusCode, response, err := SendRequest("GET", requestPath)

	// Handle the response
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	if statusCode == 200 {
		fmt.Println("Account Information:")
		fmt.Println(response)
	} else {
		fmt.Printf("Request failed with HTTP status code %d\n", statusCode)
		fmt.Println("Response:", response)
	}
}

4.2 Create an Order

Endpoint: /api/order?quantity=65000&target_address=TRON_ADDRESS&period=1 HTTP Method: POST

Code Example:

package main

import "fmt"

func main() {
	// Create an order
	requestPath := "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1"
	statusCode, response, err := SendRequest("POST", requestPath)

	// Handle the response
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	if statusCode == 200 {
		fmt.Println("Order Created Successfully:")
		fmt.Println(response)
	} else {
		fmt.Printf("Request failed with HTTP status code %d\n", statusCode)
		fmt.Println("Response:", response)
	}
}

4.3 Check Order Status

Endpoint: /api/order/{pay_hash} HTTP Method: GET

Code Example:

package main

import "fmt"

func main() {
	// Check order status
	payHash := "abcd1234" // Replace with the actual order pay_hash
	requestPath := "/api/order/" + payHash
	statusCode, response, err := SendRequest("GET", requestPath)

	// Handle the response
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	if statusCode == 200 {
		fmt.Println("Order Status:")
		fmt.Println(response)
	} else {
		fmt.Printf("Request failed with HTTP status code %d\n", statusCode)
		fmt.Println("Response:", response)
	}
}

5. Common Issues

5.1 Invalid Signature (401 Unauthorized)

  • Verify that MF-ACCESS-KEY matches your API Key.

  • Ensure the signature string follows the format: timestamp + method + requestPath.

  • Use the correct Secret Key to generate the signature.

  • Ensure the timestamp is in UTC and formatted correctly (e.g., 2024-11-26T12:34:56.789Z).

5.2 Invalid Parameters (400 Bad Request)

  • Double-check the request path and query parameters.

  • Ensure the Content-Type header is set to application/json.

5.3 Rate Limit Exceeded (429 Too Many Requests)

  • Mefree API enforces rate limits. Avoid sending excessive requests within a short period.

  • Add delays or throttle requests (e.g., no more than 2 requests per second).


6. Conclusion

This guide demonstrates how to interact with the Mefree.NET API using Go, including generating signatures, sending requests, and handling responses. For critical operations, such as placing orders, it is recommended to implement retry mechanisms for better reliability. If you encounter any issues, contact Mefree's official support team for assistance.

Last updated