Source: https://cryptanio.com/pt/docs/reference/stream-events/
Contract / release / updated: v1 / 1.0.0 62 / 2026-10-10

[Referência da API](https://cryptanio.com/pt/docs.html#reference)

# Transmitir eventos em fluxo

GET `/v1/stream`

Contrato v1 / 1.0.0 62 / 2026-10-10

[Markdown](https://cryptanio.com/pt/docs/reference/stream-events/index.md) [OpenAPI](https://cryptanio.com/openapi.json)

SSE com event:payment, data JSON e comentários heartbeat. Formato diferente de webhook v1. Recupere eventos em falta via /events; repetição Last-Event-ID não implementada. EventSource nativo não define cabeçalhos Bearer: use cliente servidor ou streaming fetch, nunca chave na query.

Permissões da chave: `stream` / read.

## Exemplos de pedidos

Os exemplos executam uma operação real na conta. Defina as variáveis de ambiente indicadas no código. Mantenha a chave privada; pedidos de escrita não são repetidos automaticamente.



### Shell / cURL

```bash
#!/usr/bin/env bash
set -euo pipefail
: "${CRYPTANIO_API_KEY:?Set CRYPTANIO_API_KEY}"
# A live SSE connection is deliberately limited to 30 seconds.
exec 3>&1
transfer_status=0
http_status="$(curl \
  --silent --show-error --no-buffer --max-time 30 --request GET \
  --header "Authorization: Bearer $CRYPTANIO_API_KEY" \
  --header 'Accept: text/event-stream' \
  "https://api.cryptanio.com/v1/stream" \
  --output /dev/fd/3 --write-out '%{http_code}')" || transfer_status=$?
exec 3>&-
if [[ "$http_status" == 2?? ]]; then
  exit "$transfer_status"
fi
printf 'HTTP %s\n' "$http_status" >&2
exit 1
```



[Transferir exemplo](https://cryptanio.com/files/examples/api/stream-events.sh)



### Go

```go
// Go; standard library only. Run: go run request.go
package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "time"
)

func env(name string) string {
    value := os.Getenv(name)
    if value == "" { fmt.Fprintln(os.Stderr, "Set", name); os.Exit(1) }
    return value
}
func run() error {
    path := "/v1/stream"

    endpoint, err := url.Parse("https://api.cryptanio.com" + path)
    if err != nil { return err }
    query := endpoint.Query()

    endpoint.RawQuery = query.Encode()

    request, err := http.NewRequest("GET", endpoint.String(), nil)
    if err != nil { return err }
    request.Header.Set("Authorization", "Bearer " + env("CRYPTANIO_API_KEY"))
    request.Header.Set("Accept", "text/event-stream")
    client := &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
    response, err := client.Do(request)
    if err != nil { return err }
    defer response.Body.Close()
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        body, err := io.ReadAll(response.Body)
        if err != nil { return err }
        return fmt.Errorf("HTTP %d: %s", response.StatusCode, body)
    }
    _, err = io.Copy(os.Stdout, response.Body)
    return err
}
func main() {
    if err := run(); err != nil { fmt.Fprintln(os.Stderr, err); os.Exit(1) }
}
```



[Transferir exemplo](https://cryptanio.com/files/examples/api/stream-events.go)



### Rust

```rust
// Cargo.toml dependencies:
// reqwest = { version = "=0.12.24", features = ["blocking", "json"] }
// serde_json = "=1.0.145"
use std::{error::Error, io, time::Duration};
use reqwest::{blocking::Client, redirect::Policy, Method, Url};

fn env(name: &str) -> Result<String, Box<dyn Error>> {
    let value = std::env::var(name)?;
    if value.is_empty() { return Err(format!("Set {name}").into()); }
    Ok(value)
}
fn run() -> Result<(), Box<dyn Error>> {
    let mut url = Url::parse("https://api.cryptanio.com")?;
    {
        let mut segments = url.path_segments_mut().map_err(|_| "Invalid base URL")?;
        segments.clear();
        segments.push("v1");
        segments.push("stream");
    }
    let client = Client::builder().timeout(Duration::from_secs(30)).redirect(Policy::none()).build()?;
    let request = client.request(Method::GET, url)
        .header("Authorization", format!("Bearer {}", env("CRYPTANIO_API_KEY")?))
        .header("Accept", "text/event-stream".to_owned());
    let mut response = request.send()?;
    let status = response.status();
    if !status.is_success() { return Err(format!("HTTP {}: {}", status.as_u16(), response.text()?).into()); }
    io::copy(&mut response, &mut io::stdout())?;
    Ok(())
}
fn main() {
    if let Err(error) = run() { eprintln!("{error}"); std::process::exit(1); }
}
```



[Transferir exemplo](https://cryptanio.com/files/examples/api/stream-events.rs)



### PHP

```php
<?php
// PHP 8 with the cURL extension. Run this on your server.
function env(string $name): string {
    $value = getenv($name);
    if ($value === false || $value === '') throw new RuntimeException('Set ' . $name);
    return $value;
}
try {
    $path = '/v1/stream';

    $query = [

    ];
    $url = 'https://api.cryptanio.com' . $path . ($query ? '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986) : '');
    $headers = [
        'Authorization: ' . 'Bearer ' . env('CRYPTANIO_API_KEY'),
        'Accept: ' . 'text/event-stream',
    ];
    $errorBody = '';
    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => false,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$errorBody): int {
            $status = curl_getinfo($handle, CURLINFO_HTTP_CODE);
            if ($status >= 200 && $status < 300) { fwrite(STDOUT, $chunk); }
            else { $errorBody .= $chunk; }
            return strlen($chunk);
        },
    ]);
    $response = curl_exec($curl);
    if ($response === false) throw new RuntimeException(curl_error($curl));
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($status < 200 || $status >= 300) throw new RuntimeException('HTTP ' . $status . ': ' . $errorBody);
} catch (Throwable $error) {
    fwrite(STDERR, $error->getMessage() . PHP_EOL);
    exit(1);
}
```



[Transferir exemplo](https://cryptanio.com/files/examples/api/stream-events.php)



### Python

```python
# Python 3; standard library only.
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import HTTPRedirectHandler, Request, build_opener

def env(name):
    result = os.environ.get(name)
    if not result:
        raise ValueError("Set " + name)
    return result

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

try:
    path = "/v1/stream"

    query = {

    }
    url = "https://api.cryptanio.com" + path + ("?" + urlencode(query) if query else "")
    headers = {
        "Authorization": "Bearer " + env("CRYPTANIO_API_KEY"),
        "Accept": "text/event-stream",
    }
    data = None
    request = Request(url, data=data, headers=headers, method="GET")
    with build_opener(NoRedirect()).open(request, timeout=30) as response:
        if not 200 <= response.status < 300:
            raise ValueError("HTTP " + str(response.status))
        for line in response:
            sys.stdout.buffer.write(line)
            sys.stdout.buffer.flush()
except HTTPError as error:
    print("HTTP " + str(error.code) + ": " + error.read().decode("utf-8", errors="replace"), file=sys.stderr)
    sys.exit(1)
except (ValueError, URLError, OSError) as error:
    print(str(error), file=sys.stderr)
    sys.exit(1)
```



[Transferir exemplo](https://cryptanio.com/files/examples/api/stream-events.py)



### Node.js

```javascript
// Node.js 18+. Run on your server, never in a browser.
const env = name => {
  const result = process.env[name];
  if (!result) throw new Error(`Set ${name}`);
  return result;
};
try {
  let path = "/v1/stream";

  const url = new URL(path, "https://api.cryptanio.com");

  const headers = {
    "Authorization": "Bearer " + env("CRYPTANIO_API_KEY"),
    "Accept": "text/event-stream",
  };
  const response = await fetch(url, {
    method: "GET", headers, redirect: "manual",
    signal: AbortSignal.timeout(30_000),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  if (response.body) {
    for await (const chunk of response.body) process.stdout.write(chunk);
  }
} catch (error) {
  console.error(error.message);
  process.exitCode = 1;
}
```



[Transferir exemplo](https://cryptanio.com/files/examples/api/stream-events.mjs)

## Respostas e erros

### 200 Fluxo Server-Sent Events.

text/event-stream

### 401 Nenhuma chave API ativa válida (unauthorized).

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `error` | `object` | Sim |  |



### 401 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 403 Chave não permite operação, projeto, serviço ou IP; email não confirmado.

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `error` | `object` | Sim |  |



### 403 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 429 Demasiados pedidos (rate_limited); repita após Retry-After.

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `error` | `object` | Sim |  |



### 429 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 500 Erro interno (internal).

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `error` | `object` | Sim |  |



### 500 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 503 Indisponibilidade temporária (unavailable); repita com espera progressiva.

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `error` | `object` | Sim |  |



### 503 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



[Tratar erros e repetir com segurança](https://cryptanio.com/pt/docs.html#errors)

## Objetos aninhados

### `StreamEvent`

JSON em data SSE; difere de webhook v1. Eventos sem pagamento omitem payment e podem incluir contract.

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `event_id` | `string` | Sim | Identificador opaco; mantenha-o como cadeia.; minLength: `1` |
| `event_type` | `string` | Sim | Tipo de evento; podem ser adicionados novos tipos. |
| `chain` | `string` | Sim | Código da rede. |
| `service` | `string` | Não | Serviço, se conhecido. |
| `watch_id` | `string` | Não | ID de monitorização do projeto, quando associado.; minLength: `1` |
| `occurred_at` | `string` | Sim | Data e hora UTC em RFC 3339.; `date-time` |
| `payment` | `object \| null` | Não | Documento de pagamento, ou null para eventos sem pagamento. GET /events não devolve conteúdos contract/notice. |
| `sandbox` | `boolean` | Não | Evento de teste; omissão significa false. |
| `project_id` | `string` | Não | Identificador opaco; mantenha-o como cadeia.; minLength: `1` |
| `project_name` | `string` | Não | Nome do projeto. |
| `url` | `string` | Não | Ligação ao evento no Account.; `uri` |
| `contract` | `object` | Não |  |
| `mode` | `string` | Não | live ou test.; `live`, `test` |

### `ID`

Identificador opaco. Formato não garantido; não converta em número.

`string` Identificador opaco. Formato não garantido; não converta em número.

### `EventPayment`

Documento de pagamento REST/SSE. Campos dependem do evento e rede; não é o formato normalizado webhook v1.

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `tx_id` | `string` | Não | Identificador da transação. |
| `index` | `integer` | Não | Índice da transferência na transação.; minimum: `0` |
| `height` | `integer` | Não | Altura do bloco, quando conhecida.; minimum: `0` |
| `address` | `string` | Não | Endereço observado. |
| `asset` | `string` | Não | Ativo REST/SSE: identificador de texto, não o objeto de ativo webhook. |
| `amount_raw` | `string` | Não | Montante inteiro nas unidades mínimas como cadeia.; pattern: `^[0-9]+$` |
| `amount` | `string` | Não | Montante decimal exato como cadeia; não use vírgula flutuante.; pattern: `^[0-9]+(?:\.[0-9]+)?$` |
| `decimals` | `integer` | Não | Casas decimais.; minimum: `0` |
| `confirmations` | `integer` | Não | Confirmações.; minimum: `0` |
| `revision` | `integer` | Não | Revisão do estado da transferência.; minimum: `0` |
| `direction` | `string` | Não | Direção em relação ao endereço observado.; `in`, `out` |
| `simulated` | `boolean` | Não | Evento simulado. |
| `late` | `boolean` | Não | Transferência detetada tardiamente. |
| `block_hash` | `string` | Não | Hash do bloco. |
| `match_key` | `string` | Não | Identificador de correspondência, quando usado pela rede. |
| `meta` | `object` | Não |  |
| `invoice` | `object` | Não |  |
| `customer` | `object` | Não |  |
| `product` | `object` | Não |  |
| `payer` | `object` | Não |  |
| `metadata` | `object` | Não |  |

### `RawAmount`

`string`

### `Decimal`

`string`

### `StringMap`

`object`

### `Customer`

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `id` | `string` | Sim | Identificador do cliente no seu sistema.; maxLength: `120` |

### `Product`

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `id` | `string` | Não | Identificador do produto no seu sistema.; maxLength: `120` |
| `name` | `string` | Não | Nome do produto.; maxLength: `200` |
| `quantity` | `integer` | Não | Quantidade.; minimum: `1`; maximum: `1000000` |

### `Payer`

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `comment` | `string` | Sim | Comentário do pagador.; maxLength: `500` |

### `Error`

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `error` | `object` | Sim |  |
