# Levantamento de fundos

### Autenticação

Uma chave de API separada deve ser usada para autenticação. Ela pode ser gerada na seção «Segurança» nas configurações da sua conta. A chave é exibida apenas uma vez, portanto certifique-se de armazená-la em um local seguro e não a divulgue.

### O que o método permite fazer

* Cria uma solicitação de saque na moeda especificada.
* Intervalo mínimo entre solicitações — 12 segundos.

### Ponto de extremidade

<mark style="color:verde;">`POST`</mark> `https://api.cryptocloud.plus/v2/invoice/api/out/create`

### Cabeçalhos

| Nome                                               | Tipo   | Exemplo                             | Descrição                                                        |
| -------------------------------------------------- | ------ | ----------------------------------- | ---------------------------------------------------------------- |
| Autorização<mark style="color:vermelho;">\*</mark> | string | Token eyJ0eXAiOiJK<...>4npi1ksS8tSY | Chave de API da seção «Segurança» nas configurações da sua conta |

### Corpo da solicitação

Parâmetros-chave

| Nome                                                  | Tipo   | Exemplo                        | Descrição                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------------------------------------------- | ------ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| currency\_code<mark style="color:vermelho;">\*</mark> | string | ETH                            | <p>Código da moeda:</p><p></p><p>BTC, LTC, TRX, SOL, TON, BNB, ETH, ETH\_ARB, ETH\_BASE, ETH\_OPT, USDT\_ARB, USDT\_BSC, USDT\_ERC20, USDT\_OPT, USDT\_SOL, USDT\_TON, USDT\_TRC20, USDC\_ARB, USDC\_BASE, USDC\_BSC, USDC\_ERC20, USDC\_OPT, USDC\_SOL, DAI\_ARB, DAI\_BASE, DAI\_BSC, DAI\_ERC20, DAI\_OPT, USDD\_TRC20, PYUSD\_ERC20, PYUSD\_SOL, XAUT\_ERC20, XAUT\_TON, ARB\_ARB, OP\_OPT, PEPE\_BSC, PEPE\_ERC20, SHIB\_BSC, SHIB\_ERC20, TRUMP\_SOL</p> |
| to\_address<mark style="color:vermelho;">\*</mark>    | string | 0x396343<...>210945346fb82Aa49 | Endereço da carteira do destinatário                                                                                                                                                                                                                                                                                                                                                                                                                           |
| amount<mark style="color:vermelho;">\*</mark>         | float  | 0.003                          | Valor da solicitação de saque na moeda especificada                                                                                                                                                                                                                                                                                                                                                                                                            |

### Exemplos de solicitação

Estes exemplos mostram como criar uma solicitação de saque.

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

```bash
curl -X POST \
  https://api.cryptocloud.plus/v2/invoice/api/out/create \
  -H 'Authorization: Token YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "currency_code": "BTC",
    "to_address": "YOUR_RECIPIENT_ADDRESS",
    "amount": 0.00023
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
from typing import Optional


class PayoutAPIClient:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = 'https://api.cryptocloud.plus'
        self.headers = {
            'Authorization': f'Token {self.api_key}',
            'Content-Type': 'application/json'
        }

    def create_payout(self, currency_code: str, to_address: str, amount: float) -> dict:
        """
        Cria uma solicitação de saque.

        :param currency_code: Código da moeda (por exemplo, “BTC”, “ETH”, “USDT”, “LTC”).
        :param to_address: Endereço do destinatário.
        :param amount: Valor a enviar.
        :return: Resposta da API no formato dict.
        """
        url = f"{self.base_url}/v2/invoice/api/out/create"
        payload = {
            "currency_code": currency_code,
            "to_address": to_address,
            "amount": amount
        }

        response = requests.post(url, json=payload, headers=self.headers)

        if response.status_code == 200:
            return response.json()
        else:
            raise PayoutAPIError(response.status_code, response.json())


class PayoutAPIError(Exception):
    def __init__(self, status_code: int, error_data: Optional[dict] = None):
        self.status_code = status_code
        self.error_data = error_data or {}
        message = f"A solicitação da API falhou com o status {status_code}: {self.error_data}"
        super().__init__(message)


# Exemplo de uso:
if __name__ == "__main__":
    # Configuração do cliente
    api_key = ""

    client = PayoutAPIClient(api_key)

    try:
        result = client.create_payout(
            currency_code="BTC",
            to_address="",
            amount=0.00023
        )
        print("Sucesso:", result)
    except PayoutAPIError as e:
        print("Ocorreu um erro:", e)
```

{% endtab %}

{% tab title="JavaScript " %}
{% code title="Axios.js:" %}

