# API ez-rails

> API de rieles de pagos y facturación electrónica ARCA para Argentina.

- **Base URL:** `https://api.ez-rails.huggian.com/rails`
- **Referencia interactiva (Try it):** https://huggian.com/ez-rails/docs/reference
- **Referencia OpenAPI en Markdown:** https://huggian.com/ez-rails/docs/reference.md
- **OpenAPI 3.1 JSON:** https://huggian.com/ez-rails/docs/openapi.json
- **Pedir API key:** https://huggian.com/rails/signup

## Inicio rápido

1. Pedí tu clave en huggian.com/rails/signup. El plan Sandbox es gratis y llega por email.
2. Mandá tu clave en el header X-API-Key en cada request autenticada.
3. Probá los endpoints en vivo desde la referencia interactiva (/ez-rails/docs/reference) con tu clave ezr_test_* o sin clave usando POST /v1/demo/match.

```bash
curl https://api.ez-rails.huggian.com/rails/v1/health
```

```bash
curl "https://api.ez-rails.huggian.com/rails/v1/movements?tenantId=TENANT_UUID" \
  -H "X-API-Key: ezr_live_..."
```

## Autenticación y convenciones

Enviá tu clave en el header X-API-Key en cada llamada /v1 excepto /v1/health, /v1/demo/match y las URLs entrantes de proveedores (/v1/inbound/*).

- Claves ezr_live_* operan sobre datos en vivo; claves ezr_test_* (plan Sandbox) operan solo sobre datos de sandbox. Mezclar ambos entornos responde 403.
- Cada clave lleva scopes (rails:read, rails:write, rails:webhooks) y la lista de tenants autorizados (allowed_tenant_ids); un tenant fuera de esa lista responde 404.
- Header opcional X-Source-App (^[a-z0-9_-]{1,64}$) para etiquetar los registros que creás.
- Los límites de plan aplican por clave (requests por minuto y por mes). Excederlos responde 429 con código rate_limited.
- Para probar matching sin estado sin API key, llamá a POST /v1/demo/match (máximo 16 KiB de body, máximo 20 movimientos y 20 expectativas, 10 requests/minuto por IP) o abrí la referencia interactiva (/ez-rails/docs/reference) y pegá tu clave ezr_test_*.

## Montos

Los montos viajan siempre como strings decimales con exactamente dos decimales ("15000.00"). Nunca envíes números de punto flotante JSON.

## Idempotencia

POST /v1/expectations, POST /v1/virtual-cvus y POST /v1/cbu-ownership-challenges aceptan el header Idempotency-Key (8 a 128 caracteres de A-Z a-z 0-9 . _ ~ + / : -). Reintentar con la misma clave y payload devuelve la primera respuesta. La misma clave con otro payload responde 409 idempotency_key_conflict; un duplicado que llega mientras el primero sigue en curso responde 409 idempotency_key_in_flight (reintentá en breve).

## Webhooks y firmas

Registrá un endpoint HTTPS (puerto 443, dirección pública) con POST /v1/webhooks/endpoints y un secreto.

Eventos: `transfer.received`, `transfer.reconciled`, `invoice.issued`, `cbu.ownership_verified`, `virtual_cvu.transfer_received`, `virtual_cvu.sweep_settled`. Los filtros de eventos aceptan comodines como transfer.*.

| Header | Significado |
|---|---|
| `X-Huggian-Signature` | HMAC-SHA256 en hex de timestamp + "." + raw_body con el secreto del endpoint |
| `X-Huggian-Signature-Secondary` | Igual, con el secreto secundario durante la rotación |
| `X-Huggian-Timestamp` | Segundos Unix usados en la firma |
| `X-Huggian-Delivery-Id` | Estable por entrega; deduplicá por este ID (la entrega es at-least-once) |
| `X-Huggian-Event` | Nombre del evento |

```text
expected = hex(hmac_sha256(secret, timestamp + "." + raw_body))
accept if constant_time_equal(expected, X-Huggian-Signature) and |now - timestamp| <= 300
```

Respondé 2xx rápido. Otras respuestas y timeouts se reintentan con backoff y pasan a dead-letter; podés reenviarlas con POST /v1/webhooks/deliveries/{delivery_id}/replay. Los headers X-BBX-* son duplicados legacy.

## Errores

Cada error es JSON: {"error": "readable message", "code": "stable_code", "not_attempted": true}. Tomá decisiones según code, nunca según error. not_attempted: true indica que el request no tuvo efecto y es seguro reintentarlo.

| Status | Códigos |
|---|---|
| 400 | `idempotency_key_invalid`, `invalid_source_app`, `malformed_webhook`, `invalid_utf8`, `invalid_json` |
| 401 | `unauthorized` (clave faltante o inválida, o firma de proveedor inválida) |
| 403 | `forbidden` (scope faltante o mezcla de clave live/sandbox) |
| 404 | `not_found` (también para recursos de tenants fuera de tu clave) |
| 409 | `idempotency_key_conflict`, `idempotency_key_in_flight` |
| 413 | `payload_too_large` (body supera el límite de la ruta, ej. 16 KiB en /v1/demo/match) |
| 422 | `validation_error`, `demo_limit_exceeded`, `ssrf_blocked`, `unsupported_operation`, `unprocessable_event`, `too_many_movements` (y otros límites de matching) |
| 429 | `rate_limited` |
| 502 | `rail_upstream_error`, `outcome_unknown` |
| 503 | `service_unavailable` |

## Planes y límites

| Plan | Requests / mes | Requests / min | Datos | Scopes |
|---|---|---|---|---|
| Sandbox | 5.000 | 60 | Solo sandbox (ezr_test_*) | rails:read, rails:write, rails:webhooks |
| Starter | 25.000 | 120 | En vivo (ezr_live_*) | rails:read, rails:write, rails:webhooks |
| Growth | 250.000 | 600 | En vivo (ezr_live_*) | rails:read, rails:write, rails:webhooks |

## Endpoints

Referencia detallada con parámetros, esquemas y ejemplos en [https://huggian.com/ez-rails/docs/reference.md](https://huggian.com/ez-rails/docs/reference.md) o interactiva en [https://huggian.com/ez-rails/docs/reference](https://huggian.com/ez-rails/docs/reference).

### Health

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `GET` | `/v1/health` | público | Liveness and database readiness (no API key, never rate limited). |

### Demo

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `POST` | `/v1/demo/match` | público | Public stateless matching demo (no API key). |

### Accounts

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `GET` | `/v1/accounts` | `rails:read` | List the tenant rail accounts (credentials are never returned; account numbers are masked). |
| `POST` | `/v1/accounts` | `rails:write` | Create or update a rail account (Mercado Pago, banks, PSPs). Secrets are encrypted at rest and never echoed. |
| `POST` | `/v1/accounts/{account_id}/verify-connection` | `rails:write` | Probe the provider credentials of an account. |
| `POST` | `/v1/accounts/{account_id}/auto-listen` | `rails:write` | Enable or disable automatic polling of incoming transfers. |
| `POST` | `/v1/accounts/{account_id}/sync-now` | `rails:write` | Poll the provider for new movements immediately. |
| `POST` | `/v1/accounts/{account_id}/import-statement` | `rails:write` | Import a bank statement (CSV/text) for a statement_cbu account. Body limit 4 MiB. |

### CBU / CVU

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `POST` | `/v1/cbu-cvu/inspect` | `rails:read` | Validate a CBU/CVU/alias and identify its bank or PSP (no network call to the bank). |
| `GET` | `/v1/cbu-ownership-challenges` | `rails:read` | List CBU ownership challenges. |
| `POST` | `/v1/cbu-ownership-challenges` | `rails:write` | Start a micro-deposit ownership challenge for a CBU. |
| `GET` | `/v1/cbu-ownership-challenges/{challenge_id}` | `rails:read` | Read one ownership challenge. |

### Virtual CVUs

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `GET` | `/v1/virtual-cvus` | `rails:read` | List virtual CVUs. |
| `POST` | `/v1/virtual-cvus` | `rails:write` | Provision a virtual CVU for collecting transfers. |
| `GET` | `/v1/virtual-cvus/sweeps` | `rails:read` | List sweep payouts from virtual CVUs. |
| `GET` | `/v1/virtual-cvus/{cvu_id}/payment-instructions` | `rails:read` | Payment instructions to show a payer. |

### Expectations

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `GET` | `/v1/expectations` | `rails:read` | List payment expectations. |
| `POST` | `/v1/expectations` | `rails:write` | Declare an expected payment so an incoming transfer reconciles against it (optionally auto-invoicing). |

### Movements

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `GET` | `/v1/movements` | `rails:read` | List received or sent rail movements. |

### Reconciliations

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `GET` | `/v1/reconciliations` | `rails:read` | List reconciliations (movement to expectation matches). |
| `POST` | `/v1/reconciliations/match` | `rails:write` | Stateless matching: send movements and expectations, get the match report; nothing is stored. |
| `GET` | `/v1/pilot/accountant-overview` | `rails:read` | Accountant summary of movements and reconciliations. |

### Webhooks

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `GET` | `/v1/webhooks/endpoints` | `rails:read` | List your webhook endpoints (secrets are never returned). |
| `POST` | `/v1/webhooks/endpoints` | `rails:webhooks` | Register an HTTPS webhook endpoint. Only https on port 443 to public addresses is accepted. |
| `GET` | `/v1/webhooks/deliveries` | `rails:read` | List webhook deliveries and their attempts. |
| `POST` | `/v1/webhooks/deliveries/{delivery_id}/replay` | `rails:webhooks` | Replay a failed or dead-lettered delivery. |

### Mercado Pago OAuth

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `POST` | `/v1/oauth/mercadopago/authorize-url` | `rails:write` | Build the Mercado Pago authorization URL for an account. |
| `POST` | `/v1/oauth/mercadopago/exchange` | `rails:write` | Exchange the OAuth code returned by Mercado Pago. |

### Sandbox

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `POST` | `/v1/sandbox/simulate-transfer` | `rails:write` | Sandbox keys only: simulate an incoming transfer and run reconciliation inline. |

### Inbound provider webhooks

| Método | Ruta | Scope | Resumen |
|---|---|---|---|
| `POST` | `/v1/inbound/{rail}/{account_id}` | público | Provider-to-EZ Rails notification URL for an account (configure it in the provider dashboard). Authenticated by the provider signature, not by an API key. |
| `POST` | `/v1/inbound/mercadopago-app` | público | Mercado Pago application-level notification URL (x-signature verified). |
