Tenant Integrations API
Overview
La API de Integraciones gestiona las conexiones entre tenants y sistemas externos como VTEX, MercadoLibre, Google Ads y Facebook. Implementa encriptación AES-256-GCM para credenciales sensibles y validación en tiempo real.
🔒 Seguridad
- Encriptación: AES-256-GCM para tokens y credenciales
- Validación: Verificación de credenciales antes de guardar
- Auditoría: Log completo de cambios y accesos
- Aislamiento: Separación completa entre tenants
📊 Estado Actual
| Integración | Tenants Activos | Total Configurado |
|---|---|---|
| VTEX | 28 | 28 |
| MercadoLibre | 0 | 0 |
| Google Ads | 0 | 0 |
| 0 | 0 |
API Endpoints
1. List Tenant Integrations
Lista todas las integraciones configuradas para un tenant.
GET /api/v2/tenant-integrations/{tenantId}
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
tenantId | integer | ✅ | Tenant ID |
Response (200 OK)
{
"success": true,
"data": [
{
"id": 1,
"tenant_id": 56,
"integration_type": "vtex",
"account_name": "chelseaio",
"environment": "vtexcommercestable",
"is_active": true,
"last_sync": "2024-09-16T10:00:00Z",
"sync_status": "success",
"created_at": "2024-01-15T08:00:00Z",
"updated_at": "2024-09-16T10:00:00Z"
},
{
"id": 2,
"tenant_id": 56,
"integration_type": "mercadolibre",
"account_name": "CHELSEA_STORE",
"is_active": false,
"last_sync": null,
"sync_status": "never_synced"
}
],
"count": 2
}
2. Get Integration Details
Obtiene detalles de una integración específica.
GET /api/v2/tenant-integrations/integration/{integrationId}
Response (200 OK)
{
"success": true,
"data": {
"id": 1,
"tenant_id": 56,
"tenant_name": "Chelsea IO - Exit",
"integration_type": "vtex",
"account_name": "chelseaio",
"environment": "vtexcommercestable",
"is_active": true,
"configuration": {
"api_version": "v2",
"sync_products": true,
"sync_orders": true,
"sync_customers": true,
"webhook_url": null
},
"statistics": {
"total_syncs": 145,
"successful_syncs": 142,
"failed_syncs": 3,
"last_error": null,
"avg_sync_time": "45.2s"
},
"last_sync": "2024-09-16T10:00:00Z",
"next_scheduled_sync": "2024-09-16T22:00:00Z"
}
}
3. Create Integration
Crea una nueva integración para un tenant.
POST /api/v2/tenant-integrations
Request Body
{
"tenant_id": 56,
"integration_type": "vtex",
"account_name": "chelseaio",
"environment": "vtexcommercestable",
"app_key": "vtexappkey-chelseaio-XXXXX",
"app_token": "EYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"configuration": {
"sync_products": true,
"sync_orders": true,
"sync_customers": true
}
}
Integration Types
| Type | Description | Required Fields |
|---|---|---|
vtex | VTEX eCommerce | account_name, environment, app_key, app_token |
mercadolibre | MercadoLibre | client_id, client_secret, redirect_uri |
google_ads | Google Ads | customer_id, developer_token, refresh_token |
facebook | Facebook Ads | app_id, app_secret, access_token |
Response (201 Created)
{
"success": true,
"message": "Integration created successfully",
"data": {
"id": 29,
"tenant_id": 56,
"integration_type": "vtex",
"validation_status": "valid",
"is_active": true
}
}
Error Response (400 Bad Request)
{
"success": false,
"error": "Invalid credentials",
"details": {
"validation_error": "VTEX API returned 401: Invalid app key or token",
"account_name": "chelseaio"
}
}
4. Update Integration
Actualiza una integración existente.
PUT /api/v2/tenant-integrations/{integrationId}
Request Body
{
"is_active": true,
"app_key": "new-vtex-app-key",
"app_token": "new-vtex-app-token",
"configuration": {
"sync_products": false,
"sync_orders": true,
"sync_customers": true,
"sync_interval": "hourly"
}
}
Response (200 OK)
{
"success": true,
"message": "Integration updated successfully",
"data": {
"id": 1,
"changes": {
"is_active": {"old": false, "new": true},
"configuration.sync_products": {"old": true, "new": false}
}
}
}
5. Delete Integration
Elimina una integración (soft delete).
DELETE /api/v2/tenant-integrations/{integrationId}
Response (200 OK)
{
"success": true,
"message": "Integration deleted successfully",
"data": {
"id": 29,
"deleted_at": "2024-09-16T20:00:00Z"
}
}
6. Validate VTEX Credentials
Valida credenciales VTEX antes de crear/actualizar integración.
POST /api/v2/tenant-integrations/validate/vtex
Request Body
{
"account_name": "chelseaio",
"app_key": "vtexappkey-chelseaio-XXXXX",
"app_token": "EYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"environment": "vtexcommercestable"
}
Response Success (200 OK)
{
"success": true,
"message": "VTEX credentials are valid",
"account_info": {
"account_name": "chelseaio",
"account_id": "4c5e6f7g-8h9i-0j1k-2l3m-4n5o6p7q8r9s",
"is_active": true,
"hosts": [
"chelseaio.vtexcommercestable.com.br",
"chelseaio.myvtex.com"
],
"apis_available": {
"catalog": true,
"orders": true,
"masterdata": true,
"payments": true
}
}
}
Response Error (400 Bad Request)
{
"success": false,
"message": "Invalid VTEX credentials",
"error": {
"code": "INVALID_CREDENTIALS",
"details": "Authentication failed: 401 Unauthorized",
"account_name": "chelseaio",
"environment": "vtexcommercestable"
}
}
7. Test Integration Connection
Prueba la conexión de una integración existente.
POST /api/v2/tenant-integrations/{integrationId}/test
Response (200 OK)
{
"success": true,
"message": "Connection test successful",
"data": {
"integration_id": 1,
"type": "vtex",
"status": "connected",
"response_time": "245ms",
"endpoints_tested": {
"catalog": {
"status": "ok",
"response_time": "120ms"
},
"orders": {
"status": "ok",
"response_time": "89ms"
},
"masterdata": {
"status": "ok",
"response_time": "156ms"
}
}
}
}
8. Sync Integration Data
Trigger manual sync for an integration.
POST /api/v2/tenant-integrations/{integrationId}/sync
Request Body
{
"sync_type": "full",
"entities": ["products", "orders", "customers"],
"date_from": "2024-09-01",
"date_to": "2024-09-16"
}
Response (202 Accepted)
{
"success": true,
"message": "Sync initiated successfully",
"data": {
"sync_id": "sync_20240916_200000_56",
"status": "queued",
"estimated_time": "15 minutes",
"webhook_url": "https://api.example.com/webhooks/sync/status"
}
}
🔐 Encryption Service
El servicio de encriptación protege las credenciales sensibles:
// Encryption Service Implementation
class EncryptionService {
constructor() {
this.algorithm = 'aes-256-gcm';
this.secretKey = process.env.ENCRYPTION_KEY || crypto.randomBytes(32);
}
encrypt(text) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(this.algorithm, this.secretKey, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
return JSON.stringify({
iv: iv.toString('hex'),
authTag: authTag.toString('hex'),
encrypted: encrypted
});
}
decrypt(encryptedData) {
const { iv, authTag, encrypted } = JSON.parse(encryptedData);
const decipher = crypto.createDecipheriv(
this.algorithm,
this.secretKey,
Buffer.from(iv, 'hex')
);
decipher.setAuthTag(Buffer.from(authTag, 'hex'));
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
}
🔄 Integration Workflows
VTEX Integration Flow
graph TD
A[Create Integration] --> B{Validate Credentials}
B -->|Valid| C[Encrypt & Store]
B -->|Invalid| D[Return Error]
C --> E[Initial Sync]
E --> F[Schedule Recurring Sync]
F --> G[Process Data]
G --> H[Update CDP]
Sync Process
- Authentication: Validate stored credentials
- Data Fetch: Retrieve data from external system
- Transform: Map to CDP schema
- Validation: Check data integrity
- Storage: Save to CDP database
- Processing: Trigger CDP analysis
- Notification: Send webhook/email on completion
📊 Integration Monitoring
Health Check Endpoint
GET /api/v2/tenant-integrations/health
Response
{
"success": true,
"data": {
"total_integrations": 28,
"active_integrations": 25,
"by_type": {
"vtex": {
"total": 28,
"active": 25,
"last_24h_syncs": 50,
"success_rate": 0.96
}
},
"alerts": [
{
"integration_id": 15,
"tenant_id": 52,
"type": "sync_failure",
"message": "3 consecutive sync failures",
"since": "2024-09-16T18:00:00Z"
}
]
}
}
🛠️ Troubleshooting
Common Issues
VTEX Authentication Errors
{
"error": "INVALID_APP_KEY",
"solution": "Verify app key format: vtexappkey-{accountName}-{hash}"
}
Rate Limiting
{
"error": "RATE_LIMIT_EXCEEDED",
"retry_after": 60,
"solution": "Implement exponential backoff"
}
Sync Timeouts
{
"error": "SYNC_TIMEOUT",
"duration": "600s",
"solution": "Use batch processing for large datasets"
}
📝 Configuration Examples
VTEX Configuration
{
"tenant_id": 56,
"integration_type": "vtex",
"account_name": "mystore",
"environment": "vtexcommercestable",
"app_key": "vtexappkey-mystore-ABCDEF",
"app_token": "EYXXXXXXXXXXXXXXXX",
"configuration": {
"sync_interval": "hourly",
"batch_size": 500,
"retry_attempts": 3,
"webhook_notifications": true
}
}
MercadoLibre Configuration
{
"tenant_id": 52,
"integration_type": "mercadolibre",
"client_id": "1234567890123456",
"client_secret": "SECRET_KEY_HERE",
"redirect_uri": "https://api.example.com/callback/ml",
"configuration": {
"site_id": "MLA",
"sync_listings": true,
"sync_questions": true
}
}
🚀 Best Practices
- Always validate credentials before saving
- Use webhook notifications for async operations
- Implement retry logic with exponential backoff
- Monitor sync success rates regularly
- Rotate encryption keys periodically
- Log all integration activities for audit
- Use batch processing for large data sets
- Set appropriate timeouts based on data volume