# PHP Guide for calling Mefree.NET API

This guide provides detailed instructions on using **PHP** to interact with the Mefree.NET API, including generating signatures, building requests, and completing the API call flow.

***

#### **1. Signature Rules Overview**

Mefree.NET API uses a signature-based authentication mechanism. The signature is generated using the following logic:

**1.1 Signature String Rules**

The signature string is created 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 encrypt 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 PHP**

**2.1 Signature Generation Function**

Here’s how to generate the signature in PHP:

```php
/**
 * Generate Mefree API signature
 *
 * @param string $timestamp UTC timestamp (ISO 8601 format)
 * @param string $method HTTP method (GET/POST)
 * @param string $request_path API request path (with parameters)
 * @param string $secret_key API Secret Key
 * @return string Base64-encoded signature
 */
function generate_signature($timestamp, $method, $request_path, $secret_key) {
    // Concatenate the string to sign
    $string_to_sign = $timestamp . $method . $request_path;

    // Hash the string using HMAC-SHA256
    $hash = hash_hmac('sha256', $string_to_sign, $secret_key, true);

    // Return the Base64-encoded signature
    return base64_encode($hash);
}
```

***

#### **3. Constructing API Requests**

**3.1 Configuration**

Set up the API base URL and keys:

```php
// API Configuration
$base_url = "https://api.mefree.net";        // Mefree API base URL
$api_key = "your_api_key";              // Replace with your actual API Key
$secret_key = "your_secret_key";        // Replace with your actual Secret Key
```

**3.2 General HTTP Request Function**

Here’s a reusable function to make API requests:

```php
/**
 * Send an HTTP request to Mefree API
 *
 * @param string $method HTTP method (GET/POST)
 * @param string $request_path API request path (with query parameters)
 * @param string $base_url API base URL
 * @param string $api_key API Key
 * @param string $secret_key API Secret Key
 * @return array Response data including HTTP status and body
 */
function send_request($method, $request_path, $base_url, $api_key, $secret_key) {
    // Current UTC timestamp in ISO 8601 format
    $timestamp = gmdate("Y-m-d\TH:i:s.v\Z");

    // Generate the signature
    $signature = generate_signature($timestamp, $method, $request_path, $secret_key);

    // Set the request headers
    $headers = [
        "Content-Type: application/json",
        "MF-ACCESS-KEY: {$api_key}",
        "MF-ACCESS-SIGN: {$signature}",
        "MF-ACCESS-TIMESTAMP: {$timestamp}",
    ];

    // Initialize CURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_url . $request_path); // Set the URL
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);        // Set the HTTP method
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);          // Add headers
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);          // Return response as a string

    // Execute the request
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);      // Get HTTP status code
    curl_close($ch);

    // Return the HTTP status code and response
    return [
        "status_code" => $http_code,
        "response" => $response
    ];
}
```

***

#### **4. API Call Examples**

**4.1 Fetch Account Information**

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

**Code Example**:

```php
// Fetch account information
$request_path = "/api/config"; // API request path
$response = send_request("GET", $request_path, $base_url, $api_key, $secret_key);

// Process the response
if ($response['status_code'] == 200) {
    echo "Account Information:\n";
    echo $response['response'];
} else {
    echo "Request failed, HTTP Status: " . $response['status_code'] . "\n";
    echo "Response: " . $response['response'];
}
```

***

**4.2 Create an Order**

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

**Code Example**:

```php
// Create an order
$request_path = "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1"; // API request path
$response = send_request("POST", $request_path, $base_url, $api_key, $secret_key);

// Process the response
if ($response['status_code'] == 200) {
    echo "Order created successfully:\n";
    echo $response['response'];
} else {
    echo "Request failed, HTTP Status: " . $response['status_code'] . "\n";
    echo "Response: " . $response['response'];
}
```

***

**4.3 Check Order Status**

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

**Code Example**:

```php
// Check order status
$pay_hash = "abcd1234"; // Replace with the actual order pay_hash
$request_path = "/api/order/" . $pay_hash; // API request path
$response = send_request("GET", $request_path, $base_url, $api_key, $secret_key);

// Process the response
if ($response['status_code'] == 200) {
    echo "Order Status:\n";
    echo $response['response'];
} else {
    echo "Request failed, HTTP Status: " . $response['status_code'] . "\n";
    echo "Response: " . $response['response'];
}
```

***

#### **5. Common Issues**

**5.1 Invalid Signature (401 Unauthorized)**

* Ensure `MF-ACCESS-KEY` matches your API Key.
* Confirm the signature string is constructed as `timestamp + method + requestPath`.
* Ensure the timestamp is in UTC and formatted correctly (e.g., `2024-11-26T12:34:56.789Z`).
* Use the correct **Secret Key** to generate the signature.

**5.2 Invalid Parameters (400 Bad Request)**

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

**5.3 Rate Limit Exceeded (429 Too Many Requests)**

* Mefree API imposes rate limits. Avoid making excessive requests in a short time.
* Add delays or throttle requests if necessary (e.g., limit to 2 requests/second).

***

#### **6. Conclusion**

This guide demonstrates how to efficiently interact with the Mefree.NET API using PHP, including generating signatures, making requests, and handling responses. For critical operations such as placing orders, implementing retry mechanisms is recommended to enhance reliability. For further assistance, contact Mefree's official support team.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mefree.net/getting-started/how-to-buy-energy/php.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