```javascript
/**
 * Erro personalizado para tratar falhas na resposta da API de saques.
 */
class PayoutAPIError extends Error {
  /**
   * @param {number} statusCode - Código de status HTTP retornado pela API.
   * @param {object} [errorData={}] - Detalhes do erro retornados pela API.
   */
  constructor(statusCode, errorData = {}) {
    super(`A solicitação da API falhou com o status ${statusCode}: ${JSON.stringify(errorData)}`);
    this.name = 'PayoutAPIError';
    this.statusCode = statusCode;
    this.errorData = errorData;
  }
}

/**
 * Cliente para interagir com a API de Saques da CryptoCloud.
 */
class PayoutAPIClient {
  /**
   * @param {string} apiKey - Token da API usado para autenticação.
   */
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.cryptocloud.plus';
    this.headers = {
      'Authorization': `Token ${this.apiKey}`,
      'Content-Type': 'application/json'
    };
  }

  /**
   * Cria uma solicitação de saque.
   *
   * @param {string} currencyCode - Código da moeda (por exemplo, "BTC", "ETH", "USDT", "LTC").
   * @param {string} toAddress - Endereço do destinatário.
   * @param {number} amount - Valor a enviar.
   * @returns {Promise<object>} - Dados da resposta da API.
   * @throws {PayoutAPIError} - Em caso de falha na solicitação.
   */
  async createPayout(currencyCode, toAddress, amount) {
    const url = `${this.baseUrl}/v2/invoice/api/out/create` ;
    const payload = {
      currency_code: currencyCode,
      to_address: toAddress,
      amount: amount
    };

    try {
      const response = await axios.post(url, payload, {
        headers: this.headers
      });
      return response.data;
    } catch (error) {
      const status = error.response?.status || 500;
      const data = error.response?.data || {};
      throw new PayoutAPIError(status, data);
    }
  }
}

// Exemplo de uso com Axios
(async () => {
  const client = new PayoutAPIClient('<your_api_key_here>');

  try {
    const result = await client.createPayout("BTC", "<recipient_address>", 0.00023);
    console.log("Sucesso:", result);
  } catch (error) {
    console.error("Ocorreu um erro:", error);
  }
})();
```

{% endcode %}

{% code title="Fetch.js:" %}

```javascript
const apiKey = '<your_api_key>';
const payload = {
  currency_code: 'BTC',
  to_address: '<recipient_address>',
  amount: 0.00023
};

fetch('https://api.cryptocloud.plus/v2/invoice/api/out/create', {
  method: 'POST',
  headers: {
    'Authorization': `Token ${apiKey}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(payload)
})
  .then(response => {
    if (!response.ok) throw new Error(`Erro HTTP ${response.status}`);
    return response.json();
  })
  .then(data => console.log('Sucesso:', data))
  .catch(err => console.error('Erro:', err));
```

{% endcode %}

{% code title="Ajax.js:" %}

```javascript
const apiKey = '<your_api_key>';
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.cryptocloud.plus/v2/invoice/api/out/create");
xhr.setRequestHeader("Authorization", `Token ${apiKey}`);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log("Sucesso:", JSON.parse(xhr.responseText));
  } else {
    console.error("Erro:", xhr.status, xhr.responseText);
  }
};

const payload = {
  currency_code: 'BTC',
  to_address: '<recipient_address>',
  amount: 0.00023
};

xhr.send(JSON.stringify(payload));
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}

<pre class="language-php" data-title="PHP 8.0 +"><code class="lang-php"><strong>&#x3C;?php
</strong>
/**
 * Classe PayoutAPIError
 *
 * Exceção personalizada para erros da API.
 */
class PayoutAPIError extends Exception
{
    public int $statusCode;
    public array $errorData;

    /**
     * Construtor de PayoutAPIError.
     *
     * @param int $statusCode
     * @param array $errorData
     */
    public function __construct(int $statusCode, array $errorData = [])
    {
        $this->statusCode = $statusCode;
        $this->errorData = $errorData;
        $message = "A solicitação da API falhou com o status $statusCode: " . json_encode($errorData);
        parent::__construct($message, $statusCode);
    }
}

/**
 * Classe PayoutAPIClient
 *
 * Cliente para criar saques de criptomoedas via a API da CryptoCloud.
 */
class PayoutAPIClient
{
    private string $apiKey;
    private string $baseUrl;
    private array $headers;

    /**
     * Construtor de PayoutAPIClient.
     *
     * @param string $apiKey
     */
    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->baseUrl = 'https://api.cryptocloud.plus';
        $this->headers = [
            'Authorization: Token ' . $this->apiKey,
            'Content-Type: application/json'
        ];
    }

    /**
     * Criar solicitação de saque.
     *
     * @param string $currencyCode Código da moeda (por exemplo, BTC, ETH).
     * @param string $toAddress Endereço do destinatário.
     * @param float $amount Valor a enviar.
     * @return array Resposta da API.
     * @throws PayoutAPIError Em caso de falha na API.
     */
    public function createPayout(string $currencyCode, string $toAddress, float $amount): array
    {
        $url = $this->baseUrl . '/v2/invoice/api/out/create';

        $payload = json_encode([
            'currency_code' => $currencyCode,
            'to_address' => $toAddress,
            'amount' => $amount,
        ]);

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $decoded = json_decode($response, true);

        curl_close($ch);

        if ($httpCode === 200) {
            return $decoded;
        } else {
            throw new PayoutAPIError($httpCode, $decoded ?? []);
        }
    }
}

