event.origin) que se muestran en esta guía son de ejemplo. Genuine Solutions
te confirmará la URL real (producción o pre-producción) y la región (MX o
ES) asignadas a tu cuenta antes de integrar.
Flujo de integración
Paso 1 — Obtener sessionId y urlWeb
Realiza una petición POST al endpoint de sesión enviando tus credenciales.
La respuesta incluye idSesion (token Bearer para APIs) y urlWeb
(URL del WebSDK que se cargará en el iframe).
POST
https://<tu-api-asignada>/api/session
application/json
POST
REQUEST BODY
{
"email": "tu_correo@empresa.com",
"pwd": "tu_contraseña"
}
RESPONSE (200 OK)
{
"idSesion": "eyJhbGciOiJSUzI1NiIs...",
"urlWeb": "https://<tu-dominio-asignado>/websdk?token=abc123..."
}
POSIBLES ERRORES
// 404 — sin licencia o cliente sin productos asignados
{ "error": "LICENSE_NOT_FOUND", "message": "..." }
{ "error": "NO_ASSIGNED_CLIENTS", "message": "..." }
// 403 — sin créditos disponibles
{ "error": "CREDITS_NOT_AVAILABLE", "message": "..." }
error de la respuesta para mostrarle al usuario un mensaje
específico (licencia no encontrada, cliente sin productos asignados, o sin créditos
disponibles) en vez de un error genérico.
EJEMPLO EN JAVASCRIPT
async function getSessionInfo() {
const response = await fetch(
'https://<tu-api-asignada>/api/session',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'tu_correo@empresa.com',
pwd: 'tu_contraseña'
})
}
);
if (!response.ok) throw new Error(`Error: ${response.status}`);
const data = await response.json();
return {
sessionId: data.idSesion,
urlWeb: data.urlWeb
};
}
idSesion se utiliza como token Bearer en las APIs REST
(por ejemplo para procesar imágenes cargadas manualmente). La urlWeb es la URL
que se carga dentro del iframe para la captura en tiempo real con cámara.
Paso 2 — Abrir el WebSDK en un iframe
Crea dinámicamente un <iframe> con la urlWeb recibida.
Es fundamental declarar los permisos de cámara y micrófono en el atributo
allow para que el detector de documentos pueda acceder al hardware del dispositivo.
async function showWebView() {
// Limpiar listener previo para evitar duplicados en capturas sucesivas
if (messageHandler) {
window.removeEventListener('message', messageHandler);
messageHandler = null;
}
const { urlWeb } = await getSessionInfo();
if (!urlWeb) {
alert('No se pudo obtener la URL de la sesión.');
return;
}
// Crear el iframe
const iframe = document.createElement('iframe');
iframe.src = urlWeb;
iframe.allow = 'camera; microphone; accelerometer; gyroscope; magnetometer';
iframe.setAttribute('allowfullscreen', 'true');
iframe.id = 'ocr_frame';
// Posicionar como overlay de pantalla completa
Object.assign(iframe.style, {
position: 'fixed',
inset: '0',
width: '100%',
height: '100%',
border: 'none',
zIndex: '9999'
});
document.body.appendChild(iframe);
// Registrar el handler de mensajes
messageHandler = createMessageHandler(iframe);
window.addEventListener('message', messageHandler, false);
}
Paso 3 — Escuchar los eventos postMessage
El WebSDK se comunica con tu página mediante window.postMessage.
Hay dos eventos que debes manejar. Siempre valida el event.origin
para evitar mensajes de orígenes no autorizados.
Evento (event.data) |
Tipo | Cuándo se dispara | Qué hacer |
|---|---|---|---|
| { accion: 'ocr_result', imgBase64, result } | object | Resultado del OCR listo (llega antes de GS_CLOSE_WEBSDK) | Guardar imagen y datos OCR para mostrarlos al cerrar el iframe |
| 'GS_CLOSE_WEBSDK_IDLE' | string | Opcional. Llega justo antes de GS_CLOSE_WEBSDK solo cuando el WebSDK se cerró solo, por inactividad o expiración de la sesión (no por acción manual del usuario) | Si te interesa distinguirlo, guarda el motivo antes de que llegue GS_CLOSE_WEBSDK |
| 'GS_CLOSE_WEBSDK' | string | Siempre se envía al cerrar el WebSDK, haya o no resultado (aceptó la captura, canceló, o se cerró solo) | Remover el iframe, desregistrar el listener, mostrar resultados si los hay |
let messageHandler = null; // referencia global para poder removerlo
let ocrResult = null; // resultado OCR almacenado temporalmente
function createMessageHandler(iframe) {
return function messageHandler(event) {
// Validar origen — NUNCA omitir este paso
if (event.origin !== 'https://<tu-dominio-asignado>') return;
const datos = event.data;
// ── Caso 1: resultado OCR ─────────────────────────────
if (datos?.accion === 'ocr_result') {
// Guardar imagen capturada
const imgElement = document.getElementById('captured-img');
if (imgElement) {
imgElement.src = 'data:image/png;base64,' + datos.imgBase64;
}
datos.imgBase64 = null; // liberar memoria
// Guardar resultado OCR
ocrResult = (typeof datos.result === 'string')
? JSON.parse(datos.result)
: datos.result;
const jsonObjeto = Array.isArray(ocrResult) ? ocrResult[0] : ocrResult;
document.getElementById('ocr-json').textContent =
JSON.stringify(jsonObjeto, null, 2);
}
// ── Caso 2: cerrar WebSDK ─────────────────────────────
if (datos === 'GS_CLOSE_WEBSDK') {
iframe.remove();
window.removeEventListener('message', messageHandler);
messageHandler = null;
// Mostrar los resultados almacenados
if (ocrResult) {
document.getElementById('result-section').style.display = 'block';
}
}
};
}
ocr_result llega antes que GS_CLOSE_WEBSDK.
Por eso se deben guardar los datos en variables temporales y solo mostrarlos al recibir
la señal de cierre.
Gestión de la sesión (opcional, recomendado)
Si tu página mantiene la sesión abierta un tiempo antes de mostrar el iframe, o si el usuario puede cerrar tu interfaz sin completar la captura, te recomendamos estos dos endpoints adicionales para no dejar sesiones "huérfanas" abiertas en el servidor.
VERIFICAR SI LA SESIÓN SIGUE ACTIVA
async function checkSessionStatus(sessionId) {
const response = await fetch(
`https://<tu-api-asignada>/api/session/${sessionId}`,
{ method: 'GET', headers: { 'Content-Type': 'application/json' } }
);
if (response.status === 404) return 'EXPIRED'; // ya no existe
const data = await response.json();
// data.status: "CREATED" (activa) | "EXPIRED" | "NOT_FOUND"
return data.status;
}
CERRAR LA SESIÓN EXPLÍCITAMENTE
async function cerrarSesion(sessionId) {
try {
await fetch(
`https://<tu-api-asignada>/api/session/${sessionId}/close`,
{ method: 'POST' }
);
} catch (error) {
// Si falla (sin red, error del servidor), no bloquees al usuario por esto.
console.error('No se pudo cerrar la sesión en el backend:', error.message);
}
}
POST /api/session/{sessionId}/close cuando el usuario cierre tu
interfaz sin completar el flujo (clic en "Salir", cierre de la ventana, timeout de
inactividad propio de tu página, etc.). Así liberas la sesión y evitas consumir créditos
de forma innecesaria.
Paso 4 — Código completo de integración
Copia este bloque completo. Solo necesitas reemplazar las credenciales
(tu_correo@empresa.com y tu_contraseña).
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mi integración OCR</title>
</head>
<body>
<button id="btnCapturar">Capturar documento</button>
<!-- Imagen capturada -->
<img id="captured-img" alt="Imagen capturada" style="max-width:300px;display:none;" />
<!-- Resultado OCR -->
<pre id="ocr-json"></pre>
<script>
// ── Configuración ────────────────────────────────────
const GS_ORIGIN = 'https://<tu-dominio-asignado>';
const API_URL = 'https://<tu-api-asignada>/api/session';
let messageHandler = null;
let ocrResult = null;
// ── 1. Obtener sesión ────────────────────────────────
async function getSessionInfo() {
const res = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'tu_correo@empresa.com', // ← reemplazar
pwd: 'tu_contraseña' // ← reemplazar
})
});
if (!res.ok) throw new Error('Error al obtener sesión: ' + res.status);
const data = await res.json();
return { sessionId: data.idSesion, urlWeb: data.urlWeb };
}
// ── 2. Mostrar WebSDK en iframe ──────────────────────
async function abrirWebSDK() {
// Remover listener anterior
if (messageHandler) {
window.removeEventListener('message', messageHandler);
messageHandler = null;
}
const { urlWeb } = await getSessionInfo();
if (!urlWeb) { alert('No se pudo obtener la sesión.'); return; }
const iframe = document.createElement('iframe');
iframe.src = urlWeb;
iframe.allow = 'camera; microphone; accelerometer; gyroscope; magnetometer';
iframe.setAttribute('allowfullscreen', 'true');
iframe.id = 'ocr_frame';
Object.assign(iframe.style, {
position: 'fixed', inset: '0',
width: '100%', height: '100%',
border: 'none', zIndex: '9999'
});
document.body.appendChild(iframe);
// ── 3. Escuchar eventos del WebSDK ───────────────
messageHandler = function(event) {
if (event.origin !== GS_ORIGIN) return;
const datos = event.data;
if (datos?.accion === 'ocr_result') {
// Guardar imagen
const img = document.getElementById('captured-img');
img.src = 'data:image/png;base64,' + datos.imgBase64;
img.style.display = 'block';
datos.imgBase64 = null; // liberar memoria
// Guardar resultado OCR
ocrResult = (typeof datos.result === 'string')
? JSON.parse(datos.result) : datos.result;
const obj = Array.isArray(ocrResult) ? ocrResult[0] : ocrResult;
document.getElementById('ocr-json').textContent =
JSON.stringify(obj, null, 2);
}
if (datos === 'GS_CLOSE_WEBSDK') {
// Cerrar iframe y limpiar listener
document.getElementById('ocr_frame')?.remove();
window.removeEventListener('message', messageHandler);
messageHandler = null;
// Aquí ya tienes ocrResult y la imagen disponibles
console.log('OCR completado:', ocrResult);
}
};
window.addEventListener('message', messageHandler, false);
}
// ── Disparar desde el botón ──────────────────────────
document.getElementById('btnCapturar').addEventListener('click', abrirWebSDK);
</script>
</body>
</html>
Estructura del resultado OCR
El campo result dentro del evento ocr_result contiene la lectura
del documento. Puede venir como string JSON o como objeto
y en ocasiones como un array (toma el primer elemento).
El contenido varía según el tipo de documento procesado (INE, pasaporte, licencia, etc.).
// Normalizar resultado (aplica al recibir datos.result)
const rawData = (typeof datos.result === 'string')
? JSON.parse(datos.result)
: datos.result;
const jsonObjeto = Array.isArray(rawData) ? rawData[0] : rawData;
// Ejemplo de campos para una INE / credencial de elector:
// {
// "NAME": "JUAN PÉREZ LÓPEZ",
// "CURP": "PELJ900101HDFRNS09",
// "SURNAME": ["PÉREZ", "LÓPEZ"],
// "ADDRESS": ["CALLE REFORMA 45", "COL. CENTRO", "CDMX 06000"],
// "DOB": "01/01/1990",
// "FOLIO": "123456789012"
// }
result puede venir como
{ "result": "Documento no reconocido." } en lugar de los campos esperados.
Verifica ese caso antes de intentar mostrar los datos como si fuera un documento válido.
Checklist de integración
- Solicitar credenciales de acceso a Genuine Solutions
-
Llamar al endpoint
POST /api/sessionantes de abrir el iframe -
Crear el iframe con
allow="camera; microphone; ..." -
Registrar
window.addEventListener('message', handler)después de crear el iframe -
Validar
event.origin === 'https://<tu-dominio-asignado>' -
Capturar el evento
ocr_result(imagen + datos OCR) -
Remover el iframe y el listener al recibir
'GS_CLOSE_WEBSDK' -
Liberar la memoria de
imgBase64asignandonulltras usarlo - Tu sitio debe servirse por HTTPS (requerido para acceder a la cámara)
-
(Opcional) Llamar a
POST /api/session/{id}/closesi el usuario abandona el flujo sin completarlo -
(Opcional) Escuchar
'GS_CLOSE_WEBSDK_IDLE'si necesitas distinguir un cierre automático de uno manual
Demo interactiva
Probar el WebSDK
Haz clic para abrir un entorno de prueba en vivo, donde podrás iniciar sesión y ver el detector de documentos en tiempo real.
Tus credenciales se usan únicamente para esa sesión y no se almacenan.