# PHP 调用示例

### **前提条件**

1. [您需要一个有效的 API Key 和 API Secret](/getting-started/buy-energy-via-api-on-catfee/api-overview.md#apply-api-info)。
2. 确保您的环境已安装 `cURL` 扩展（大多数 PHP 安装默认包含该扩展）。

### **示例代码**

```php
<?php

$API_KEY = "your_api_key";  // 请替换为您的API Key
$API_SECRET = "your_api_secret";  // 请替换为您的API Secret
$BASE_URL = "https://api.catfee.io";

// 生成当前的时间戳（ISO 8601格式）
function generateTimestamp() {
    return gmdate("Y-m-d\TH:i:s.000\Z");
}

// 构建请求路径，包括查询参数
function buildRequestPath($path, $queryParams) {
    if (empty($queryParams)) {
        return $path;
    }
    $queryString = http_build_query($queryParams);
    return $path . '?' . $queryString;
}

// 使用 HMAC-SHA256 算法生成签名
function generateSignature($timestamp, $method, $requestPath) {
    $signString = $timestamp . $method . $requestPath;
    return base64_encode(hash_hmac('sha256', $signString, $GLOBALS['API_SECRET'], true));
}

// 创建 HTTP 请求
function createRequest($url, $method, $timestamp, $signature) {
    $headers = [
        "Content-Type: application/json",
        "CF-ACCESS-KEY: " . $GLOBALS['API_KEY'],
        "CF-ACCESS-SIGN: " . $signature,
        "CF-ACCESS-TIMESTAMP: " . $timestamp
    ];

    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    switch (strtoupper($method)) {
        case "POST":
            curl_setopt($ch, CURLOPT_POST, true);
            break;
        case "GET":
            curl_setopt($ch, CURLOPT_HTTPGET, true);
            break;
        case "PUT":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            break;
        case "DELETE":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            break;
        default:
            throw new Exception("Unsupported HTTP method: $method");
    }

    $response = curl_exec($ch);

    // 检查是否请求成功
    if (curl_errno($ch)) {
        throw new Exception("cURL error: " . curl_error($ch));
    }

    curl_close($ch);
    
    return $response;
}

function main() {
    $method = "POST";  // 可以修改为 "GET", "PUT", "DELETE" 等方法
    $path = "/v1/order";

    // 示例：创建订单
    $queryParams = [
        "quantity" => "65000",
        "receiver" => "TRON_ADDRESS",
        "duration" => "1h"
    ];

    // 生成请求头
    $timestamp = generateTimestamp();
    $requestPath = buildRequestPath($path, $queryParams);
    $signature = generateSignature($timestamp, $method, $requestPath);

    // 创建请求 URL
    $url = $BASE_URL . $requestPath;

    // 发送请求
    try {
        $response = createRequest($url, $method, $timestamp, $signature);
        echo "Response Code: 200\n";
        echo "Response Body: $response\n";
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

// 执行主函数
main();

?>
```

### **代码解析**

1. **`generateTimestamp()`**：\
   该函数返回当前 UTC 时间戳（ISO 8601 格式）。我们使用 `gmdate("Y-m-d\TH:i:s.000\Z")` 来生成时间戳。
2. **`buildRequestPath()`**：\
   该函数构建请求路径，包括查询参数（如果有）。查询参数通过 `http_build_query()` 来构建 URL 编码字符串，不进行排序。
3. **`generateSignature()`**：\
   使用 `timestamp`、`method` 和 `requestPath` 拼接成签名字符串，并通过 `hash_hmac()` 方法使用 HMAC-SHA256 算法对其进行加密，最后对结果进行 Base64 编码。
4. **`createRequest()`**：\
   根据请求方法（`POST`、`GET`、`PUT`、`DELETE`）构建并发送 HTTP 请求。通过 `curl_setopt()` 设置相应的 HTTP 请求类型，并设置请求头。`curl_exec()` 发送请求并返回响应。
5. **`main()`**：\
   在 `main()` 函数中，设置请求方法为 `POST`，并构建查询参数。生成时间戳、签名和请求路径后，调用 `createRequest()` 函数发送请求并打印响应。

### **注意事项**

* **API Key 和 Secret**：\
  请确保将 `API_KEY` 和 `API_SECRET` 替换为您从 CatFee.IO 获取的实际值。
* **错误处理**：\
  使用 `try-catch` 捕获并打印可能出现的异常，如 `cURL` 错误。
* **请求方法**：\
  当前示例支持 `POST`、`GET`、`PUT` 和 `DELETE` 方法，您可以根据实际需求修改请求方法。
* **响应处理**：\
  `curl_exec()` 会返回响应体，您可以根据实际情况进一步解析响应数据（如 JSON 格式）。

### **总结**

此示例展示了如何使用 PHP 调用 CatFee.IO Rest API，利用 HMAC-SHA256 签名确保请求的安全性。通过 `cURL` 发送请求，支持 `GET`、`POST`、`PUT` 和 `DELETE` 等 HTTP 方法，您可以根据需要调整代码。


---

# 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.catfee.io/getting-started/buy-energy-via-api-on-catfee/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.
