La integración con iFrame requiere autorización especial de Cobrix. Contacta a tu Account Manager para iniciar el proceso.
Requisitos Previos
Para usar el checkout embebido en un iFrame necesitas:
KYC Aprobado
Tu empresa debe completar el proceso de Know Your Customer
Autorización de Cobrix
Solicitar y recibir autorización explícita del equipo de Cobrix
Registro de Dominios
Proporcionar los dominios donde se mostrará el iFrame
Proceso de Autorización
1. Solicitar Autorización
Contacta a tu Account Manager con:
- Nombre de tu empresa
- Dominios donde usarás el iFrame
- Caso de uso y justificación
- Volumen estimado de transacciones
2. Completar KYC
Si aún no lo has hecho, deberás completar el proceso KYC que incluye:
- Documentación legal de la empresa
- Información de representantes legales
- Verificación de identidad
3. Registro de Dominios
Proporciona todos los dominios donde mostrarás el checkout:
# Dominios a registrar (ejemplo)
https://tu-ecommerce.com
https://www.tu-ecommerce.com
https://checkout.tu-ecommerce.com
https://staging.tu-ecommerce.com # Para pruebas
Cada dominio debe registrarse explícitamente. Subdominios no se incluyen automáticamente.
Implementación
Una vez autorizado, puedes implementar el iFrame:
HTML Básico
<iframe
id="cobrix-checkout"
src="https://checkout.cobrix.co/{sessionId}?embed=true"
width="100%"
height="600"
frameborder="0"
allow="payment"
style="border: none; border-radius: 8px;"
></iframe>
Parámetros de URL
| Parámetro | Valor | Descripción |
|---|
embed | true | Activa modo embebido |
theme | light / dark | Tema visual (opcional) |
lang | es / en | Idioma (opcional) |
https://checkout.cobrix.co/{sessionId}?embed=true&theme=light&lang=es
Comunicación con el iFrame
El checkout envía mensajes a la ventana padre usando postMessage:
Escuchar Eventos
window.addEventListener('message', (event) => {
// Verificar origen
if (event.origin !== 'https://checkout.cobrix.co') {
return;
}
const { type, data } = event.data;
switch (type) {
case 'cobrix:ready':
console.log('Checkout cargado');
break;
case 'cobrix:resize':
// Ajustar altura del iFrame
document.getElementById('cobrix-checkout').style.height = `${data.height}px`;
break;
case 'cobrix:payment:success':
console.log('Pago exitoso:', data.transactionId);
handlePaymentSuccess(data);
break;
case 'cobrix:payment:failed':
console.log('Pago fallido:', data.reason);
handlePaymentFailed(data);
break;
case 'cobrix:cancelled':
console.log('Usuario canceló');
handleCancelled();
break;
}
});
Eventos Disponibles
| Evento | Descripción | Datos |
|---|
cobrix:ready | Checkout cargado | - |
cobrix:resize | Cambio de altura | { height } |
cobrix:payment:success | Pago exitoso | { transactionId, method } |
cobrix:payment:failed | Pago fallido | { reason } |
cobrix:cancelled | Usuario canceló | - |
Implementación Completa
<!DOCTYPE html>
<html>
<head>
<title>Checkout</title>
<style>
.checkout-container {
max-width: 500px;
margin: 0 auto;
padding: 20px;
}
.checkout-frame {
width: 100%;
min-height: 500px;
border: none;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.loading {
text-align: center;
padding: 40px;
color: #666;
}
</style>
</head>
<body>
<div class="checkout-container">
<div id="loading" class="loading">
Cargando checkout...
</div>
<iframe
id="cobrix-checkout"
class="checkout-frame"
style="display: none;"
allow="payment"
></iframe>
</div>
<script>
const sessionId = 'TU_SESSION_ID'; // Obtener de tu backend
const checkoutUrl = `https://checkout.cobrix.co/${sessionId}?embed=true`;
const iframe = document.getElementById('cobrix-checkout');
const loading = document.getElementById('loading');
// Cargar iFrame
iframe.src = checkoutUrl;
// Escuchar mensajes
window.addEventListener('message', (event) => {
if (event.origin !== 'https://checkout.cobrix.co') return;
const { type, data } = event.data;
switch (type) {
case 'cobrix:ready':
loading.style.display = 'none';
iframe.style.display = 'block';
break;
case 'cobrix:resize':
iframe.style.height = `${data.height}px`;
break;
case 'cobrix:payment:success':
// Redirigir a página de éxito
window.location.href = `/success?tx=${data.transactionId}`;
break;
case 'cobrix:payment:failed':
alert('El pago no pudo procesarse. Por favor intenta de nuevo.');
break;
case 'cobrix:cancelled':
window.location.href = '/cart';
break;
}
});
</script>
</body>
</html>
React Component
import { useEffect, useRef, useState } from 'react';
export function CobrixCheckout({ sessionId, onSuccess, onFailure, onCancel }) {
const iframeRef = useRef(null);
const [loading, setLoading] = useState(true);
const [height, setHeight] = useState(500);
useEffect(() => {
const handleMessage = (event) => {
if (event.origin !== 'https://checkout.cobrix.co') return;
const { type, data } = event.data;
switch (type) {
case 'cobrix:ready':
setLoading(false);
break;
case 'cobrix:resize':
setHeight(data.height);
break;
case 'cobrix:payment:success':
onSuccess?.(data);
break;
case 'cobrix:payment:failed':
onFailure?.(data);
break;
case 'cobrix:cancelled':
onCancel?.();
break;
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [onSuccess, onFailure, onCancel]);
const checkoutUrl = `https://checkout.cobrix.co/${sessionId}?embed=true`;
return (
<div>
{loading && <div className="loading">Cargando...</div>}
<iframe
ref={iframeRef}
src={checkoutUrl}
width="100%"
height={height}
frameBorder="0"
allow="payment"
style={{
display: loading ? 'none' : 'block',
border: 'none',
borderRadius: '8px'
}}
/>
</div>
);
}
Seguridad
Importante: Aunque uses iFrame, siempre verifica los webhooks. Los eventos del iFrame son informativos pero el webhook es la fuente de verdad.
Verificaciones Recomendadas
- Verificar origen de los mensajes (
event.origin)
- No confiar solo en los eventos del iFrame para confirmar pagos
- Siempre procesar el webhook
payment.succeeded en tu backend
- Implementar timeout para sesiones abandonadas
Troubleshooting
El iFrame no carga
| Problema | Causa | Solución |
|---|
| Pantalla en blanco | Dominio no autorizado | Verificar registro de dominio |
| Error X-Frame-Options | Headers de seguridad | Contactar soporte |
| Error de CSP | Content Security Policy | Agregar cobrix.co a CSP |
No recibo eventos
- Verificar que
event.origin sea correcto
- Verificar que el listener esté activo antes de cargar el iFrame
- Revisar consola del navegador por errores