Introducción
Wallet es una API de infraestructura financiera multi-cliente: cuentas, créditos, débitos, transferencias y un ledger de doble entrada con idempotencia de extremo a extremo.
Está pensada para integrarse desde cualquier sistema —ecommerce, tienda online, SaaS, ERP, app móvil o plataforma de servicios— sin acoplarse a ningún producto concreto. Solo necesitas PostgreSQL, Node.js y un juego de credenciales por cliente.
- Montos como strings decimales exactos (nunca float).
- Ledger de doble entrada: todo movimiento POSTED está balanceado.
- Protección contra doble gasto mediante
Idempotency-Key. - Autenticación por API Key + HMAC-SHA256 con tolerancia de ±300 s.
- Aislamiento total entre clientes: cada uno solo ve sus cuentas.
Base de ejemplo: https://wallet.example.com — sustitúyela por el dominio de tu instalación.
Arquitectura
SISTEMA DEL CLIENTE
│ X-Api-Key + X-Wallet-Timestamp + X-Wallet-Signature (HMAC-SHA256)
▼
WALLET API (Next.js · rutas /v1/*)
│ validación de firma, idempotencia y reglas de saldo
▼
LEDGER (asientos CREDIT/DEBIT balanceados)
│
▼
POSTGRESQL (DECIMAL(36,18) · sin FLOAT/DOUBLE)- API: rutas HTTP con autenticación por firma.
- Ledger: núcleo contable atómico (transacción SQL serializable).
- PostgreSQL: fuente única de verdad.
- Admin: panel web protegido por sesión (salud, clientes, cuentas, movimientos).
- Docs: esta guía en
/docsy especificación en/openapi.yaml.
Instalación
Requisitos: Node.js 20+ y PostgreSQL 14+.
# 1) Desempaquetar y entrar
tar -xzf programmit-wallet-standalone-v1.0.0.tar.gz
cd programmit-wallet-standalone-v1.0.0
# 2) Configurar entorno (sin secretos reales en el repo)
cp .env.example .env
$EDITOR .env
# 3) Instalar (valida requisitos, genera secretos, aplica esquema, build)
sudo ./deploy/standalone/install.sh
# 4) Arrancar
sudo systemctl enable --now wallet.service
curl -s http://127.0.0.1:3104/healthTambién existe opción Docker en deploy/standalone/docker-compose.yml. La guía completa está en deploy/standalone/README.md y el arranque exprés en docs/standalone/QUICKSTART.md.
Autenticación
Toda ruta /v1/* exige tres cabeceras además del cuerpo JSON. /health es pública.
| Cabecera | Descripción | Ejemplo |
|---|---|---|
| X-Api-Key | Clave del cliente en claro (se almacena como sha256). | wlt_REPLACE_WITH_YOUR_API_KEY |
| X-Wallet-Timestamp | Segundos Unix. Tolerancia ±300 s. | 1767225600 |
| X-Wallet-Signature | Firma HMAC-SHA256 con prefijo v1=. | v1=8f2f0c1c… |
| Idempotency-Key | Obligatoria en créditos, débitos y transferencias. | uuid-v4 |
Las credenciales se entregan una única vez al crear o regenerar un cliente desde Panel Admin. El secreto HMAC nunca se vuelve a mostrar ni se guarda en texto plano.
Cómo generar la firma HMAC
Mensaje firmado:
# Con cuerpo JSON:
X-Wallet-Signature = "v1=" + hex( HMAC_SHA256(secret, `${timestamp}.${rawBody}`) )
# Sin cuerpo (GET):
X-Wallet-Signature = "v1=" + hex( HMAC_SHA256(secret, `${timestamp}.${METHOD} ${path}`) )rawBody que firmas debe ser byte a byte el mismo que envías. Si serializas el JSON por tu cuenta, envía ese mismo string (no re-serializes con otro orden de claves).# Payload firmado: ${timestamp}.${rawBody}
# ó ${timestamp}."${METHOD} ${path}" (peticiones sin cuerpo)
TS=$(date +%s)
BODY='{"account_id":"ACCOUNT_ID","amount":"125.50"}'
SIG=$(printf '%s' "${TS}.${BODY}" \
| openssl dgst -sha256 -hmac "$HMAC_SECRET" -hex | sed 's/^.* //')
curl -sS -X POST "https://wallet.example.com/v1/credits" \
-H "content-type: application/json" \
-H "x-api-key: $API_KEY" \
-H "x-wallet-timestamp: $TS" \
-H "x-wallet-signature: v1=$SIG" \
-H "idempotency-key: $(uuidgen)" \
-d "$BODY"Idempotencia
Créditos, débitos y transferencias requieren la cabecera Idempotency-Key. Reglas:
- Primera vez → se aplica el movimiento y responde
201. - Reenvío con la misma clave y el mismo cuerpo →
200conidempotent_replay: true: no se duplica saldo. - Reenvío con la misma clave y otro cuerpo →
409 IDEMPOTENCY_KEY_CONFLICT. - Clave ausente →
400 MISSING_IDEMPOTENCY_KEY.
La clave es única por cliente. Usa un UUID v4 por evento de negocio (pedido, factura, recarga) y reutilízalo en los reintentos.
Cuentas
Una cuenta identifica el saldo de un propietario dentro de un cliente y una moneda. La combinación (owner_ref, account_type, currency) es única.
owner_ref: 1–64 caracteres, no puede empezar por@(reservado al sistema).account_type: por defectoAVAILABLE.EXTERNALestá reservado.currency: ISO-4217 de 3 letras (o tokens soportados: USDT, USDC, BUSD).- Llamar de nuevo con los mismos valores devuelve la cuenta existente (
200en lugar de201).
curl -sS -X POST "https://wallet.example.com/v1/accounts" \
-H "content-type: application/json" \
-H "x-api-key: $API_KEY" \
-H "x-wallet-timestamp: $TS" \
-H "x-wallet-signature: v1=$SIG" \
-d '{"owner_ref":"user:1001","currency":"USD"}'
# 201 →
# {
# "id": "2f0c...", "client_id": "c1a2...",
# "owner_ref": "user:1001", "account_type": "AVAILABLE",
# "currency": "USD", "available": "0.00", "held": "0.00",
# "created_at": "2026-01-01T12:00:00.000Z", "updated_at": "..."
# }Créditos
Acredita saldo en una cuenta propia. El ledger registra DEBIT en la cuenta puente @external y CREDIT en la cuenta destino.
TS=$(date +%s)
BODY='{"account_id":"ACCOUNT_ID","amount":"125.50","external_reference":"order-1001"}'
SIG=$(printf '%s' "${TS}.${BODY}" \
| openssl dgst -sha256 -hmac "$HMAC_SECRET" -hex | sed 's/^.* //')
curl -sS -X POST "https://wallet.example.com/v1/credits" \
-H "content-type: application/json" \
-H "x-api-key: $API_KEY" \
-H "x-wallet-timestamp: $TS" \
-H "x-wallet-signature: v1=$SIG" \
-H "idempotency-key: 8b6f0a1e-2f5c-4a3d-9d9a-4d9a1b2c3d4e" \
-d "$BODY"
# 201 →
# {
# "transaction_id": "...", "type": "CREDIT", "status": "POSTED",
# "currency": "USD", "idempotent_replay": false,
# "entries": [
# { "account_id": "@external", "direction": "DEBIT", "amount": "125.50" },
# { "account_id": "ACCOUNT_ID", "direction": "CREDIT", "amount": "125.50" }
# ],
# "balance": { "account_id": "ACCOUNT_ID", "currency": "USD",
# "available": "125.50", "held": "0.00" }
# }Débitos
Descuenta saldo. Si no hay fondos suficientes responde 402 y no se modifica nada.
TS=$(date +%s)
BODY='{"account_id":"ACCOUNT_ID","amount":"10.00"}'
SIG=$(printf '%s' "${TS}.${BODY}" \
| openssl dgst -sha256 -hmac "$HMAC_SECRET" -hex | sed 's/^.* //')
curl -sS -X POST "https://wallet.example.com/v1/debits" \
-H "content-type: application/json" \
-H "x-api-key: $API_KEY" \
-H "x-wallet-timestamp: $TS" \
-H "x-wallet-signature: v1=$SIG" \
-H "idempotency-key: 3f2a9c77-1d4e-4b8a-8f21-0a1b2c3d4e5f" \
-d "$BODY"
# Si no hay saldo suficiente:
# 402 {"error":"Insufficient balance.","code":"INSUFFICIENT_BALANCE"}owner_ref con prefijo system:) pueden quedar con saldo negativo: representan clearing o tesorería. Las cuentas de usuario (user:…) jamás.Transferencias
Mueve saldo entre dos cuentas propias del mismo cliente. Deben compartir moneda y ser distintas; si no, 400 CURRENCY_MISMATCH o 400 SAME_ACCOUNT.
TS=$(date +%s)
BODY='{"from_account_id":"FROM_ID","to_account_id":"TO_ID","amount":"25.00"}'
SIG=$(printf '%s' "${TS}.${BODY}" \
| openssl dgst -sha256 -hmac "$HMAC_SECRET" -hex | sed 's/^.* //')
curl -sS -X POST "https://wallet.example.com/v1/transfers" \
-H "content-type: application/json" \
-H "x-api-key: $API_KEY" \
-H "x-wallet-timestamp: $TS" \
-H "x-wallet-signature: v1=$SIG" \
-H "idempotency-key: 5c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f" \
-d "$BODY"
# 201 → transaction + from_balance + to_balanceConsulta de saldo
Los montos se devuelven siempre como string con dos decimales como mínimo (nunca notación flotante): "1125.50", "-590.47".
# GET sin cuerpo: se firma "${timestamp}.GET /v1/accounts/ACCOUNT_ID/balance"
TS=$(date +%s)
SIG=$(printf '%s' "${TS}.GET /v1/accounts/ACCOUNT_ID/balance" \
| openssl dgst -sha256 -hmac "$HMAC_SECRET" -hex | sed 's/^.* //')
curl -sS "https://wallet.example.com/v1/accounts/ACCOUNT_ID/balance" \
-H "x-api-key: $API_KEY" \
-H "x-wallet-timestamp: $TS" \
-H "x-wallet-signature: v1=$SIG"
# {"account_id":"ACCOUNT_ID","currency":"USD","available":"1125.50","held":"0.00"}Transacciones
Cada movimiento tiene un transaction_id y sus asientos de ledger. Permite auditar de dónde vino y a dónde fue cada importe.
TS=$(date +%s)
SIG=$(printf '%s' "${TS}.GET /v1/transactions/TX_ID" \
| openssl dgst -sha256 -hmac "$HMAC_SECRET" -hex | sed 's/^.* //')
curl -sS "https://wallet.example.com/v1/transactions/TX_ID" \
-H "x-api-key: $API_KEY" \
-H "x-wallet-timestamp: $TS" \
-H "x-wallet-signature: v1=$SIG"{
"transaction_id": "…",
"type": "TRANSFER",
"status": "POSTED",
"currency": "USD",
"external_reference": "order-1001",
"metadata": { "note": "payout semanal" },
"entries": [
{ "account_id": "…from…", "direction": "DEBIT", "amount": "25.00" },
{ "account_id": "…to…", "direction": "CREDIT", "amount": "25.00" }
],
"created_at": "2026-01-01T12:00:00.000Z",
"posted_at": "2026-01-01T12:00:00.010Z",
"idempotent_replay": false
}Errores HTTP
Todo error responde { "error": string, "code": string }.
| HTTP | Códigos | Cuándo |
|---|---|---|
| 400 | INVALID_AMOUNT / INVALID_JSON / INVALID_CURRENCY / INVALID_OWNER_REF / MISSING_IDEMPOTENCY_KEY | Cuerpo o parámetros inválidos. |
| 401 | MISSING_API_KEY / STALE_TIMESTAMP / MISSING_SIGNATURE / INVALID_SIGNATURE | Firma ausente, caducada (>300 s) o incorrecta. |
| 402 | INSUFFICIENT_BALANCE | Saldo insuficiente: no se aplica nada. |
| 403 | UNKNOWN_API_KEY / RESERVED_ACCOUNT_TYPE | API key desconocida, cliente inactivo o tipo reservado. |
| 404 | ACCOUNT_NOT_FOUND / TRANSACTION_NOT_FOUND | Recurso inexistente o de otro cliente. |
| 409 | IDEMPOTENCY_KEY_CONFLICT | Misma Idempotency-Key con otro cuerpo. |
| 500 | INTERNAL_ERROR / UNBALANCED_LEDGER | Error interno (nunca debe ocurrir: el ledger se valida). |
| 503 | DATABASE_UNAVAILABLE | Base de datos no disponible. |
Seguridad
- TLS obligatorio en producción; el panel Admin vive tras sesión firmada, CSRF y límite de intentos de login.
- Los secretos HMAC se guardan sellados con AES-256-GCM y jamás se devuelven por API ni se escriben en logs.
- Ventana de reloj de ±300 s y comparación en tiempo constante de las firmas (replay seguro).
- Nunca expongas
API_KEYniHMAC_SECRETen JavaScript de navegador, apps móviles o repositorios públicos: las llamadas deben salir de tu backend. - El Admin no permite editar saldos manualmente: la única fuente de verdad es la API.
Ejemplos completos
Flujo típico: crear cuenta → acreditar → consultar saldo → debitar → transferir → consultar movimiento. Sustituye ACCOUNT_ID y las credenciales por las tuyas.
cURL
BASE="https://wallet.example.com"
API_KEY="wlt_REPLACE_WITH_YOUR_API_KEY"
HMAC_SECRET="REPLACE_WITH_YOUR_HMAC_SECRET"
firmar() { # $1 = método, $2 = ruta, $3 = cuerpo (opcional)
local ts=$(date +%s) sig
if [ -n "$3" ]; then
sig=$(printf '%s' "${ts}.$3" | openssl dgst -sha256 -hmac "$HMAC_SECRET" -hex | sed 's/^.* //')
else
sig=$(printf '%s' "${ts}.$1 $2" | openssl dgst -sha256 -hmac "$HMAC_SECRET" -hex | sed 's/^.* //')
fi
echo "$ts|$sig"
}
BODY='{"owner_ref":"user:1001","currency":"USD"}'
IFS='|' read -r TS SIG <<< "$(firmar POST /v1/accounts "$BODY")"
curl -sS -X POST "$BASE/v1/accounts" \
-H "content-type: application/json" \
-H "x-api-key: $API_KEY" \
-H "x-wallet-timestamp: $TS" \
-H "x-wallet-signature: v1=$SIG" \
-d "$BODY"JavaScript / Node.js
import { call } from "./wallet-client.js";
// 1) Crear (o recuperar) la cuenta del usuario
const [status, account] = await call("POST", "/v1/accounts", {
owner_ref: "user:1001",
currency: "USD",
});
console.log(status, account.id, account.available); // 201, uuid, "0.00"
// 2) Acreditar (Idempotency-Key obligatoria y reutilizable)
const credit = await call(
"POST",
"/v1/credits",
{ account_id: account.id, amount: "125.50", external_reference: "order-1001" },
{ "idempotency-key": crypto.randomUUID() },
);
console.log(credit.data.balance.available); // "125.50"
// 3) Reenviar la MISMA clave → replay seguro, sin duplicar saldo
// 4) Consultar saldo y movimiento
const balance = await call("GET", `/v1/accounts/${account.id}/balance`);
const tx = await call("GET", `/v1/transactions/${credit.data.transaction_id}`);
console.log(balance.data.available, tx.data.entries);PHP
<?php
require "wallet-client.php";
// 1) Crear cuenta
[$status, $account] = walletCall('POST', '/v1/accounts', [
'owner_ref' => 'user:1001',
'currency' => 'USD',
]);
// 2) Acreditar con Idempotency-Key
$idempotencyKey = bin2hex(random_bytes(16));
[$status, $credit] = walletCall('POST', '/v1/credits', [
'account_id' => $account['id'],
'amount' => '125.50',
'external_reference'=> 'order-1001',
], ['idempotency-key: ' . $idempotencyKey]);
// 3) Saldo
[$status, $balance] = walletCall('GET', '/v1/accounts/' . $account['id'] . '/balance');
// 4) Movimiento
[$status, $tx] = walletCall('GET', '/v1/transactions/' . $credit['transaction_id']);
echo $balance['available']; // 125.50OpenAPI
Especificación completa (schemas, cabeceras, códigos y ejemplos) en formato OpenAPI 3.0:
Puedes importarla en Postman, Insomnia, Redoc, Swagger UI o generadores de clientes (openapi-generator).