# 步骤 2：扩展请求

## 选项 1：使用 API 密钥扩展订单

<mark style="color:orange;">`POST`</mark> `https://api.tronsave.io/v2/extend-request`

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

通过[API](https://docs.tronsave.io/chinese/developer/get-api-key)密钥创建新的延长请求订单

**Headers**

<table><thead><tr><th width="171">名称 </th><th width="142">类型</th><th>描述</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="162">名称 </th><th width="105">类型</th><th>描述</th></tr></thead><tbody><tr><td>receiver<mark style="color:red;">*</mark></td><td>String</td><td>接收资源的地址</td></tr><tr><td>extendData<mark style="color:red;">*</mark></td><td>Array</td><td>数组扩展数据。 从 API 预估中获取响应，<a href="step-1-get-extendable-delegates">获取可扩展的委托人</a>。</td></tr><tr><td>resourceType</td><td>String</td><td>“ENERGY”或“BANDWIDTH”，默认： “ENERGY”</td></tr></tbody></table>

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

```json
{
    "error": false,
    "message": "Success",
    "data": {
        "orderId": "6819da2d4d1b2aadb0d44eee"
    }
}
```

{% endtab %}

{% tab title="400: Bad Request Invalid params" %}

```json
{
    "MISSING_PARAMS": "请求体中缺少某些参数",
    "INVALID_PARAMS": "某些参数无效",
    "INTERNAL_ACCOUNT_NOT_FOUND": "内部账户不存在",
    "INTERNAL_BALANCE_ACCOUNT_TOO_LOW": "余额不足",
    "SOME_DELEGATE_CANNOT_EXTEND": "由于某些错误，此委托订单无法扩展。请稍后重试。"
}
```

{% endtab %}

{% tab title="401: Unauthorized Invalid api key" %}

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

{% endtab %}

{% tab title="429: Too many requests Rate limit reached" %}

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

{% endtab %}
{% endtabs %}

**Example**

{% tabs %}
{% tab title="请求体  " %}

```json
    "extendData":[
        {
            "delegator": "TFwUFWr3QV376677Z8VWXxGUAMFSSSSSSS",
            "isExtend": true,
            "extraAmount": 0,
            "extendTo": 1746702000
        },
        {
            "delegator": "TFwUFWr3QV376677Z8VWXxGUAMFFFFFFFF",
            "isExtend": true,
            "extraAmount": 0,
            "extendTo": 1746702000
        },
        ...
    ],
    "receiver": "TFwUFWr3QV376677Z8VWXxGUAMF1111111",
    "resourceType": "BANDWIDTH"
}
```

{% endtab %}

{% tab title="请求头" %}

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

{% endtab %}

{% tab title="成功响应" %}

```json
{
    "error": false,
    "message": "Success",
    "data": {
        "orderId": "6819da2d4d1b2aadb0d44eee"
    }
}
```

{% endtab %}
{% endtabs %}

**示例代码**

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

```javascript
const SendExtendRequest = async (extendTo, maxPriceAccepted) => {
    const url = TRONSAVE_API_URL + `/v2/extend-request`
    // Get estimate extendable delegates
    const estimateResponse = await GetEstimateExtendData(extendTo, maxPriceAccepted)
    const extendData = estimateResponse.data?.extendData
    if (extendData && extendData.length) { 
        const body = {
            extendData: extendData,
            receiver: RECEIVER,
        }
        const data = await fetch(url, {
            method: "POST",
            headers: {
                'apikey': API_KEY,
                "content-type": "application/json",
            },
            body: JSON.stringify(body)
        })
        const response = await data.json()
        /**
         * Example response 
         {
            error: false,
            message: 'Success',
            data: { orderId: '680b5ac7b09a385fb3d582ff' }
            }
         */
        return response
    }
    return []
}
```

{% endtab %}

{% tab title="PHP" %}

```php
function sendExtendRequest(int $extendTo, int $maxPriceAccepted): array {
    $url = TRONSAVE_API_URL . "/v2/extend-request";
    $estimateResponse = getEstimateExtendData($extendTo, $maxPriceAccepted);
    $extendData = $estimateResponse['data']['extendData'] ?? [];

    if (!empty($extendData)) {
        $body = [
            'extendData' => $extendData,
            'receiver' => RECEIVER,
        ];

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

    return [];
}
```

{% endtab %}

{% tab title="Python" %}

```python
def send_extend_request(extend_to: int, max_price_accepted: int) -> Dict[str, Any]:
    """Send extend request"""
    url = f"{TRONSAVE_API_URL}/v2/extend-request"
    headers = {
        'apikey': API_KEY,
        'Content-Type': 'application/json'
    }
    
    estimate_response = get_estimate_extend_data(extend_to, max_price_accepted)
    extend_data = estimate_response.get('data', {}).get('extendData', [])

    if extend_data:
        body = {
            'extendData': extend_data,
            'receiver': RECEIVER,
        }
        
        response = requests.post(url, headers=headers, json=body)
        return response.json()

    return {}
```

{% endtab %}
{% endtabs %}

## 选项 2：使用签名交易扩展订单

<mark style="color:orange;">`POST`</mark> `https://api.tronsave.io/v2/extend-request`

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

**Request Body**

<table><thead><tr><th width="162">名称 </th><th width="169">类型</th><th>描述</th></tr></thead><tbody><tr><td>receiver<mark style="color:red;">*</mark></td><td>String</td><td>接收资源的地址</td></tr><tr><td>extendData<mark style="color:red;">*</mark></td><td>Array</td><td>数组扩展数据。 从 API 预估中获取响应，<a href="step-1-get-extendable-delegates">获取可扩展的委托人</a>。</td></tr><tr><td>resourceType</td><td>String</td><td>“ENERGY”或“BANDWIDTH”，默认： “ENERGY”</td></tr><tr><td>signedTx</td><td>SignedTransaction</td><td>签名交易，请注意它是一个 JSON 对象<br>（在 <a href="../buy-resources-v2/use-signed-transaction/get-signed-transaction">GET SIGNED</a> 中为 signedTx）</td></tr></tbody></table>

**Example**

{% tabs %}
{% tab title="请求体  " %}

```json
    "extendData":[
        {
            "delegator": TGGVrYaT8XoosBEXPp6dmSZkoh11223344,
            "isExtend": true,
            "extraAmount": 0,
            "extendTo": 1746403201
        },
        ...
    ],
    "receiver": "TGGVrYaT8XoosBEXPp6dmSZkoh123456",
    "resourceType": "BANDWIDTH",
    "signedTx": {
      "visible": false,
      "txID": "446eed36e31249b98b201db2e81a3825b185f1a3d8b2fea348b24fc021e58e0d",
      "raw_data": {
        "contract": [
          {
            "parameter": {
              "value": {
                "amount": 5500000,
                "owner_address": "417a0d868d1418c9038584af1252f85d486502eec0",
                "to_address": "41055756f33f419278d9ea059bd2b21120e6add748"
              },
              "type_url": "type.googleapis.com/protocol.TransferContract"
            },
            "type": "TransferContract"
          }
        ],
        "ref_block_bytes": "0713",
        "ref_block_hash": "6c5f7686f4176139",
        "expiration": 1691465106000,
        "timestamp": 1691465046758
      },
      "raw_data_hex": "0a02071322086c5f7686f417613940d084b5999d315a68080112640a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412330a15417a0d868d1418c9038584af1252f85d486502eec0121541055756f33f419278d9ea059bd2b21120e6add74818e0fcb70670e6b5b1999d31",
      "signature": ["xxxxxxxxx"]
    }
}
```

{% endtab %}

{% tab title="成功响应" %}

```json
{
    "error": false,
    "message": "Success",
    "data": {
        "orderId": "6819da2d4d1b2aadb0d44eee"
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}

* 要创建签名交易，请按照此处的说明操作。
* 签名所需的 TRX 数量在 [**Get Extendable Delegates**](https://docs.tronsave.io/chinese/developer/extend-orders-v2/step-1-get-extendable-delegates) API 响应的 **total\_estimate\_trx** 字段中提供。-
  {% endhint %}

***Example Code***

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

```javascript
const SendExtendRequest = async (extendTo, maxPriceAccepted) => {
    const url = TRONSAVE_API_URL + `/v2/extend-request`
    // Get estimate extendable delegates
    const estimateResponse = await GetEstimateExtendData(REQUESTER_ADDRESS, extendTo, maxPriceAccepted)
    const extendData = estimateResponse.data?.extendData
    // check if there are extendable delegates
    if (extendData && extendData.length) { 
        const totalEstimateTrx = estimateResponse.data?.totalEstimateTrx
        // Build a signed transaction by using the private key
        const signedTx = await GetSignedTx(totalEstimateTrx)
        const body = {
            extendData: extendData,
            receiver: RECEIVER,
            signedTx
        }
        const data = await fetch(url, {
            method: "POST",
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(body)
        })
        const response = await data.json()
        /**
         * Example response 
         {
            error: false,
            message: 'Success',
            data: { orderId: '680b5ac7b09a385fb3d582ff' }
            }
         */
        return response
    }
    return []
}
```

{% endtab %}

{% tab title="PHP" %}

```php
function sendExtendRequest(int $extendTo, int $maxPriceAccepted): array {
    $url = TRONSAVE_API_URL . "/v2/extend-request";
    $estimateResponse = getEstimateExtendData(REQUESTER_ADDRESS, $extendTo, $maxPriceAccepted);
    $extendData = $estimateResponse['data']['extendData'] ?? [];

    if (!empty($extendData)) {
        $totalEstimateTrx = $estimateResponse['data']['totalEstimateTrx'];
        $signedTx = getSignedTx($totalEstimateTrx);

        $body = [
            'extendData' => $extendData,
            'receiver' => RECEIVER,
            'signedTx' => $signedTx
        ];

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

    return [];
}
```

{% endtab %}

{% tab title="Python" %}

```python
def send_extend_request(extend_to: int, max_price_accepted: int) -> Dict[str, Any]:
    """Send extend request"""
    url = f"{TRONSAVE_API_URL}/v2/extend-request"
    
    estimate_response = get_estimate_extend_data(REQUESTER_ADDRESS, extend_to, max_price_accepted)
    extend_data = estimate_response.get('data', {}).get('extendData', [])

    if extend_data:
        total_estimate_trx = estimate_response['data']['totalEstimateTrx']
        signed_tx = get_signed_tx(total_estimate_trx)

        body = {
            'extendData': extend_data,
            'receiver': RECEIVER,
            'signedTx': signed_tx
        }
        
        response = requests.post(url, json=body)
        return response.json()

    return {}
```

{% endtab %}
{% endtabs %}
