Guía para los equipos de tecnología de las empresas clientes que quieran alimentar el registro de habeas data de IntempoLeads desde sus propios sistemas (CRM, core de seguros, formularios web, procesos ETL), sin subir archivos a mano.
Con la API usted puede:
- registrar personas (titulares) con la evidencia de su autorización de tratamiento de datos;
- registrar revocaciones de esa autorización;
- consultar el resultado de cada envío, registro por registro;
- consultar a una persona y su estado de consentimiento.
Lo que se envía por la API queda en el mismo registro y con las mismas reglas que la carga de archivos CSV/XLSX del portal (Habeas data → Subir CSV/XLSX). Cada envío aparece en Habeas data → Cargas con el origen «API» y el token que lo hizo.
Los nombres de campos, rutas y códigos de error están en inglés; esta guía y los mensajes del portal están en español. El contrato formal es la especificación OpenAPI, que puede importar en Postman, Insomnia o su generador de clientes.
1. Inicio rápido
URL base: https://intempotracker.com/integration/v1
Paso 1. Cree un token. Un usuario con rol Administrador entra al portal, abre Integraciones y crea un token. Póngale un nombre que identifique el sistema que lo usará (p. ej. «CRM producción») y elija sus permisos y su vigencia. El token (nxl_…) se muestra una sola vez: cópielo al gestor de secretos del sistema que lo usará.
Paso 2. Pruebe la conexión.
export INTEGRATION_API_URL=https://intempotracker.com/integration/v1
export INTEGRATION_API_TOKEN=nxl_... # el token del paso 1
curl "$INTEGRATION_API_URL/ping" -H "Authorization: Bearer $INTEGRATION_API_TOKEN"{ "tenant": { "name": "Andina Seguros" },
"token": { "id": "0192…", "name": "CRM producción", "scopes": ["habeas_data:write", "habeas_data:read"] } }Paso 3. Envíe su primer lote.
curl "$INTEGRATION_API_URL/authorizations" \
-H "Authorization: Bearer $INTEGRATION_API_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: primer-lote-001" \
-d '{
"externalReference": "prueba-inicial",
"records": [
{
"documentType": "CC",
"documentNumber": "1020304050",
"authorization": { "authorizedOn": "2026-09-01", "channel": "Formulario web", "policyVersion": "v3" }
}
]
}'La respuesta (201 Created) trae el resumen del lote y el resultado de cada registro. El lote ya aparece en el portal, en Habeas data → Cargas.
2. Tokens y seguridad
- Quién los crea: solo los usuarios con rol Administrador de la empresa, en Integraciones.
- De quién son: de la empresa, no de la persona que los creó. Si esa persona sale de la compañía, el token sigue funcionando. El portal lo marca como «Creador deshabilitado»; revóquelo y cree otro si ya no está bajo control de la empresa.
- Formato:
nxl_seguido de 43 caracteres. El prefijonxl_permite que las herramientas de detección de secretos lo reconozcan si se filtra en un repositorio. - Almacenamiento: IntempoLeads guarda solo una huella (SHA-256) del token, nunca el token. Por eso no se puede volver a mostrar ni recuperar: si se pierde, cree otro.
- Vigencia: 30, 90 o 180 días, o 1 año. No hay tokens sin vencimiento. Cree el reemplazo antes del vencimiento, despliéguelo y revoque el anterior.
- Revocación: inmediata, desde el portal. Las solicitudes con un token revocado reciben
401. Si IntempoLeads suspende la cuenta de la empresa, sus tokens se revocan y no vuelven a funcionar aunque la cuenta se reactive. - Máximo: 20 tokens activos por empresa.
Permisos (scopes). Asigne a cada token solo lo que necesita:
| Scope | Permite |
|---|---|
habeas_data:write | Enviar lotes de autorizaciones y revocaciones, y consultar los lotes enviados. |
habeas_data:read | Consultar personas (/data-subjects/lookup) y los lotes enviados. |
Un token que solo envía datos no necesita habeas_data:read: así, si se filtra, no sirve para leer datos personales.
Buenas prácticas
- Use el token solo desde servidores, nunca desde una aplicación móvil ni desde un navegador.
- Guárdelo en un gestor de secretos (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault, variables protegidas del CI). No lo guarde en el código ni en archivos
.envversionados. - Use un token distinto por sistema o por entorno, para poder revocar uno sin afectar a los demás.
- No escriba el token ni los datos personales de las respuestas en sus logs.
- Use siempre HTTPS en producción.
3. Conceptos: lotes, resultados e idempotencia
Lotes
Cada POST envía un lote de 1 a 1.000 registros. IntempoLeads lo procesa de forma síncrona: la respuesta llega cuando el lote ya quedó aplicado.
- Un lote se aplica completo o no se aplica. Si algo falla en el servidor, no queda nada a medias.
- Dentro del lote, cada registro se valida por separado. Un registro inválido se rechaza con sus motivos y los demás se cargan.
externalReferencees opcional: una referencia libre (el id de su proceso, la fecha de la sincronización) que aparece en el portal para reconocer el lote.
Resultado por registro
La respuesta trae un elemento en records por cada registro enviado, en el mismo orden. index es la posición del registro en su arreglo, desde 0.
status | Significado |
|---|---|
created | Persona nueva, registrada con su autorización. |
updated | La persona ya existía. Se corrigieron datos (changed), se agregó una autorización (authorizationAdded), se agregaron placas (platesAdded) o se registró una revocación (revocationRecorded). |
unchanged | Ya estaba así; no se cambió nada. En revocaciones, alreadyRevoked: true. |
duplicate | La persona ya venía en un registro anterior del mismo lote (duplicateOfIndex). Cuenta el primer registro válido. |
rejected | No se cargó. issues dice qué campo falló y por qué. |
El lote termina en completed si no hubo rechazos o en completed_with_errors si hubo al menos uno. Un rechazo no es un error HTTP: la respuesta es 201 y usted debe revisar records.
Idempotencia
Las redes fallan: una solicitud puede llegar al servidor y perderse la respuesta. Para que reintentar sea siempre seguro, todo POST de lotes exige la cabecera Idempotency-Key:
- Clave nueva: se procesa el lote y se responde
201. - Misma clave y mismo cuerpo: no se procesa de nuevo. Se responde
200, con la cabeceraIdempotent-Replayed: truey el mismo resultado original. - Misma clave con otro cuerpo, o en otra operación:
422 idempotency_key_reused.fields.batchIdindica el lote original. - Dos solicitudes simultáneas con la misma clave producen un solo lote.
Cómo elegir la clave:
- Debe ser única por lote y estable entre reintentos de ese lote. Tiene de 1 a 255 caracteres ASCII visibles (sin espacios).
- Recomendado: derivarla del contenido, p. ej.
personas-+ los primeros 32 caracteres del SHA-256 del cuerpo JSON. Así, volver a ejecutar el mismo proceso sobre los mismos datos nunca carga dos veces. Todos los ejemplos de la sección 8 lo hacen así. - Otra opción: un identificador estable de su proceso, como
sync-2026-09-23-lote-3. - Las claves son por empresa y no vencen.
Dos cuerpos con los mismos datos pero distinto formato JSON (espacios, saltos de línea) se consideran el mismo. El orden de los registros y de las propiedades sí cuenta: al reintentar, envíe exactamente el mismo cuerpo.
Reglas del registro
Son las mismas que la carga de archivos:
- Identidad: una persona se identifica por
documentType+documentNumberdentro de su empresa. El número se normaliza sin puntos, espacios ni guiones, así que52.784.292y52784292son la misma persona. El nombre es opcional: si no lo envía, IntempoLeads lo toma del RUNT cuando su proveedor lo informa. - Correcciones: si la persona ya existe,
fullName,emailyphonereemplazan los datos guardados. Un campo vacío o ausente nunca borra un dato. - Autorizaciones: una autorización con la misma fecha, canal y versión de política que otra ya registrada para la persona es la misma, sin distinguir mayúsculas ni tildes, y no se duplica. Si cambia cualquiera de los tres, se agrega una nueva. El historial de autorizaciones nunca se edita ni se borra.
- Placas: las placas enviadas se agregan a las que ya tiene la persona; un envío sin placas no borra ninguna. IntempoLeads las vigila en el RUNT para detectar matrículas, traspasos y prendas que no aparecen en el registro de la persona, como un carro nuevo comprado en concesionario.
- Revocaciones: la persona queda con consentimiento revocado si su última revocación es igual o posterior a su última autorización. Una autorización con fecha posterior, enviada por archivo o por API, lo restablece.
- Estado: IntempoLeads registra la evidencia que usted envía;
consentStatuses el estado del registro, no una conclusión legal sobre la validez de la autorización.
4. Operaciones
Todas las rutas son relativas a la URL base y exigen Authorization: Bearer <token>, salvo openapi.json.
| Método | Ruta | Scope | Para qué |
|---|---|---|---|
GET | /ping | cualquiera | Verificar el token. |
POST | /authorizations | habeas_data:write | Lote de personas con su autorización. |
POST | /revocations | habeas_data:write | Lote de revocaciones. |
GET | /batches | write o read | Lotes enviados por API (paginado; filtro type). |
GET | /batches/{id} | write o read | Resumen de un lote. |
GET | /batches/{id}/records | write o read | Resultado por registro (paginado; filtro status). |
POST | /data-subjects/lookup | habeas_data:read | Consultar a una persona por documento. |
GET | /openapi.json | ninguno | Especificación OpenAPI 3.1. |
POST /authorizations
{
"externalReference": "crm-sync-2026-09-23T10:00",
"records": [
{
"documentType": "CC",
"documentNumber": "1020304050",
"fullName": "Laura Martínez Prueba",
"email": "[email protected]",
"phone": "+573001234567",
"plates": ["ABC123"],
"authorization": {
"authorizedOn": "2026-09-01",
"channel": "Formulario web",
"policyVersion": "v3",
"evidenceReference": "FORM-2026-000123"
}
}
]
}Respuesta 201 (fragmento):
{
"id": "0192…",
"type": "authorizations",
"status": "completed_with_errors",
"externalReference": "crm-sync-2026-09-23T10:00",
"idempotencyKey": "personas-3f9a…",
"counts": { "received": 3, "created": 1, "updated": 1, "unchanged": 0, "duplicate": 0, "rejected": 1 },
"records": [
{ "index": 0, "status": "created", "subjectId": "0192…" },
{ "index": 1, "status": "updated", "subjectId": "0192…", "changed": ["email"], "authorizationAdded": true },
{ "index": 2, "status": "rejected", "subjectId": null,
"issues": [ { "field": "documentNumber", "code": "invalid" },
{ "field": "authorization.authorizedOn", "code": "future_date" } ] }
]
}POST /revocations
{
"externalReference": "revocaciones-2026-09-23",
"records": [
{
"documentType": "CC",
"documentNumber": "1020304050",
"revokedOn": "2026-09-20",
"channel": "Correo electrónico",
"notes": "Solicitud recibida en servicio al cliente",
"evidenceReference": "PQR-2026-0042"
}
]
}Resultados específicos de las revocaciones:
| Resultado | Cuándo |
|---|---|
updated + revocationRecorded: true | Se registró la revocación. |
unchanged + alreadyRevoked: true | Ya estaba revocada; no se registra otra. |
rejected, documentNumber / not_found | La persona no está en el registro de su empresa. |
rejected, revokedOn / before_authorization | La fecha es anterior a la última autorización, que sigue vigente. |
Consultar lotes
# Lotes recientes
curl "$INTEGRATION_API_URL/batches?page=1&pageSize=20" -H "Authorization: Bearer $INTEGRATION_API_TOKEN"
# Solo los registros rechazados de un lote, para corregirlos
curl "$INTEGRATION_API_URL/batches/$BATCH_ID/records?status=rejected&pageSize=1000" \
-H "Authorization: Bearer $INTEGRATION_API_TOKEN"Las listas paginadas responden { "items": [...], "total": 42, "page": 1, "pageSize": 20 }. Solo aparecen los lotes enviados por API, no los archivos subidos en el portal.
POST /data-subjects/lookup
Es POST para que el número de documento no viaje en la URL, donde podría quedar registrado en logs de proxies.
curl "$INTEGRATION_API_URL/data-subjects/lookup" \
-H "Authorization: Bearer $INTEGRATION_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "documentType": "CC", "documentNumber": "1.020.304.050" }'{
"id": "0192…",
"documentType": "cc",
"documentNumber": "1020304050",
"fullName": "Laura Martínez Prueba",
"email": "[email protected]",
"phone": "+573001234567",
"consentStatus": "registered",
"latestAuthorization": { "authorizedOn": "2026-09-01", "channel": "Formulario web", "policyVersion": "v3", "evidenceReference": "FORM-2026-000123" },
"latestRevocation": null,
"authorizationCount": 1,
"createdAt": "…",
"updatedAt": "…"
}Si la persona no está en el registro de su empresa, la respuesta es 404.
Cada consulta exitosa queda registrada en el historial de auditoría de su empresa, con el token que la hizo. Los usuarios de cumplimiento la ven en el portal, en la hoja de vida de la persona (Consultas). Consulte solo cuando lo necesite.
5. Campos y validaciones
Autorizaciones
| Campo | Obligatorio | Regla |
|---|---|---|
documentType | Sí | CC, CE, TI, PA (también PASAPORTE o PASSPORT), PEP, PPT o NIT (empresas). No distingue mayúsculas ni tildes; también acepta «Cédula». Las respuestas usan cc, ce, ti, passport, pep, ppt, nit. |
documentNumber | Sí | Siempre como texto, para conservar los ceros a la izquierda. Se ignoran puntos, espacios y guiones. CC: 3–10 dígitos; TI: 6–11 dígitos; CE: 3–15 letras o números; pasaporte, PEP y PPT: 5–20. |
fullName | No | 2 a 160 caracteres. Los espacios repetidos se reducen a uno. Si no se envía, IntempoLeads toma el nombre del RUNT cuando su proveedor lo informa. |
email | No | Correo válido, hasta 254 caracteres. Se guarda en minúsculas. |
phone | No | 7 a 15 dígitos, con + opcional. Se ignoran espacios, puntos, guiones y paréntesis. |
plates | No | Arreglo de hasta 5 placas de vehículos de la persona: carro ABC123, moto ABC12D o moto antigua ABC12. Se ignoran guiones y mayúsculas. |
authorization.authorizedOn | Sí | Fecha AAAA-MM-DD. No puede ser posterior a hoy en Colombia. |
authorization.channel | Sí | 2 a 100 caracteres: cómo se obtuvo la autorización (p. ej. «Formulario web», «Firma física»). |
authorization.policyVersion | No | Hasta 40 caracteres. |
authorization.evidenceReference | No | Hasta 255 caracteres: dónde está el soporte en sus sistemas. |
Revocaciones
| Campo | Obligatorio | Regla |
|---|---|---|
documentType, documentNumber | Sí | Igual que arriba. La persona debe existir en su registro. |
revokedOn | Sí | Fecha AAAA-MM-DD, no futura y no anterior a la última autorización. |
channel | Sí | 2 a 100 caracteres. |
notes | No | Hasta 500 caracteres. |
evidenceReference | No | Hasta 255 caracteres. |
Códigos de issues
code | Significado |
|---|---|
required | Falta el campo o está vacío. |
invalid | Formato inválido, o un valor de otro tipo (p. ej. un número donde se espera texto). |
too_long | Supera la longitud máxima. |
future_date | Fecha posterior a hoy. |
not_found | Revocaciones: la persona no está en el registro. |
before_authorization | Revocaciones: fecha anterior a la última autorización. |
field es la ruta del campo en su JSON, p. ej. documentNumber o authorization.authorizedOn. Si el elemento de records no es un objeto, field es record.
Por privacidad, IntempoLeads no guarda los valores rechazados, solo el campo y el motivo.
6. Errores y reintentos
Los errores HTTP tienen siempre esta forma:
{ "error": { "code": "idempotency_key_reused", "message": "…", "fields": { "batchId": "0192…" } } }Programe contra code, que es estable. message es técnico, en inglés, y puede cambiar.
| HTTP | code | ¿Reintentar? | Qué hacer |
|---|---|---|---|
| 400 | bad_request, validation_failed, too_many_records, idempotency_key_required, invalid_idempotency_key | No | Corrija la solicitud. validation_failed detalla en fields los problemas de estructura, como records vacío o que no es un arreglo. |
| 401 | invalid_token | No | Token ausente, mal escrito, vencido o revocado, o cuenta suspendida. Verifique el token o cree uno nuevo. |
| 403 | insufficient_scope | No | El token no tiene el scope que exige la operación. |
| 403 | agreement_required | Sí, después de aceptarlo | Su empresa debe aceptar la versión vigente del acuerdo de tratamiento de datos. Un administrador la firma al iniciar sesión en el portal. |
| 404 | not_found | No | El lote o la persona no existe en su empresa. |
| 409 | batch_conflict | Sí | Otro lote modificaba las mismas personas al mismo tiempo. No se cargó nada. Reintente con la misma Idempotency-Key. |
| 413 | payload_too_large | No | El cuerpo supera 1 MB. Divida el lote. |
| 422 | idempotency_key_reused | No | Use una clave nueva para un lote distinto. |
| 429 | rate_limited | Sí | Espere los segundos que indique Retry-After. |
| 5xx | internal_error | Sí | Reintente con la misma clave. Si persiste, contacte a soporte con el requestId del error. |
| — | error de red o timeout | Sí | Reintente con la misma clave: la idempotencia evita cargar dos veces. |
Política de reintentos recomendada. Reintente solo en los casos marcados, con espera exponencial: 1 s, 2 s, 4 s, 8 s, hasta 5 intentos. Si hay Retry-After, respete ese valor. Use siempre la misma Idempotency-Key y exactamente el mismo cuerpo. Configure un timeout de al menos 60 s por solicitud: un lote de 1.000 registros suele tardar menos de 1 s, pero no hay garantía.
7. Límites
| Límite | Valor |
|---|---|
| Registros por lote | 1.000 |
| Tamaño del cuerpo | 1 MB |
| Solicitudes por minuto, por token | 120 (configurable por IntempoLeads); ventana fija por minuto calendario |
| Tokens activos por empresa | 20 |
Longitud de Idempotency-Key | 1 a 255 caracteres ASCII visibles |
Todas las respuestas autenticadas incluyen RateLimit-Limit, RateLimit-Remaining y RateLimit-Reset, este último en segundos. Para cargas grandes, envíe los lotes uno tras otro y no en paralelo: 100.000 personas son 100 lotes, que enviados en serie no se acercan al límite.
8. Ejemplos por lenguaje
Programas completos, listos para copiar o descargar, que hacen lo mismo en cada lenguaje:
- Leen
INTEGRATION_API_URLyINTEGRATION_API_TOKEN. - Verifican el token con
/ping. - Leen un CSV de personas (
people.csv, con datos sintéticos). - Lo dividen en lotes de 1.000.
- Envían cada lote con una
Idempotency-Keyderivada del contenido. - Reintentan según la política de la sección 6.
- Muestran los registros rechazados con su línea del CSV.
Ninguno necesita librerías externas. Al ejecutarlo dos veces sobre el mismo archivo, la segunda vez la respuesta es 200 y Idempotent-Replayed: true: no se carga nada de nuevo.
export INTEGRATION_API_URL=https://intempotracker.com/integration/v1
export INTEGRATION_API_TOKEN=nxl_...
python3 send_batch.py /ruta/a/cartera.csv # sin argumento usa ../people.csvRequiere curl y un shell POSIX. Ejecútelo con sh send-batch.sh
#!/bin/sh
# Envía un lote a la API de integración con curl.
#
# Uso:
# export INTEGRATION_API_TOKEN=nxl_...
# export INTEGRATION_API_URL=http://localhost:4100/integration/v1 # opcional
# sh send-batch.sh # authorizations-batch.json → POST /authorizations
# sh send-batch.sh revocations # revocations-batch.json → POST /revocations
#
# La Idempotency-Key se deriva del contenido del archivo: reenviar el mismo
# archivo devuelve el resultado original (HTTP 200) sin cargar nada de nuevo.
set -eu
API_URL="${INTEGRATION_API_URL:-http://localhost:4100/integration/v1}"
: "${INTEGRATION_API_TOKEN:?Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).}"
DIR=$(cd "$(dirname "$0")" && pwd)
if [ "${1:-}" = "revocations" ] || [ "${1:-}" = "revocaciones" ]; then
FILE="$DIR/revocations-batch.json"; ENDPOINT=revocations
else
FILE="$DIR/authorizations-batch.json"; ENDPOINT=authorizations
fi
# sha256 del archivo (Linux: sha256sum; macOS: shasum -a 256).
if command -v sha256sum >/dev/null 2>&1; then
HASH=$(sha256sum "$FILE" | cut -c1-64)
else
HASH=$(shasum -a 256 "$FILE" | cut -c1-64)
fi
echo "== Verificando el token (GET /ping)"
curl -sS "$API_URL/ping" -H "Authorization: Bearer $INTEGRATION_API_TOKEN"
echo
echo "== Enviando $(basename "$FILE") a POST /$ENDPOINT"
# -w imprime el código HTTP al final: 201 = lote nuevo, 200 = reintento (misma clave y cuerpo).
curl -sS "$API_URL/$ENDPOINT" \
-H "Authorization: Bearer $INTEGRATION_API_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: lote-$HASH" \
--data-binary "@$FILE" \
-w '\nHTTP %{http_code}\n'
Requiere Python 3.9 o superior. Ejecútelo con python3 send_batch.py
"""Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.
Uso (Python 3.9+, solo biblioteca estándar):
export INTEGRATION_API_TOKEN=nxl_...
export INTEGRATION_API_URL=http://localhost:4100/integration/v1 # opcional
python send_batch.py [ruta/al/archivo.csv] # por defecto ../people.csv
La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
script con el mismo archivo devuelve el resultado original (HTTP 200) sin
cargar nada de nuevo.
"""
import csv
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
API_URL = os.environ.get("INTEGRATION_API_URL", "http://localhost:4100/integration/v1").rstrip("/")
TOKEN = os.environ.get("INTEGRATION_API_TOKEN")
BATCH_SIZE = 1000
MAX_ATTEMPTS = 5
def request(method, path, body=None, headers=None):
"""Envía una solicitud y devuelve (status, cabeceras, JSON). Reintenta lo reintentable."""
for attempt in range(1, MAX_ATTEMPTS + 1):
req = urllib.request.Request(f"{API_URL}{path}", data=body, method=method)
req.add_header("Authorization", f"Bearer {TOKEN}")
if body is not None:
req.add_header("Content-Type", "application/json")
for name, value in (headers or {}).items():
req.add_header(name, value)
try:
with urllib.request.urlopen(req, timeout=60) as res:
return res.status, res.headers, json.load(res)
except urllib.error.HTTPError as err:
status, payload = err.code, json.loads(err.read() or b"{}")
retryable = status in (409, 429) or status >= 500
if not retryable or attempt == MAX_ATTEMPTS:
error = payload.get("error", {})
sys.exit(f"Error {status} {error.get('code')}: {error.get('message')}")
wait = int(err.headers.get("Retry-After", 0)) or 2 ** (attempt - 1)
except urllib.error.URLError as err:
if attempt == MAX_ATTEMPTS:
sys.exit(f"No se pudo conectar con la API: {err.reason}")
wait = 2 ** (attempt - 1)
print(f" Reintento {attempt}/{MAX_ATTEMPTS - 1} en {wait} s…")
time.sleep(wait)
def to_record(row):
"""Una fila del CSV → un registro de la API; los opcionales vacíos se omiten."""
record = {"documentType": row["documentType"], "documentNumber": row["documentNumber"], "fullName": row["fullName"]}
for field in ("email", "phone"):
if row.get(field):
record[field] = row[field]
authorization = {"authorizedOn": row["authorizedOn"], "channel": row["channel"]}
for field in ("policyVersion", "evidenceReference"):
if row.get(field):
authorization[field] = row[field]
record["authorization"] = authorization
return record
def main():
if not TOKEN:
sys.exit("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).")
csv_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent.parent / "people.csv"
_, _, ping = request("GET", "/ping")
print(f"Conectado a {ping['tenant']['name']} · permisos: {', '.join(ping['token']['scopes'])}")
with open(csv_path, newline="", encoding="utf-8") as f:
records = [to_record(row) for row in csv.DictReader(f)]
for start in range(0, len(records), BATCH_SIZE):
body = json.dumps(
{"externalReference": csv_path.name, "records": records[start : start + BATCH_SIZE]},
ensure_ascii=False,
separators=(",", ":"),
).encode("utf-8")
key = "personas-" + hashlib.sha256(body).hexdigest()[:32]
status, headers, batch = request("POST", "/authorizations", body, {"Idempotency-Key": key})
replayed = headers.get("Idempotent-Replayed") == "true"
print(f"\nLote {batch['id']} · HTTP {status}{' (reintento: resultado original)' if replayed else ''}")
print(" " + " · ".join(f"{name}: {count}" for name, count in batch["counts"].items()))
for result in batch["records"]:
if result["status"] == "rejected":
line = start + result["index"] + 2 # la línea 1 es el encabezado
issues = ", ".join(f"{i['field']} ({i['code']})" for i in result["issues"])
print(f" Rechazado · línea {line} del CSV: {issues}")
if __name__ == "__main__":
main()
Requiere Node.js 20 o superior. Ejecútelo con node send-batch.mjs
// Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.
//
// Uso (Node.js 20+, sin dependencias):
// export INTEGRATION_API_TOKEN=nxl_...
// export INTEGRATION_API_URL=http://localhost:4100/integration/v1 # opcional
// node send-batch.mjs [ruta/al/archivo.csv] # por defecto ../people.csv
//
// La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
// script con el mismo archivo devuelve el resultado original (HTTP 200).
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const API_URL = (process.env.INTEGRATION_API_URL ?? "http://localhost:4100/integration/v1").replace(/\/$/, "");
const TOKEN = process.env.INTEGRATION_API_TOKEN;
const BATCH_SIZE = 1000;
const MAX_ATTEMPTS = 5;
const sleep = (s) => new Promise((resolve) => setTimeout(resolve, s * 1000));
// Envía una solicitud; reintenta errores de red, 409, 429 y 5xx.
async function request(method, path, body, headers = {}) {
for (let attempt = 1; ; attempt++) {
let wait = 2 ** (attempt - 1);
try {
const res = await fetch(`${API_URL}${path}`, {
method,
body,
headers: { authorization: `Bearer ${TOKEN}`, ...(body && { "content-type": "application/json" }), ...headers },
signal: AbortSignal.timeout(60_000),
});
const payload = await res.json();
if (res.ok) return { res, payload };
const retryable = res.status === 409 || res.status === 429 || res.status >= 500;
if (!retryable || attempt === MAX_ATTEMPTS) {
console.error(`Error ${res.status} ${payload.error?.code}: ${payload.error?.message}`);
process.exit(1);
}
wait = Number(res.headers.get("retry-after")) || wait;
} catch (err) {
if (attempt === MAX_ATTEMPTS) {
console.error(`No se pudo conectar con la API: ${err.message}`);
process.exit(1);
}
}
console.log(` Reintento ${attempt}/${MAX_ATTEMPTS - 1} en ${wait} s…`);
await sleep(wait);
}
}
// CSV sencillo (sin comas dentro de los campos). En producción use una
// biblioteca como csv-parse.
function readCsv(path) {
const [header, ...lines] = readFileSync(path, "utf8").trim().split(/\r?\n/);
const columns = header.split(",");
return lines.map((line) => Object.fromEntries(line.split(",").map((value, i) => [columns[i], value.trim()])));
}
// Una fila del CSV → un registro de la API; los opcionales vacíos se omiten.
const toRecord = (row) => ({
documentType: row.documentType,
documentNumber: row.documentNumber,
fullName: row.fullName,
...(row.email && { email: row.email }),
...(row.phone && { phone: row.phone }),
authorization: {
authorizedOn: row.authorizedOn,
channel: row.channel,
...(row.policyVersion && { policyVersion: row.policyVersion }),
...(row.evidenceReference && { evidenceReference: row.evidenceReference }),
},
});
if (!TOKEN) {
console.error("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).");
process.exit(1);
}
const csvPath = process.argv[2] ?? join(dirname(fileURLToPath(import.meta.url)), "..", "people.csv");
const { payload: ping } = await request("GET", "/ping");
console.log(`Conectado a ${ping.tenant.name} · permisos: ${ping.token.scopes.join(", ")}`);
const records = readCsv(csvPath).map(toRecord);
for (let start = 0; start < records.length; start += BATCH_SIZE) {
const body = JSON.stringify({ externalReference: basename(csvPath), records: records.slice(start, start + BATCH_SIZE) });
const key = `personas-${createHash("sha256").update(body).digest("hex").slice(0, 32)}`;
const { res, payload: batch } = await request("POST", "/authorizations", body, { "idempotency-key": key });
const replayed = res.headers.get("idempotent-replayed") === "true";
console.log(`\nLote ${batch.id} · HTTP ${res.status}${replayed ? " (reintento: resultado original)" : ""}`);
console.log(" " + Object.entries(batch.counts).map(([name, n]) => `${name}: ${n}`).join(" · "));
for (const r of batch.records.filter((r) => r.status === "rejected")) {
const issues = r.issues.map((i) => `${i.field} (${i.code})`).join(", ");
console.log(` Rechazado · línea ${start + r.index + 2} del CSV: ${issues}`); // la línea 1 es el encabezado
}
}
Requiere .NET 10 SDK. Ejecútelo con dotnet run send-batch.cs
// Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.
//
// Uso (.NET 10+, aplicación de un solo archivo, sin paquetes):
// export INTEGRATION_API_TOKEN=nxl_...
// export INTEGRATION_API_URL=http://localhost:4100/integration/v1 # opcional
// dotnet run send-batch.cs [ruta/al/archivo.csv] # por defecto ../people.csv
//
// La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
// programa con el mismo archivo devuelve el resultado original (HTTP 200).
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
const int BatchSize = 1000;
const int MaxAttempts = 5;
var apiUrl = (Environment.GetEnvironmentVariable("INTEGRATION_API_URL") ?? "http://localhost:4100/integration/v1").TrimEnd('/');
var token = Environment.GetEnvironmentVariable("INTEGRATION_API_TOKEN");
if (string.IsNullOrEmpty(token)) Fail("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).");
var csvPath = args.Length > 0 ? args[0] : Path.Combine("..", "people.csv");
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var (_, ping) = await Send(HttpMethod.Get, "/ping", null, null);
var scopes = string.Join(", ", ping["token"]!["scopes"]!.AsArray().Select(s => s!.GetValue<string>()));
Console.WriteLine($"Conectado a {ping["tenant"]!["name"]} · permisos: {scopes}");
// CSV sencillo (sin comas dentro de los campos). En producción use una
// biblioteca como CsvHelper.
var lines = File.ReadAllLines(csvPath).Where(l => l.Trim() != "").ToArray();
var columns = lines[0].Split(',');
var records = lines.Skip(1).Select(line =>
{
var values = line.Split(',').Select(v => v.Trim()).ToArray();
string Get(string name) => values[Array.IndexOf(columns, name)];
var authorization = new JsonObject { ["authorizedOn"] = Get("authorizedOn"), ["channel"] = Get("channel") };
if (Get("policyVersion") != "") authorization["policyVersion"] = Get("policyVersion");
if (Get("evidenceReference") != "") authorization["evidenceReference"] = Get("evidenceReference");
var record = new JsonObject { ["documentType"] = Get("documentType"), ["documentNumber"] = Get("documentNumber"), ["fullName"] = Get("fullName") };
if (Get("email") != "") record["email"] = Get("email");
if (Get("phone") != "") record["phone"] = Get("phone");
record["authorization"] = authorization;
return record;
}).ToList();
var jsonOptions = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
for (var start = 0; start < records.Count; start += BatchSize)
{
var chunk = new JsonArray(records.Skip(start).Take(BatchSize).Select(r => (JsonNode)r.DeepClone()).ToArray());
var body = new JsonObject { ["externalReference"] = Path.GetFileName(csvPath), ["records"] = chunk }.ToJsonString(jsonOptions);
var key = "personas-" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(body)))[..32];
var (res, batch) = await Send(HttpMethod.Post, "/authorizations", body, key);
var replayed = res.Headers.TryGetValues("Idempotent-Replayed", out var v) && v.First() == "true" ? " (reintento: resultado original)" : "";
Console.WriteLine($"\nLote {batch["id"]} · HTTP {(int)res.StatusCode}{replayed}");
Console.WriteLine(" " + string.Join(" · ", batch["counts"]!.AsObject().Select(c => $"{c.Key}: {c.Value}")));
foreach (var r in batch["records"]!.AsArray().Where(r => (string)r!["status"]! == "rejected"))
{
var issues = string.Join(", ", r!["issues"]!.AsArray().Select(i => $"{i!["field"]} ({i["code"]})"));
var line = start + (int)r["index"]! + 2; // la línea 1 es el encabezado
Console.WriteLine($" Rechazado · línea {line} del CSV: {issues}");
}
}
// Envía la solicitud; reintenta errores de red, 409, 429 y 5xx con el mismo cuerpo.
async Task<(HttpResponseMessage, JsonNode)> Send(HttpMethod method, string path, string? body, string? idempotencyKey)
{
for (var attempt = 1; ; attempt++)
{
var wait = TimeSpan.FromSeconds(Math.Pow(2, attempt - 1));
var request = new HttpRequestMessage(method, apiUrl + path);
if (body != null) request.Content = new StringContent(body, Encoding.UTF8, "application/json");
if (idempotencyKey != null) request.Headers.Add("Idempotency-Key", idempotencyKey);
try
{
var res = await http.SendAsync(request);
var payload = JsonNode.Parse(await res.Content.ReadAsStringAsync())!;
if (res.IsSuccessStatusCode) return (res, payload);
var status = (int)res.StatusCode;
var retryable = status == 409 || status == 429 || status >= 500;
if (!retryable || attempt == MaxAttempts) Fail($"Error {status} {payload["error"]?["code"]}: {payload["error"]?["message"]}");
wait = res.Headers.RetryAfter?.Delta ?? wait;
}
catch (HttpRequestException e) when (attempt < MaxAttempts)
{
Console.WriteLine($" Error de red: {e.Message}");
}
catch (HttpRequestException e)
{
Fail($"No se pudo conectar con la API: {e.Message}");
}
Console.WriteLine($" Reintento {attempt}/{MaxAttempts - 1} en {wait.TotalSeconds} s…");
await Task.Delay(wait);
}
}
static void Fail(string message)
{
Console.Error.WriteLine(message);
Environment.Exit(1);
}
Requiere Java 21 o superior. Ejecútelo con java SendBatch.java
// Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.
//
// Uso (Java 21+, un solo archivo, sin dependencias):
// export INTEGRATION_API_TOKEN=nxl_...
// export INTEGRATION_API_URL=http://localhost:4100/integration/v1 # opcional
// java SendBatch.java [ruta/al/archivo.csv] # por defecto ../people.csv
//
// La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
// programa con el mismo archivo devuelve el resultado original (HTTP 200).
//
// Java no trae un parser JSON: aquí el cuerpo se arma a mano y la respuesta se
// imprime tal cual. En producción use Jackson o Gson para ambas cosas.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.regex.Pattern;
public class SendBatch {
static final int BATCH_SIZE = 1000;
static final int MAX_ATTEMPTS = 5;
static final String API_URL = System.getenv().getOrDefault("INTEGRATION_API_URL", "http://localhost:4100/integration/v1").replaceAll("/$", "");
static final String TOKEN = System.getenv("INTEGRATION_API_TOKEN");
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
public static void main(String[] args) throws Exception {
if (TOKEN == null || TOKEN.isEmpty()) fail("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).");
Path csv = Path.of(args.length > 0 ? args[0] : "../people.csv");
System.out.println("Ping: " + send("GET", "/ping", null, null).body());
// CSV sencillo (sin comas dentro de los campos). En producción use
// una biblioteca como Apache Commons CSV.
List<String> lines = Files.readAllLines(csv, StandardCharsets.UTF_8).stream().filter(l -> !l.isBlank()).toList();
List<String> columns = List.of(lines.get(0).split(","));
List<String> records = new ArrayList<>();
for (String line : lines.subList(1, lines.size())) {
String[] values = line.split(",", -1);
java.util.function.Function<String, String> get = name -> values[columns.indexOf(name)].trim();
String authorization = "{" + field("authorizedOn", get.apply("authorizedOn")) + "," + field("channel", get.apply("channel"))
+ optional("policyVersion", get.apply("policyVersion")) + optional("evidenceReference", get.apply("evidenceReference")) + "}";
records.add("{" + field("documentType", get.apply("documentType")) + "," + field("documentNumber", get.apply("documentNumber"))
+ "," + field("fullName", get.apply("fullName")) + optional("email", get.apply("email")) + optional("phone", get.apply("phone"))
+ ",\"authorization\":" + authorization + "}");
}
for (int start = 0; start < records.size(); start += BATCH_SIZE) {
List<String> chunk = records.subList(start, Math.min(start + BATCH_SIZE, records.size()));
String body = "{" + field("externalReference", csv.getFileName().toString()) + ",\"records\":[" + String.join(",", chunk) + "]}";
byte[] hash = MessageDigest.getInstance("SHA-256").digest(body.getBytes(StandardCharsets.UTF_8));
String key = "personas-" + HexFormat.of().formatHex(hash).substring(0, 32);
HttpResponse<String> res = send("POST", "/authorizations", body, key);
boolean replayed = res.headers().firstValue("Idempotent-Replayed").orElse("").equals("true");
System.out.println("\nHTTP " + res.statusCode() + (replayed ? " (reintento: resultado original)" : ""));
var counts = Pattern.compile("\"counts\":\\{[^}]*\\}").matcher(res.body());
if (counts.find()) System.out.println(" " + counts.group());
// El índice de cada registro rechazado + 2 es su línea en el CSV (la 1 es el encabezado).
var rejected = Pattern.compile("\\{\"index\":(\\d+),\"status\":\"rejected\",\"subjectId\":null,\"issues\":(\\[[^\\]]*\\])").matcher(res.body());
while (rejected.find()) {
int line = start + Integer.parseInt(rejected.group(1)) + 2;
System.out.println(" Rechazado · línea " + line + " del CSV: " + rejected.group(2));
}
}
}
// Envía la solicitud; reintenta errores de red, 409, 429 y 5xx con el mismo cuerpo.
static HttpResponse<String> send(String method, String path, String body, String idempotencyKey) throws InterruptedException {
for (int attempt = 1; ; attempt++) {
long wait = 1L << (attempt - 1);
var request = HttpRequest.newBuilder(URI.create(API_URL + path)).timeout(Duration.ofSeconds(60))
.header("Authorization", "Bearer " + TOKEN)
.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8));
if (body != null) request.header("Content-Type", "application/json").header("Idempotency-Key", idempotencyKey);
try {
HttpResponse<String> res = HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
int status = res.statusCode();
if (status < 300) return res;
boolean retryable = status == 409 || status == 429 || status >= 500;
if (!retryable || attempt == MAX_ATTEMPTS) fail("Error " + status + ": " + res.body());
wait = res.headers().firstValue("Retry-After").map(Long::parseLong).orElse(wait);
} catch (java.io.IOException e) {
if (attempt == MAX_ATTEMPTS) fail("No se pudo conectar con la API: " + e.getMessage());
}
System.out.println(" Reintento " + attempt + "/" + (MAX_ATTEMPTS - 1) + " en " + wait + " s…");
Thread.sleep(wait * 1000);
}
}
static String field(String name, String value) {
return "\"" + name + "\":\"" + escape(value) + "\"";
}
// Los campos opcionales vacíos se omiten.
static String optional(String name, String value) {
return value.isEmpty() ? "" : "," + field(name, value);
}
static String escape(String s) {
StringBuilder out = new StringBuilder();
for (char c : s.toCharArray()) {
switch (c) {
case '"' -> out.append("\\\"");
case '\\' -> out.append("\\\\");
case '\n' -> out.append("\\n");
case '\r' -> out.append("\\r");
case '\t' -> out.append("\\t");
default -> out.append(c < 0x20 ? String.format("\\u%04x", (int) c) : String.valueOf(c));
}
}
return out.toString();
}
static void fail(String message) {
System.err.println(message);
System.exit(1);
}
}
Requiere PHP 8.2 o superior. Ejecútelo con php send-batch.php
<?php
// Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.
//
// Uso (PHP 8.2+, sin extensiones adicionales):
// export INTEGRATION_API_TOKEN=nxl_...
// export INTEGRATION_API_URL=http://localhost:4100/integration/v1 # opcional
// php send-batch.php [ruta/al/archivo.csv] # por defecto ../people.csv
//
// La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
// script con el mismo archivo devuelve el resultado original (HTTP 200).
const BATCH_SIZE = 1000;
const MAX_ATTEMPTS = 5;
$apiUrl = rtrim(getenv('INTEGRATION_API_URL') ?: 'http://localhost:4100/integration/v1', '/');
$token = getenv('INTEGRATION_API_TOKEN') ?: fail('Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).');
$csvPath = $argv[1] ?? __DIR__ . '/../people.csv';
function fail(string $message): never
{
fwrite(STDERR, $message . PHP_EOL);
exit(1);
}
// Envía una solicitud y devuelve [status, cabeceras, cuerpo decodificado].
// Reintenta errores de red, 409, 429 y 5xx, siempre con el mismo cuerpo.
function request(string $method, string $path, ?string $body = null, array $headers = []): array
{
global $apiUrl, $token;
$headers[] = "Authorization: Bearer $token";
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
}
for ($attempt = 1; ; $attempt++) {
$wait = 2 ** ($attempt - 1);
$context = stream_context_create(['http' => [
'method' => $method, 'header' => $headers, 'content' => $body ?? '',
'ignore_errors' => true, 'timeout' => 60,
]]);
$raw = @file_get_contents($apiUrl . $path, false, $context);
if ($raw === false) {
if ($attempt === MAX_ATTEMPTS) fail('No se pudo conectar con la API.');
} else {
// $http_response_header lo llena file_get_contents.
$status = (int) explode(' ', $http_response_header[0])[1];
$responseHeaders = [];
foreach (array_slice($http_response_header, 1) as $line) {
[$name, $value] = array_map('trim', explode(':', $line, 2)) + [1 => ''];
$responseHeaders[strtolower($name)] = $value;
}
$payload = json_decode($raw, true);
if ($status < 300) return [$status, $responseHeaders, $payload];
$retryable = $status === 409 || $status === 429 || $status >= 500;
if (!$retryable || $attempt === MAX_ATTEMPTS) {
fail("Error $status {$payload['error']['code']}: {$payload['error']['message']}");
}
$wait = (int) ($responseHeaders['retry-after'] ?? 0) ?: $wait;
}
echo " Reintento $attempt/" . (MAX_ATTEMPTS - 1) . " en $wait s…\n";
sleep($wait);
}
}
// Una fila del CSV → un registro de la API; los opcionales vacíos se omiten.
function toRecord(array $row): array
{
$authorization = array_filter([
'authorizedOn' => $row['authorizedOn'], 'channel' => $row['channel'],
'policyVersion' => $row['policyVersion'], 'evidenceReference' => $row['evidenceReference'],
], fn ($v) => $v !== '');
return array_filter([
'documentType' => $row['documentType'], 'documentNumber' => (string) $row['documentNumber'],
'fullName' => $row['fullName'], 'email' => $row['email'], 'phone' => $row['phone'],
], fn ($v) => $v !== '') + ['authorization' => $authorization];
}
[, , $ping] = request('GET', '/ping');
echo "Conectado a {$ping['tenant']['name']} · permisos: " . implode(', ', $ping['token']['scopes']) . "\n";
$file = fopen($csvPath, 'r') ?: fail("No se pudo abrir $csvPath");
$columns = fgetcsv($file, escape: '');
$records = [];
while (($row = fgetcsv($file, escape: '')) !== false) {
if ($row === [null]) continue; // línea vacía
$records[] = toRecord(array_combine($columns, array_map('trim', $row)));
}
foreach (array_chunk($records, BATCH_SIZE) as $n => $chunk) {
$body = json_encode(['externalReference' => basename($csvPath), 'records' => $chunk], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
$key = 'personas-' . substr(hash('sha256', $body), 0, 32);
[$status, $headers, $batch] = request('POST', '/authorizations', $body, ["Idempotency-Key: $key"]);
$replayed = ($headers['idempotent-replayed'] ?? '') === 'true' ? ' (reintento: resultado original)' : '';
echo "\nLote {$batch['id']} · HTTP $status$replayed\n ";
echo implode(' · ', array_map(fn ($k, $v) => "$k: $v", array_keys($batch['counts']), $batch['counts'])) . "\n";
foreach ($batch['records'] as $r) {
if ($r['status'] !== 'rejected') continue;
$issues = implode(', ', array_map(fn ($i) => "{$i['field']} ({$i['code']})", $r['issues']));
$line = $n * BATCH_SIZE + $r['index'] + 2; // la línea 1 es el encabezado
echo " Rechazado · línea $line del CSV: $issues\n";
}
}
Requiere Go 1.22 o superior. Ejecútelo con go run main.go
// Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.
//
// Uso (Go 1.21+, solo biblioteca estándar):
//
// export INTEGRATION_API_TOKEN=nxl_...
// export INTEGRATION_API_URL=http://localhost:4100/integration/v1 # opcional
// go run main.go [ruta/al/archivo.csv] # por defecto ../people.csv
//
// La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
// programa con el mismo archivo devuelve el resultado original (HTTP 200).
package main
import (
"bytes"
"crypto/sha256"
"encoding/csv"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const batchSize = 1000
const maxAttempts = 5
var (
apiURL = strings.TrimRight(envOr("INTEGRATION_API_URL", "http://localhost:4100/integration/v1"), "/")
token = os.Getenv("INTEGRATION_API_TOKEN")
client = &http.Client{Timeout: 60 * time.Second}
)
type authorization struct {
AuthorizedOn string `json:"authorizedOn"`
Channel string `json:"channel"`
PolicyVersion string `json:"policyVersion,omitempty"`
EvidenceReference string `json:"evidenceReference,omitempty"`
}
type record struct {
DocumentType string `json:"documentType"`
DocumentNumber string `json:"documentNumber"`
FullName string `json:"fullName"`
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
Authorization authorization `json:"authorization"`
}
type batchResult struct {
ID string `json:"id"`
Counts map[string]int `json:"counts"`
Records []struct {
Index int `json:"index"`
Status string `json:"status"`
Issues []struct{ Field, Code string }
} `json:"records"`
}
func main() {
if token == "" {
fail("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).")
}
csvPath := filepath.Join("..", "people.csv")
if len(os.Args) > 1 {
csvPath = os.Args[1]
}
var ping struct {
Tenant struct{ Name string }
Token struct{ Scopes []string }
}
request("GET", "/ping", nil, "", &ping)
fmt.Printf("Conectado a %s · permisos: %s\n", ping.Tenant.Name, strings.Join(ping.Token.Scopes, ", "))
records := readRecords(csvPath)
for start := 0; start < len(records); start += batchSize {
end := min(start+batchSize, len(records))
body, _ := json.Marshal(map[string]any{"externalReference": filepath.Base(csvPath), "records": records[start:end]})
sum := sha256.Sum256(body)
key := "personas-" + hex.EncodeToString(sum[:])[:32]
var batch batchResult
res := request("POST", "/authorizations", body, key, &batch)
replayed := ""
if res.Header.Get("Idempotent-Replayed") == "true" {
replayed = " (reintento: resultado original)"
}
fmt.Printf("\nLote %s · HTTP %d%s\n", batch.ID, res.StatusCode, replayed)
fmt.Printf(" received: %d · created: %d · updated: %d · unchanged: %d · duplicate: %d · rejected: %d\n",
batch.Counts["received"], batch.Counts["created"], batch.Counts["updated"],
batch.Counts["unchanged"], batch.Counts["duplicate"], batch.Counts["rejected"])
for _, r := range batch.Records {
if r.Status != "rejected" {
continue
}
issues := make([]string, len(r.Issues))
for i, issue := range r.Issues {
issues[i] = fmt.Sprintf("%s (%s)", issue.Field, issue.Code)
}
// La línea 1 del CSV es el encabezado.
fmt.Printf(" Rechazado · línea %d del CSV: %s\n", start+r.Index+2, strings.Join(issues, ", "))
}
}
}
// request envía la solicitud y decodifica la respuesta en out. Reintenta
// errores de red, 409, 429 y 5xx, siempre con el mismo cuerpo.
func request(method, path string, body []byte, idempotencyKey string, out any) *http.Response {
for attempt := 1; ; attempt++ {
wait := time.Duration(1<<(attempt-1)) * time.Second
req, _ := http.NewRequest(method, apiURL+path, bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
if body != nil {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", idempotencyKey)
}
res, err := client.Do(req)
if err == nil {
data, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode < 300 {
if err := json.Unmarshal(data, out); err != nil {
fail("Respuesta inesperada: " + err.Error())
}
return res
}
retryable := res.StatusCode == 409 || res.StatusCode == 429 || res.StatusCode >= 500
if !retryable || attempt == maxAttempts {
var e struct{ Error struct{ Code, Message string } }
json.Unmarshal(data, &e)
fail(fmt.Sprintf("Error %d %s: %s", res.StatusCode, e.Error.Code, e.Error.Message))
}
if s, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && s > 0 {
wait = time.Duration(s) * time.Second
}
} else if attempt == maxAttempts {
fail("No se pudo conectar con la API: " + err.Error())
}
fmt.Printf(" Reintento %d/%d en %s…\n", attempt, maxAttempts-1, wait)
time.Sleep(wait)
}
}
// readRecords convierte cada fila del CSV en un registro de la API.
func readRecords(path string) []record {
f, err := os.Open(path)
if err != nil {
fail("No se pudo abrir el CSV: " + err.Error())
}
defer f.Close()
rows, err := csv.NewReader(f).ReadAll()
if err != nil {
fail("CSV inválido: " + err.Error())
}
col := map[string]int{}
for i, name := range rows[0] {
col[name] = i
}
records := make([]record, 0, len(rows)-1)
for _, row := range rows[1:] {
get := func(name string) string { return strings.TrimSpace(row[col[name]]) }
records = append(records, record{
DocumentType: get("documentType"), DocumentNumber: get("documentNumber"), FullName: get("fullName"),
Email: get("email"), Phone: get("phone"),
Authorization: authorization{
AuthorizedOn: get("authorizedOn"), Channel: get("channel"),
PolicyVersion: get("policyVersion"), EvidenceReference: get("evidenceReference"),
},
})
}
return records
}
func envOr(name, fallback string) string {
if v := os.Getenv(name); v != "" {
return v
}
return fallback
}
func fail(message string) {
fmt.Fprintln(os.Stderr, message)
os.Exit(1)
}
9. Lista de verificación para producción
- Un token por sistema y por entorno, solo con los scopes necesarios.
- El token está en un gestor de secretos, no en el código ni en logs.
- Hay un recordatorio para rotar el token antes de su vencimiento.
- Cada lote lleva una
Idempotency-Keyestable entre reintentos, idealmente derivada del contenido. - Los reintentos siguen la sección 6 y usan la misma clave y el mismo cuerpo.
- Su proceso revisa
recordsy trata losrejected, porque un201puede traer rechazos. - Los números de documento se envían como texto.
- Las fechas van en formato
AAAA-MM-DD. - Sus logs no guardan las respuestas completas, que contienen identificadores de personas, ni el token.
- Solo se usa HTTPS.