# 购买能源

要使用此功能，您必须拥有API密钥。请[在此处](/chinese/developer/get-api-key.md)了解如何获取我们的API密钥

## **TronSave 使用API密钥购买**

## 通过API密钥创建新的购买能源订单

<mark style="color:green;">`POST`</mark> `https://api.tronsave.io/v2/buy-resource`

通过[API](/chinese/developer/get-api-key.md)密钥创建新的购买能源订单

速率限制 (Rate limit): 每1秒15个请求。

#### Headers

<table><thead><tr><th width="170">Name</th><th width="143">Type</th><th>Description</th></tr></thead><tbody><tr><td>apikey<mark style="color:red;">*</mark></td><td>String</td><td>Tronsave API密钥，用于内部帐户。</td></tr></tbody></table>

#### Request Body

<table><thead><tr><th width="207.33333333333331">域</th><th width="99">类型</th><th width="439.6666666666667">描述</th></tr></thead><tbody><tr><td>resourceType</td><td>string</td><td>“ENERGY”或“BANDWIDTH”，默认： “ENERGY”</td></tr><tr><td>unitPrice</td><td>number</td><td><p>“FAST”、“MEDIUM”、“SLOW”, 或者一个数字。<strong>默认值： “MEDIUM”</strong></p><ul><li>“FAST”：如果市场准备填充度 = 100%，则 FAST = MEDIUM；如果市场准备填充度 &#x3C; 100%，则 FAST = MEDIUM + 10；如果市场准备填充度 = 0%，则 FAST = SLOW + 20。</li><li>“MEDIUM”：此订单的最大市场填充量对应的最低价格。如果市场准备填充度 = 0%，则 MEDIUM = SLOW + 10。</li><li>“SLOW”：此订单可以设置的最低价格。</li><li>如果价格是一个数字，则价格单位为 SUN。</li></ul></td></tr><tr><td>resourceAmount<mark style="color:red;">*</mark></td><td>number</td><td>资源数量</td></tr><tr><td>receiver<mark style="color:red;">*</mark></td><td>string</td><td>资源接收者的地址。</td></tr><tr><td>durationSec</td><td>number</td><td>购买资源的持续时间，时间单位为秒。默认值：259200（3天）。</td></tr><tr><td>sponsor</td><td>string</td><td>赞助代码</td></tr><tr><td>options</td><td>Object</td><td><em>optional</em></td></tr><tr><td>options.onlyCreateWhenFulfilled</td><td>Boolean</td><td><p>[true] => 仅在订单能够完成时创建订单</p><p>[false] => 即使订单无法完成也会创建订单</p><p>默认值：false</p></td></tr><tr><td>options.allowPartialFill</td><td>Boolean</td><td>允许订单部分匹配或整体匹配。</td></tr><tr><td>options.preventDuplicateIncompleteOrders</td><td>Boolean</td><td><p>[true]=>仅在不存在具有相同参数的未完成订单时创建订单。</p><p>[false]=>无论是否存在未完成订单，始终创建新订单。</p><p>默认值：false</p></td></tr><tr><td>options.maxPriceAccepted</td><td>number</td><td>仅在预估价格小于该值时创建订单。</td></tr><tr><td>options.minResourceDelegateRequiredAmount</td><td>number</td><td>单个提供者委托的最小能量数量。</td></tr></tbody></table>

{% tabs %}
{% tab title="200: OK 成功 (Success)" %}
如果成功，返回订单ID。

```javascript
{
    "error": false,
    "message": "Success",
    "data": {
        "orderId": "6818426a65fa8ea36d119d2c"
    }
}
```

{% endtab %}

{% tab title="400: Bad Request 无效的参数 (Invalid params)" %}

```javascript
{
    "MISSING_PARAMS": "请求体中缺少某些参数",
    "INVALID_PARAMS": "某些参数无效",
    "MIN_PRICE_INVALID": "minPrice 小于系统的最低价格或格式不正确。",
    "INTERNAL_ACCOUNT_NOT_FOUND": "内部账户不存在",
    "INTERNAL_BALANCE_ACCOUNT_TOO_LOW": "余额不足",
    "CANNOT_FULFILLED": "订单需要立即完全匹配，但系统无法满足 100% 的需求。",
    "MUST_BE_WAIT_PREVIOUS_ORDER_FILLED": "系统中已经存在具有相同参数的待处理订单。",
    "PRICE_EXCEED_MAX_PRICE_REQUIRED": "订单价格超过了最大可接受价格。"
}
```

