# Python Guide for Calling Mefree.NET API

This guide demonstrates how to use **Python** to interact with the Mefree.NET API, including signature generation, HTTP request construction, and example API calls.

***

#### **1. Overview of the Signature Rules**

**1.1 Signature String Rules**

Mefree.NET API requires requests to be signed for authentication. Follow these rules to generate the signature:

1. **Construct the String to Sign**:

   ```
   sign = timestamp + method + requestPath
   ```

   * **timestamp**: UTC time in ISO 8601 format, e.g., `2024-11-26T12:34:56.789Z`.
   * **method**: HTTP method, e.g., `GET` or `POST`.
   * **requestPath**: API request path (including query parameters), such as:
     * `/api/config`
     * `/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1`
2. **Generate the Signature**:
   * Use the **HMAC-SHA256** algorithm with the **Secret Key** to hash the string.
   * Encode the resulting hash with **Base64** to generate the final signature.

***

**1.2 Required HTTP Headers**

Each 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. Environment Setup**

Ensure you have **Python 3.6+** installed. Install the required libraries using:

```bash
pip install requests
```

***

#### **3. Signature Generation Function**

Below is the Python implementation for generating the signature:

```python
import hmac
import base64
import hashlib
from datetime import datetime

def generate_signature(timestamp, method, request_path, secret_key):
    """
    Generate HMAC-SHA256 signature.

    Args:
        timestamp (str): Current UTC timestamp in ISO 8601 format.
        method (str): HTTP method (e.g., GET or POST).
        request_path (str): API request path (with query parameters, if any).
        secret_key (str): Your API Secret Key.

    Returns:
        str: Base64-encoded signature.
    """
    message = f"{timestamp}{method}{request_path}"
    signature = hmac.new(
        secret_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    ).digest()
    return base64.b64encode(signature).decode()

def get_utc_timestamp():
    """
    Get the current UTC timestamp in ISO 8601 format.

    Returns:
        str: Timestamp in ISO 8601 format (e.g., 2024-11-26T12:34:56.789Z).
    """
    return datetime.utcnow().isoformat(timespec='milliseconds') + 'Z'
```

***

#### **4. Sending HTTP Requests**

You can use the `requests` library to send HTTP requests with the required headers.

```python
import requests

BASE_URL = "https://api.mefree.net"
API_KEY = "your_api_key"       # Replace with your API Key
SECRET_KEY = "your_secret_key" # Replace with your Secret Key

def send_request(method, request_path):
    """
    Send an HTTP request to the Mefree.NET API.

    Args:
        method (str): HTTP method (GET or POST).
        request_path (str): API request path (with query parameters).

    Returns:
        dict: Parsed JSON response from the API.
    """
    timestamp = get_utc_timestamp()
    signature = generate_signature(timestamp, method, request_path, SECRET_KEY)

    # Construct headers
    headers = {
        "Content-Type": "application/json",
        "MF-ACCESS-KEY": API_KEY,
        "MF-ACCESS-SIGN": signature,
        "MF-ACCESS-TIMESTAMP": timestamp
    }

    # Send the request
    url = BASE_URL + request_path
    try:
        if method == "GET":
            response = requests.get(url, headers=headers)
        elif method == "POST":
            response = requests.post(url, headers=headers)
        else:
            raise ValueError("Unsupported HTTP method")

        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        print(f"Request failed: {e}")
        return None
```

***

#### **5. Example API Calls**

**5.1 Get Account Information**

**API Endpoint**: `/api/config`\
**HTTP Method**: `GET`

**Code Example**:

```python
if __name__ == "__main__":
    response = send_request("GET", "/api/config")
    if response:
        print("Account Information:", response)
```

***

**5.2 Create an Order**

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

**Code Example**:

```python
if __name__ == "__main__":
    request_path = "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1"
    response = send_request("POST", request_path)
    if response:
        print("Order Created:", response)
```

***

**5.3 Query Order Status**

**API Endpoint**: `/api/order/{pay_hash}`\
**HTTP Method**: `GET`

**Code Example**:

```python
if __name__ == "__main__":
    pay_hash = "abcd1234"  # Replace with actual pay_hash
    request_path = f"/api/order/{pay_hash}"
    response = send_request("GET", request_path)
    if response:
        print("Order Status:", response)
```

***

#### **6. Common Issues**

**6.1 Invalid Signature (401 Unauthorized)**

* Ensure the `MF-ACCESS-KEY` matches your API Key.
* Verify the signature generation logic:
  * Concatenate the string in the correct order: `timestamp + method + requestPath`.
  * Use the correct `SECRET_KEY`.
* Ensure the timestamp is in UTC format and not older than 5 seconds.

**6.2 Bad Request (400)**

* Verify the request path and query parameters are correct.
* Ensure `Content-Type` is set to `application/json`.

**6.3 Too Many Requests (429)**

* Respect the API rate limits. Implement request throttling if necessary.

***

#### **7. Summary**

This guide covers Python implementation for calling Mefree.NET API. It includes signature generation, HTTP request construction, and example usage. By following this guide, you can easily integrate Mefree.NET API into your Python applications. For further support, contact Mefree technical support or consult the official API documentation.
