# Autenticação — Delta Wallet

Autentique seu servidor com a chave da carteira e mantenha os segredos protegidos.

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

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

## Chave de API

Envie X-Wallet-Key em cada chamada. Também é aceito Authorization: Bearer para chaves de desenvolvedor com prefixo delta_wk_. Use um único modo de autenticação por requisição.

### 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'
```

Headers de uma consulta

```http
GET /api/v1/wallet/balance HTTP/1.1
Host: api.deltaapplications.com.br
X-Wallet-Key: <DELTA_WALLET_KEY>
Accept: application/json
```

## Sessão do painel (cookie e JWT)

O painel Delta usa o cookie de sessão token ou o JWT de login em Authorization: Bearer. Esse modo é destinado à conta autenticada. Não solicite a senha ou o token de sessão do cliente para uma integração de terceiros.

- A sessão permite gerar a primeira chave sem já possuir uma chave de API.
- Quando X-Wallet-Key está presente, a autenticação por chave tem prioridade.
- Uma chave revogada não deve ser substituída automaticamente por outra conta.

## Armazenamento da chave

- Use variáveis de ambiente ou um gerenciador de segredos no backend.
- Nunca use NEXT_PUBLIC_ para armazenar a chave.
- Não inclua a chave em URLs, prints, logs ou mensagens de erro.
- Em caso de exposição, revogue ou rotacione pelo painel e atualize seus serviços.

> Credenciais de bots gerenciados: Os bots hospedados pela Delta recebem credenciais pelo provisionamento. Não rotacione essas credenciais como tentativa de corrigir indisponibilidade da API.