{% endtab %}

{% tab title="401: Unauthorized 无效的API密钥 (Invalid API key)" %}

```javascript
{
"API_KEY_REQUIRED": "请求头中缺少API密钥",
"INVALID_API_KEY": "API密钥不正确"
}
```

{% endtab %}

{% tab title="429: Too Many Requests 已达到速率限制 (Rate limit reached)" %}

```javascript
{
"RATE_LIMIT": "已达到速率限制"
}
```

{% endtab %}
{% endtabs %}

**例子 (*****Example)***

{% tabs %}
{% tab title="Body" %}

```javascript
{
    "resourceType": "ENERGY",
    "receiver": "TFFbwz3UpmgaPT4UudwsxbiJf63t777777",
    "durationSec": 3600,
    "resourceAmount": 32000,
    "unitPrice": "MEDIUM",
    "options": {
        "allowPartialFill": true,
        "onlyCreateWhenFulfilled": true,
        "preventDuplicateIncompleteOrders": false,
        "maxPriceAccepted": 100,
        "minResourceDelegateRequiredAmount": 100000
    }
}
```

{% endtab %}

{% tab title="Headers" %}

```javascript
{
  "apikey": <YOUR_API_KEY>
}
```

{% endtab %}

{% tab title="Success Response" %}

```javascript
{
    "error": false,
    "message": "Success",
    "data": {
        "orderId": "6818426a65fa8ea36d119d2c"
    }
}
```

{% endtab %}
{% endtabs %}

*Example Code*

{% tabs %}
{% tab title="Javascript" %}

```javascript
const BuyResource = async (apiKey, receiverAddress, resourceAmount, durationSec, maxPriceAccepted) => {
    const url = `${TRONSAVE_API_URL}/v2/buy-resource`
    const body = {
        resourceType: RESOURCE_TYPE,
        unitPrice: "MEDIUM", // 价格单位为 sun 或者 "SLOW"|"MEDIUM"|"FAST"
        resourceAmount, // 想要购买的资源数量
        receiver: receiverAddress,
        durationSec, // 订单持续时间（秒）。默认值：259200（3天）
        options: {
            allowPartialFill: true, // 允许部分匹配
            onlyCreateWhenFulfilled: false, // 只有在订单可完全匹配时才创建
            maxPriceAccepted, // 最大可接受价格
        }
    }
    const data = await fetch(url, {
        method: "POST",
        headers: {
            'apikey': apiKey,
            "content-type": "application/json",
        },
        body: JSON.stringify(body)
    })
    const response = await data.json()
    /**
     * 示例响应
     * {
     *     "error": false,
     *     "message": "成功",
     *     "data": {
     *         "orderId": "6809fdb7b9...a41d726fd"
     *     }
     * }
     */
    return response
}

```

{% endtab %}

{% tab title="PHP" %}

```php
function buyResource($apiKey, $receiverAddress, $resourceAmount, $durationSec, $maxPriceAccepted) {
    $url = TRONSAVE_API_URL . "/v2/buy-resource";
    $body = [
        'resourceType' => RESOURCE_TYPE,
        'unitPrice' => "MEDIUM",
        'resourceAmount' => $resourceAmount,
        'receiver' => $receiverAddress,
        'durationSec' => $durationSec,
        'options' => [
            'allowPartialFill' => true,
            'onlyCreateWhenFulfilled' => false,
            'maxPriceAccepted' => $maxPriceAccepted,
        ]
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($body),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'apikey: ' . $apiKey,
            'Content-Type: application/json'
        ]
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

```

{% endtab %}

{% tab title="Python" %}

```python
def buy_resource(amount: int, duration_sec: int, max_price_accepted: int) -> Dict[str, Any]:
    """Buy resource"""
    url = f"{TRONSAVE_API_URL}/v2/buy-resource"
    headers = {
        'apikey': API_KEY,
        'Content-Type': 'application/json'
    }
    
    body = {
        'resourceType': RESOURCE_TYPE,
        'unitPrice': "MEDIUM",
        'amount': amount,
        'receiver': RECEIVER_ADDRESS,
        'durationSec': duration_sec,
        'options': {
            'allowPartialFill': True,
            'onlyCreateWhenFulfilled': False,
            'maxPriceAccepted': max_price_accepted,
        }
    }
    
    response = requests.post(url, headers=headers, json=body)
    return response.json()
```

{% endtab %}
{% endtabs %}


---

# 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.tronsave.io/chinese/developer/buy-resources-v2/use-api-key/buy-energy.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.
