Rutas de Redirección
Endpoints para manejar redirecciones de Bridge tras completar procesos (éxito o fallo), procesar datos en backend y redirigir al frontend según el ambiente.
🔁 Redirecciones Bridge → Backend → Frontend
Bridge redirige al backend por GET (sin autenticación). El backend valida parámetros, registra el estado y redirige al frontend con la información necesaria.
1) Éxito en Bridge
GET
/bridge/successRedirección exitosa después de firmar ToS en Bridge
📋 Parámetros
signed_agreement_idstringrequeridoID del acuerdo firmado
user_tokenstringrequeridoToken temporal del usuario (UUID)
📤 Respuesta
// Redirección HTTP 302 al frontend (success)
// Ejemplo:
// https://tu-frontend.com/registro-exitoso?customer_id=bridge_customer_123Ejemplo de URL (success)
GET /bridge/success?signed_agreement_id=agr_123&user_token=uuid-token-123
Comportamiento
Redirección automática a:
[https://tu-frontend.com/registro-exitoso?customer_id=bridge_customer_123](https://tu-frontend.com/registro-exitoso?customer_id=bridge_customer_123)
2) Fallo en Bridge
GET
/bridge/failedRedirección de fallo en Bridge
📋 Parámetros
errorstringCódigo de error (opcional)
messagestringMensaje descriptivo del error (opcional)
📤 Respuesta
// Redirección HTTP 302 al frontend (error)
// Ejemplo:
// https://tu-frontend.com/error?reason=bridge_verification_failedEjemplo de URL (failed)
GET /bridge/failed?error=verification_failed&message=Documents rejected
Comportamiento
Redirección automática a:
[https://tu-frontend.com/error?reason=bridge_verification_failed](https://tu-frontend.com/error?reason=bridge_verification_failed)
🔄 Flujo de Redirección
Proceso Exitoso
- Usuario firma ToS en portal de Bridge
- Bridge redirecciona a
/bridge/successcon parámetros - Backend procesa y actualiza estado
- Redirección final al frontend con
customer_id
Proceso Fallido
- Ocurre un error en Bridge (KYC, documentos, timeout, etc.)
- Bridge redirecciona a
/bridge/failedcon parámetros - Backend registra el fallo (logs)
- Redirección final al frontend con la causa del error
📋 Parámetros de Éxito
signed_agreement_id
- Tipo: String
- Descripción: ID único del acuerdo firmado
- Ejemplo:
agr_abc123def456 - Uso: Verificar que el acuerdo se firmó correctamente
user_token
- Tipo: String (UUID)
- Descripción: Token temporal del usuario
- Ejemplo:
550e8400-e29b-41d4-a716-446655440000 - Uso: Identificar al usuario y vincular con el customer
📋 Parámetros de Error
error
- Tipo: String
- Valores comunes:
verification_failed- Verificación KYC fallidadocuments_rejected- Documentos rechazadosinvalid_data- Datos inválidostimeout- Tiempo de sesión agotado
message
- Tipo: String
- Descripción: Mensaje descriptivo del error
- Ejemplo:
"Documents do not meet verification requirements"
🏠 URLs de Frontend (por ambiente)
Producción
const FRONTEND_URLS = {
success: 'https://app.swapbits.com/onboarding/success',
error: 'https://app.swapbits.com/onboarding/error'
};
Staging
const FRONTEND_URLS = {
success: 'https://staging.swapbits.com/onboarding/success',
error: 'https://staging.swapbits.com/onboarding/error'
};
Desarrollo
const FRONTEND_URLS = {
success: 'http://localhost:3000/onboarding/success',
error: 'http://localhost:3000/onboarding/error'
};
🔍 Procesamiento Backend
Éxito — /bridge/success
app.get('/bridge/success', async (req, res) => {
try {
const { signed_agreement_id, user_token } = req.query;
// 1. Validar parámetros
if (!signed_agreement_id || !user_token) {
return res.redirect(`${FRONTEND_URL}/error?reason=invalid_params`);
}
// 2. Buscar usuario por token
const user = await findUserByToken(user_token);
if (!user) {
return res.redirect(`${FRONTEND_URL}/error?reason=user_not_found`);
}
// 3. Obtener datos del customer en Bridge
const customer = await bridge.getCustomerByAgreement(signed_agreement_id);
// 4. Actualizar base de datos
await updateUserBridgeCustomer(user.id, customer.id);
// 5. Redireccionar al frontend
res.redirect(`${FRONTEND_URL}/success?customer_id=${customer.id}`);
} catch (error) {
logger.error('Bridge success redirect failed:', error);
res.redirect(`${FRONTEND_URL}/error?reason=processing_error`);
}
});
Error — /bridge/failed
app.get('/bridge/failed', (req, res) => {
const { error, message } = req.query;
// Log del error para debugging
logger.warn('Bridge redirect failed:', { error, message });
// Redireccionar con información del error
const params = new URLSearchParams({
reason: 'bridge_verification_failed',
error_code: error || 'unknown',
error_message: message || 'Verification failed'
});
res.redirect(`${FRONTEND_URL}/error?${params.toString()}`);
});
📱 Manejo en Frontend
Página de Éxito
// /onboarding/success
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const customerId = urlParams.get('customer_id');
if (customerId) {
setUserVerificationStatus('verified');
showSuccessMessage('¡Verificación completada exitosamente!');
setTimeout(() => {
navigate('/dashboard');
}, 3000);
}
}, []);
Página de Error
// /onboarding/error
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const reason = urlParams.get('reason');
const errorCode = urlParams.get('error_code');
const errorMessages = {
verification_failed: 'No se pudo verificar tu identidad',
documents_rejected: 'Los documentos fueron rechazados',
timeout: 'El tiempo de verificación ha expirado'
};
showErrorMessage(errorMessages[errorCode] || 'Error en la verificación');
}, []);
⚠️ Errores Comunes
Problemas típicos y solución
Parámetros faltantes
- Problema: URLs sin parámetros requeridos
- Solución: Validar parámetros y redirigir con
reason=invalid_params
Tokens expirados
- Problema:
user_tokenno válido o expirado - Solución: Generar un nuevo link de ToS
Customer no encontrado
- Problema:
signed_agreement_idinválido - Solución: Verificar configuración de Bridge
📝 Notas Importantes
Consideraciones de seguridad
- Las redirecciones son GET sin autenticación
- Los tokens son de un solo uso y expiran
- Siempre validar parámetros antes de procesar
- Mantener logs detallados para debugging
- URLs del frontend configurables por ambiente