Saltar al contenido principal

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ónTenants ActivosTotal Configurado
VTEX2828
MercadoLibre00
Google Ads00
Facebook00

API Endpoints

1. List Tenant Integrations

Lista todas las integraciones configuradas para un tenant.

GET /api/v2/tenant-integrations/{tenantId}

Parameters

ParameterTypeRequiredDescription
tenantIdintegerTenant 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

TypeDescriptionRequired Fields
vtexVTEX eCommerceaccount_name, environment, app_key, app_token
mercadolibreMercadoLibreclient_id, client_secret, redirect_uri
google_adsGoogle Adscustomer_id, developer_token, refresh_token
facebookFacebook Adsapp_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

  1. Authentication: Validate stored credentials
  2. Data Fetch: Retrieve data from external system
  3. Transform: Map to CDP schema
  4. Validation: Check data integrity
  5. Storage: Save to CDP database
  6. Processing: Trigger CDP analysis
  7. 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

  1. Always validate credentials before saving
  2. Use webhook notifications for async operations
  3. Implement retry logic with exponential backoff
  4. Monitor sync success rates regularly
  5. Rotate encryption keys periodically
  6. Log all integration activities for audit
  7. Use batch processing for large data sets
  8. Set appropriate timeouts based on data volume