// Exemplo de uso
try {
    $client = new PayoutAPIClient('&#x3C;your_api_key_here>');
    $response = $client->createPayout('BTC', '&#x3C;recipient_address>', 0.00023);
    echo "Sucesso:\n";
    print_r($response);
} catch (PayoutAPIError $e) {
    echo "Ocorreu um erro:\n" . $e->getMessage();
}
</code></pre>

{% endtab %}
{% endtabs %}

### Exemplo de resposta

Uma solicitação bem-sucedida retorna uma resposta com o estado `sucesso` e um `resultado` objeto.

{% tabs %}
{% tab title="200: OK – Solicitação criada" %}

```json
{
    "estado": "sucesso",
    "result": {
        "uuid": "INV-2Q2SICZN",
        "created": "2026-01-01 08:03:02.216905",
        "address": "TT2T11KZhoDu48i2p4FWxfG79zdkEWkU9N",
        "currency": {
            "id": 4,
            "code": "USDT",
            "fullcode": "USDT_TRC20",
            "network": {
                "code": "TRC20",
                "id": 4,
                "icon": "https://cdn.cryptocloud.plus/img/network/TRC20.svg",
                "fullname": "Tron"
            },
            "name": "Tether",
            "is_email_required": false,
            "stablecoin": true,
            "icon_base": "https://cdn.cryptocloud.plus/img/currency/USDT.svg",
            "icon_network": "https://cdn.cryptocloud.plus/img/currency_network/USDT_TRC.svg",
            "icon_qr": "https://cdn.cryptocloud.plus/img/stroke/USDT_STROKE.svg",
            "order": 1
        },
        "date_finished": null,
        "expiry_date": null,
        "side_commission": "client",
        "side_commission_cc": "merchant",
        "type_payments": "crypto",
        "status": "created",
        "invoice_status": "start",
        "is_email_required": false,
        "project": {
            "id": 1,
            "name": "Test",
            "fail": "https://test.com/failed-payment",
            "success": "https://test.com/successful-payment",
            "logo": ""
        },
        "tx_list": [],
        "step": 1,
        "test_mode": false,
        "type": "dw",
        "user_email": "",
        "pay_url": "None",
        "phone": "",
        "order_id": "None",
        "amount_in_crypto": null,
        "amount_in_fiat": 0,
        "amount": 10.0,
        "amount_usd": 10.0,
        "amount_to_pay": 10.0,
        "amount_to_pay_usd": 10.0,
        "amount_paid": 0.0,
        "amount_paid_usd": 0.0,
        "fee": 0.0,
        "fee_usd": 0.0,
        "service_fee": 0.0,
        "service_fee_usd": 0.0,
        "received": 0,
        "received_usd": 0,
        "to_surcharge": 10.0,
        "to_surcharge_usd": 10.0,
        "total_rub": 0,
        "currency_list": [
            {
                "code": "USDT",
                "fullcode": "USDT_TRC20",
                "name": "Tether",
                "is_email_required": false,
                "stablecoin": true,
                "icon_base": "https://cdn.cryptocloud.plus/img/currency/USDT.svg",
                "icon_qr": "https://cdn.cryptocloud.plus/img/stroke/USDT_STROKE.svg",
                "order": 28,
                "network": [
                    {
                        "code": "TRC20",
                        "id": 4,
                        "icon": "https://cdn.cryptocloud.plus/img/network/TRC20.svg",
                        "fullname": "Tron"
                    }
                ]
            }
        ],
        "aml_enabled": false,
        "aml_side": "merchant",
        "aml_cost": 0.0,
        "aml_cost_usd": 0.0,
        "aml_checks": [],
        "links": [],
        "quiz_result": false,
        "quiz_detail": {
            "invoice": null,
            "rating": null,
            "comment": null,
            "created": null
        },
        "memo": ""
    }
}
```

{% endtab %}
{% endtabs %}

### Descrição do parâmetro

O `resultado` objeto contém:

<table data-full-width="false"><thead><tr><th>Nome</th><th>Tipo</th><th>Exemplo</th><th>Descrição</th></tr></thead><tbody><tr><td>invoice_id</td><td>string</td><td>INV-89UX09KA</td><td>Identificador único da solicitação de saque com o prefixo INV</td></tr><tr><td>estado</td><td>string</td><td>criado</td><td>Status da solicitação de saque — sempre <code>criado</code> quando a solicitação é enviada</td></tr><tr><td>currency</td><td>string</td><td>ETH</td><td>Código da criptomoeda selecionada na solicitação de saque</td></tr><tr><td>amount</td><td>float</td><td>0.0029</td><td>Valor da solicitação de saque em criptomoeda</td></tr></tbody></table>


---

# 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.cryptocloud.plus/pt/referencia-da-api-v2/withdrawals.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.
