Quick Start Guide - CDP Enterprise
Comienza a usar el CDP Enterprise de Nerdistan en 5 minutos.
🚀 Inicio Rápido
1. Verificar el Estado del Sistema
curl https://nerdistan-datalake-production.up.railway.app/health
Respuesta esperada:
{
"success": true,
"message": "System operational",
"data": {
"database": "connected",
"profiles": 202808
}
}
2. Enviar tu Primer Evento
curl -X POST https://nerdistan-datalake-production.up.railway.app/api/v2/cdp/events \
-H "Content-Type: application/json" \
-d '{
"tenant_id": 56,
"customer_id": 12345,
"event_type": "product_view",
"event_data": {
"product_id": "SKU123",
"product_name": "Zapatillas Running",
"price": 89990,
"category": "Deportes"
}
}'
3. Verificar el Estado del CDP
curl https://nerdistan-datalake-production.up.railway.app/api/v2/cdp/status
📦 Integración JavaScript
Instalación del Cliente
<!-- En tu HTML -->
<script>
class CDPTracker {
constructor(tenantId) {
this.tenantId = tenantId;
this.baseURL = 'https://nerdistan-datalake-production.up.railway.app';
this.customerId = this.getCustomerId();
this.events = [];
}
getCustomerId() {
// Obtener del localStorage o generar uno temporal
let id = localStorage.getItem('cdp_customer_id');
if (!id) {
id = 'temp_' + Date.now();
localStorage.setItem('cdp_customer_id', id);
}
return id;
}
track(eventType, eventData) {
const event = {
tenant_id: this.tenantId,
customer_id: this.customerId,
event_type: eventType,
event_data: eventData
};
// Agregar al buffer
this.events.push(event);
// Enviar si hay más de 10 eventos o han pasado 5 segundos
if (this.events.length >= 10) {
this.flush();
}
}
async flush() {
if (this.events.length === 0) return;
const eventsToSend = [...this.events];
this.events = [];
try {
const response = await fetch(`${this.baseURL}/api/v2/cdp/events/batch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(eventsToSend)
});
const result = await response.json();
console.log('CDP Events sent:', result);
} catch (error) {
console.error('CDP Error:', error);
// Re-agregar eventos al buffer en caso de error
this.events = eventsToSend.concat(this.events);
}
}
setCustomerId(id) {
this.customerId = id;
localStorage.setItem('cdp_customer_id', id);
}
}
// Inicializar tracker
window.cdp = new CDPTracker(56); // Reemplazar 56 con tu tenant_id
// Auto-flush cada 5 segundos
setInterval(() => window.cdp.flush(), 5000);
</script>
Tracking de Eventos Comunes
// Vista de página
cdp.track('page_view', {
page: window.location.pathname,
title: document.title,
referrer: document.referrer
});
// Vista de producto
cdp.track('product_view', {
product_id: 'SKU123',
product_name: 'Zapatillas Running',
price: 89990,
category: 'Deportes'
});
// Agregar al carrito
cdp.track('add_to_cart', {
product_id: 'SKU123',
quantity: 1,
price: 89990
});
// Compra completada
cdp.track('purchase', {
order_id: 'ORD-2025-001',
total: 89990,
items: [
{
product_id: 'SKU123',
quantity: 1,
price: 89990
}
],
payment_method: 'credit_card'
});
// Búsqueda
cdp.track('search', {
query: 'zapatillas nike',
results_count: 45
});
// Login de usuario
cdp.track('user_login', {
method: 'email',
success: true
});
// Identificar usuario después del login
cdp.setCustomerId('customer_12345');
🔧 Integración Backend (Node.js)
Instalación
npm install axios
Cliente Node.js
const axios = require('axios');
class CDPClient {
constructor(tenantId) {
this.tenantId = tenantId;
this.baseURL = 'https://nerdistan-datalake-production.up.railway.app';
}
async sendEvent(customerId, eventType, eventData) {
try {
const response = await axios.post(`${this.baseURL}/api/v2/cdp/events`, {
tenant_id: this.tenantId,
customer_id: customerId,
event_type: eventType,
event_data: eventData
});
return response.data;
} catch (error) {
console.error('CDP Error:', error.response?.data || error.message);
throw error;
}
}
async sendBatch(events) {
try {
const formattedEvents = events.map(e => ({
tenant_id: this.tenantId,
customer_id: e.customerId,
event_type: e.eventType,
event_data: e.eventData
}));
const response = await axios.post(
`${this.baseURL}/api/v2/cdp/events/batch`,
formattedEvents
);
return response.data;
} catch (error) {
console.error('CDP Batch Error:', error.response?.data || error.message);
throw error;
}
}
async getProfile(profileId) {
try {
const response = await axios.get(
`${this.baseURL}/api/v2/cdp/profiles/${profileId}?tenant_id=${this.tenantId}`
);
return response.data;
} catch (error) {
console.error('CDP Profile Error:', error.response?.data || error.message);
throw error;
}
}
async getStatus() {
try {
const response = await axios.get(`${this.baseURL}/api/v2/cdp/status`);
return response.data;
} catch (error) {
console.error('CDP Status Error:', error.response?.data || error.message);
throw error;
}
}
}
// Uso
const cdp = new CDPClient(56); // Tu tenant_id
// Enviar evento de compra
cdp.sendEvent('customer_12345', 'purchase', {
order_id: 'ORD-2025-001',
total: 89990,
items: 1
}).then(result => {
console.log('Evento enviado:', result);
});
// Enviar batch de eventos
cdp.sendBatch([
{
customerId: 'customer_12345',
eventType: 'page_view',
eventData: { page: '/home' }
},
{
customerId: 'customer_12346',
eventType: 'product_view',
eventData: { product_id: 'SKU456' }
}
]).then(result => {
console.log('Batch enviado:', result);
});
🐍 Integración Python
Instalación
pip install requests
Cliente Python
import requests
import json
from typing import Dict, List, Any
class CDPClient:
def __init__(self, tenant_id: int):
self.tenant_id = tenant_id
self.base_url = 'https://nerdistan-datalake-production.up.railway.app'
self.session = requests.Session()
self.session.headers.update({'Content-Type': 'application/json'})
def send_event(self, customer_id: int, event_type: str, event_data: Dict[str, Any]) -> Dict:
"""Enviar un evento único"""
payload = {
'tenant_id': self.tenant_id,
'customer_id': customer_id,
'event_type': event_type,
'event_data': event_data
}
response = self.session.post(
f'{self.base_url}/api/v2/cdp/events',
json=payload
)
response.raise_for_status()
return response.json()
def send_batch(self, events: List[Dict]) -> Dict:
"""Enviar múltiples eventos"""
formatted_events = []
for event in events:
formatted_events.append({
'tenant_id': self.tenant_id,
'customer_id': event['customer_id'],
'event_type': event['event_type'],
'event_data': event['event_data']
})
response = self.session.post(
f'{self.base_url}/api/v2/cdp/events/batch',
json=formatted_events
)
response.raise_for_status()
return response.json()
def get_profile(self, profile_id: int) -> Dict:
"""Obtener información de un perfil"""
response = self.session.get(
f'{self.base_url}/api/v2/cdp/profiles/{profile_id}',
params={'tenant_id': self.tenant_id}
)
response.raise_for_status()
return response.json()
def get_status(self) -> Dict:
"""Obtener estado del CDP"""
response = self.session.get(f'{self.base_url}/api/v2/cdp/status')
response.raise_for_status()
return response.json()
# Uso
if __name__ == "__main__":
# Inicializar cliente
cdp = CDPClient(tenant_id=56)
# Enviar evento de vista de producto
result = cdp.send_event(
customer_id=12345,
event_type='product_view',
event_data={
'product_id': 'SKU123',
'product_name': 'Zapatillas Running',
'price': 89990,
'category': 'Deportes'
}
)
print(f"Evento enviado: {result}")
# Enviar batch de eventos
batch_result = cdp.send_batch([
{
'customer_id': 12345,
'event_type': 'page_view',
'event_data': {'page': '/home', 'duration': 30}
},
{
'customer_id': 12346,
'event_type': 'add_to_cart',
'event_data': {'product_id': 'SKU456', 'quantity': 2}
}
])
print(f"Batch enviado: {batch_result}")
# Obtener estado del CDP
status = cdp.get_status()
print(f"Estado del CDP: {status}")
📊 Eventos Recomendados
E-commerce
product_view- Vista de productoadd_to_cart- Agregar al carritoremove_from_cart- Quitar del carritocheckout_started- Inicio de checkoutpurchase- Compra completadaproduct_review- Review de producto
Engagement
page_view- Vista de páginaemail_open- Email abiertoemail_click- Click en emailpush_received- Push notification recibidapush_clicked- Push notification clickeada
Usuario
user_signup- Registro de usuariouser_login- Login de usuariouser_logout- Logout de usuarioprofile_update- Actualización de perfilpassword_reset- Reset de contraseña
Custom
custom_event- Evento personalizado con cualquier data
🔍 Debugging
Verificar que los eventos se están procesando
# Ver estado y estadísticas
curl https://nerdistan-datalake-production.up.railway.app/api/v2/cdp/status
# Ver un perfil específico
curl "https://nerdistan-datalake-production.up.railway.app/api/v2/cdp/profiles/12345?tenant_id=56"
Logs y Monitoreo
Los eventos procesados aparecerán en:
- La tabla
cdp.real_time_eventsen la base de datos - Los traits calculados en
cdp.unified_customer_profiles.real_time_traits - Las audiencias en
cdp.audience_memberships
🆘 Troubleshooting
Error: "tenant_id not found"
Verifica que estás usando el tenant_id correcto. Contacta soporte para obtener tu tenant_id.
Error: "customer_id required"
Todos los eventos deben incluir un customer_id. Puede ser un ID temporal hasta que el usuario se autentique.
Eventos no aparecen
- Verifica que la respuesta de la API sea
success: true - Los traits pueden tardar hasta 5 segundos en actualizarse
- Las audiencias se recalculan cada 10 segundos
📞 Soporte
- Email: soporte@nerdistan.com.ar
- Slack: #cdp-support
- Docs: https://docs.nerdistan.com.ar
¡Felicitaciones! Ya estás enviando eventos al CDP Enterprise. 🎉