# WhatsApp Gateway - Arquitectura Profesional ## πŸ—οΈ Arquitectura del Sistema ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Manager Web β”‚ β”‚ (React + TypeScript) β”‚ β”‚ - QR Display β”‚ β”‚ - Status Dashboard β”‚ β”‚ - Control Interface β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ HTTP/WebSocket β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ WhatsApp Gateway (Node) β”‚ β”‚ Baileys β”‚ β”‚ - Session Management β”‚ β”‚ - QR Generation β”‚ β”‚ - Message Handling β”‚ β”‚ - WebSocket Events β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ REST API β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Core API Layer β”‚ β”‚ - Send Messages β”‚ β”‚ - Bulk Operations β”‚ β”‚ - Status Monitoring β”‚ β”‚ - Health Checks β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ File Storage β”‚ β”‚ - Session Credentials β”‚ β”‚ - Auth Information β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` ## πŸš€ Inicio RΓ‘pido ### 1. Instalar Dependencias ```bash # Gateway (Backend) cd gateway npm install # Manager Web (Frontend) cd ../manager npm install ``` ### 2. Configurar Variables de Entorno ```bash # gateway/.env PORT=3001 NODE_ENV=production SESSION_ID=default LOG_LEVEL=info ``` ### 3. Iniciar Servicios ```bash # Terminal 1: Gateway cd gateway npm run dev # Terminal 2: Manager Web cd manager npm run dev ``` ### 4. Acceder a la Interfaz - **Manager Web**: http://localhost:3002 - **API Gateway**: http://localhost:3001 - **WebSocket**: ws://localhost:3003 ## πŸ“‘ API Endpoints ### Enviar Mensaje ```http POST /api/send Content-Type: application/json { "jid": "1234567890@s.whatsapp.net", "content": "Hola desde el Gateway!", "type": "text" } ``` ### Enviar Mensajes Masivos ```http POST /api/send/bulk Content-Type: application/json { "messages": [ { "jid": "1234567890@s.whatsapp.net", "content": "Mensaje 1", "type": "text" }, { "jid": "0987654321@s.whatsapp.net", "content": "Mensaje 2", "type": "text" } ] } ``` ### Ver Estado ```http GET /api/status ``` ### Health Check ```http GET /api/health ``` ## πŸ”§ ConfiguraciΓ³n para VPS ### Systemd Service (Gateway) ```ini # /etc/systemd/system/whatsapp-gateway.service [Unit] Description=WhatsApp Gateway Service After=network.target [Service] Type=simple User=whatsapp WorkingDirectory=/opt/whatsapp-gateway ExecStart=/usr/bin/node dist/index.js Restart=always RestartSec=10 Environment=NODE_ENV=production Environment=PORT=3001 [Install] WantedBy=multi-user.target ``` ### Nginx Reverse Gateway ```nginx # /etc/nginx/sites-available/whatsapp-gateway server { listen 80; server_name tu-dominio.com; # Manager Web location / { proxy_pass http://localhost:3002; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # API Gateway location /api/ { proxy_pass http://localhost:3001; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # WebSocket location /ws { proxy_pass http://localhost:3003; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; } } ``` ### Docker Compose ```yaml # docker-compose.yml version: '3.8' services: whatsapp-gateway: build: ./gateway ports: - "3001:3001" - "3003:3003" volumes: - ./auth_info:/app/auth_info environment: - NODE_ENV=production - PORT=3001 restart: unless-stopped whatsapp-manager: build: ./manager ports: - "3002:3002" depends_on: - whatsapp-gateway restart: unless-stopped nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf depends_on: - whatsapp-gateway - whatsapp-manager restart: unless-stopped ``` ## πŸ” Seguridad ### 1. Variables de Entorno ```bash # Nunca exponer credenciales en el cΓ³digo SESSION_ID=unique-session-id API_KEY=your-api-key-here WEBHOOK_SECRET=webhook-secret ``` ### 2. CORS Configurado ```typescript // Solo dominios confiables cors({ origin: ['https://tu-dominio.com', 'https://manager.tu-dominio.com'], credentials: true }) ``` ### 3. Rate Limiting ```bash # Nginx rate limiting limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; ``` ## πŸ“ˆ Monitoreo ### Logs Estructurados ```bash # Ver logs en tiempo real tail -f /var/log/whatsapp-gateway.log | jq '.' ``` ### MΓ©tricas de Salud ```bash # Health check endpoint curl http://localhost:3001/api/health ``` ### Uso de Recursos ```bash # Monitorear memoria y CPU htop docker stats ``` ## πŸš€ Despliegue en VPS ### 1. Preparar Servidor ```bash # Actualizar sistema sudo apt update && sudo apt upgrade -y # Instalar Node.js 18+ curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt-get install -y nodejs # Instalar PM2 sudo npm install -g pm2 ``` ### 2. Clonar y Configurar ```bash # Clonar repositorio git clone whatsapp-gateway cd whatsapp-gateway # Instalar dependencias cd gateway && npm install cd ../manager && npm install ``` ### 3. Iniciar con PM2 ```bash # Gateway pm2 start gateway/dist/index.js --name whatsapp-gateway # Manager Web (opcional, puede servir con nginx) pm2 start "cd manager && npm run build && serve -s dist -l 3002" --name whatsapp-manager # Guardar configuraciΓ³n pm2 save pm2 startup ``` ### 4. Configurar Firewall ```bash # Solo puertos necesarios sudo ufw allow 22 # SSH sudo ufw allow 80 # HTTP sudo ufw allow 443 # HTTPS sudo ufw enable ``` ## πŸ”„ IntegraciΓ³n con n8n ### Webhook Configuration ```json { "method": "POST", "path": "/webhook", "webhookId": "whatsapp-events", "responseMode": "onReceived" } ``` ### n8n Node Example ```javascript // Enviar mensaje desde n8n const response = await fetch('http://localhost:3001/api/send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jid: $input.first().json.phone + '@s.whatsapp.net', content: $input.first().json.message, type: 'text' }) }); ``` ## πŸ› οΈ Troubleshooting ### Problemas Comunes 1. **QR no aparece** - Verificar conexiΓ³n WebSocket - Revisar logs del Gateway 2. **ConexiΓ³n se cae** - Checar persistencia de sesiΓ³n - Verificar archivo de credenciales 3. **Mensajes no se envΓ­an** - Validar formato JID - Verificar estado de conexiΓ³n ### Debug Mode ```bash # Habilitar logs detallados LOG_LEVEL=debug npm run dev ``` ## πŸ“ Licencia Este proyecto es para uso personal y educativo.