# Consultar saldo — Delta Wallet

Consulte a carteira, os saldos disponíveis e a tabela de tarifas da conta.

URL: https://deltaapplications.com.br/docs/saldo
Base da API: https://api.deltaapplications.com.br/api/v1/wallet

Exemplos fictícios; endpoints de produção. Chaves somente no servidor.

Endpoint: GET /balance

## Requisição

Não recebe corpo nem parâmetros obrigatórios. O alias /saldo retorna o mesmo recurso.

### GET /balance

### TypeScript

```typescript
// Node.js 20+ · execute no servidor
const key = process.env.DELTA_WALLET_KEY;
if (!key) throw new Error("Defina DELTA_WALLET_KEY");

const response = await fetch("https://api.deltaapplications.com.br/api/v1/wallet/balance", {
  method: "GET",
  headers: {
    "X-Wallet-Key": key,
    "Accept": "application/json",
  },
  signal: AbortSignal.timeout(15_000),
  redirect: "error",
});

const data: Record<string, unknown> = await response.json();
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${data.error ?? "Falha na API"}`);
}
// Persista os IDs no seu servidor. Não registre chaves nem dados pessoais.
// Em timeout, repita o POST apenas com o mesmo Idempotency-Key ou consulte a operação.
```

### JavaScript

```javascript
// Node.js 20+ · execute no servidor
const key = process.env.DELTA_WALLET_KEY;
if (!key) throw new Error("Defina DELTA_WALLET_KEY");

const response = await fetch("https://api.deltaapplications.com.br/api/v1/wallet/balance", {
  method: "GET",
  headers: {
    "X-Wallet-Key": key,
    "Accept": "application/json",
  },
  signal: AbortSignal.timeout(15_000),
  redirect: "error",
});

const data = await response.json();
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${data.error ?? "Falha na API"}`);
}
// Persista os IDs no seu servidor. Não registre chaves nem dados pessoais.
// Em timeout, repita o POST apenas com o mesmo Idempotency-Key ou consulte a operação.
```

### Python

```python
# Python 3 · biblioteca padrão · execute no servidor
import json
import os
from urllib.error import HTTPError
from urllib.request import Request, HTTPRedirectHandler, build_opener

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Do not forward credentials to another address.

key = os.environ["DELTA_WALLET_KEY"]
headers = {
    "X-Wallet-Key": key,
    "Accept": "application/json",
}
request = Request(
    "https://api.deltaapplications.com.br/api/v1/wallet/balance",
    method="GET",
    headers=headers,
)

try:
    with build_opener(NoRedirect()).open(request, timeout=15) as response:
        data = json.load(response)
except HTTPError as error:
    # Preserve o status para diagnóstico, sem expor credenciais.
    raise RuntimeError(f"Delta Wallet: HTTP {error.code}") from error

# Use data no servidor. Em timeout, repita o POST só com o mesmo Idempotency-Key.
```

### Go

```go
// Go 1.20+ · biblioteca padrão
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "time"
)

func run() error {
    key := os.Getenv("DELTA_WALLET_KEY")
    if key == "" { return fmt.Errorf("defina DELTA_WALLET_KEY") }
    client := &http.Client{
        Timeout: 15 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    req, err := http.NewRequest("GET", "https://api.deltaapplications.com.br/api/v1/wallet/balance", nil)
    if err != nil { return err }
    req.Header.Set("X-Wallet-Key", key)
    req.Header.Set("Accept", "application/json")
    res, err := client.Do(req)
    if err != nil { return err } // Em timeout, repita só com o mesmo Idempotency-Key.
    defer res.Body.Close()
    if res.StatusCode < 200 || res.StatusCode >= 300 {
        return fmt.Errorf("Delta Wallet: HTTP %d", res.StatusCode)
    }
    var data map[string]any
    if err := json.NewDecoder(io.LimitReader(res.Body, 2 << 20)).Decode(&data); err != nil {
        return err
    }
    // Use data no servidor; persista IDs sem registrar segredos.
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
```

### PHP

```php
<?php
// PHP 8+ com extensão cURL · execute no servidor
$key = getenv('DELTA_WALLET_KEY');
if (!$key) { throw new RuntimeException('Defina DELTA_WALLET_KEY'); }

$ch = curl_init('https://api.deltaapplications.com.br/api/v1/wallet/balance');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_HTTPHEADER => [
        'X-Wallet-Key: ' . $key,
        'Accept: application/json',
    ],
]);
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$failed = $raw === false;
curl_close($ch);
if ($failed) { throw new RuntimeException('Falha de comunicação; repita só com o mesmo Idempotency-Key.'); }
if ($status < 200 || $status >= 300) {
    throw new RuntimeException('Delta Wallet: HTTP ' . $status);
}
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
// Use $data no servidor. Não registre chaves nem dados pessoais.
```

### C#

```csharp
// C# · .NET 8 · aplicação de console no servidor
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;

var key = Environment.GetEnvironmentVariable("DELTA_WALLET_KEY")
    ?? throw new InvalidOperationException("Defina DELTA_WALLET_KEY");
using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) };
using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.deltaapplications.com.br/api/v1/wallet/balance");
request.Headers.Add("X-Wallet-Key", key);
request.Headers.Add("Accept", "application/json");

using var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
    throw new HttpRequestException($"Delta Wallet: HTTP {(int)response.StatusCode}");
using var data = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
// Use data.RootElement no servidor. Não exponha credenciais.
// Em timeout, repita o POST só com o mesmo Idempotency-Key.
```

### cURL

```bash
curl --request GET 'https://api.deltaapplications.com.br/api/v1/wallet/balance' \
  --max-time 15 \
  --header "X-Wallet-Key: $DELTA_WALLET_KEY" \
  --header 'Accept: application/json'
```

## Resposta

Resposta ilustrativa (campos relevantes):

```json
{
  "walletId": "wallet_exemplo",
  "status": "ACTIVE",
  "isActivated": true,
  "requiresActivation": false,
  "subaccountReady": true,
  "balance": {
    "availableCentavos": 15000,
    "pendingCentavos": 0,
    "lockedCentavos": 0,
    "spendableCentavos": 15000,
    "availableReais": 150,
    "pendingReais": 0,
    "lockedReais": 0,
    "spendableReais": 150,
    "updatedAt": "2026-10-25T12:00:00.000Z"
  },
  "pricing": {
    "cashIn": {
      "fixedCentavos": 45,
      "bps": 0,
      "fixedReais": 0.45,
      "percent": 0,
      "description": "R$ 0,45 fixo por recebimento"
    },
    "cashOut": {
      "fixedCentavos": 50,
      "bps": 0,
      "fixedReais": 0.5,
      "percent": 0,
      "description": "R$ 0,50 fixo por transferência"
    }
  },
  "authMode": "api_key"
}
```

> Tarifas da sua carteira: O pricing acima ilustra a tabela do guia. Use os valores retornados pela sua conta; as tarifas podem variar. Confira também balance.updatedAt ao exibir um saldo.

## Campos de saldo

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| availableCentavos | integer | Não | Saldo disponível informado pela carteira. |
| pendingCentavos | integer | Não | Valor pendente de liberação. |
| lockedCentavos | integer | Não | Valor bloqueado ou reservado. |
| spendableCentavos | integer | Não | Saldo liberado para uso. A transferência valida a disponibilidade novamente. |
| isActivated | boolean | Não | Indica carteira ativa e com subconta vinculada. |
