366 lines
7.2 KiB
Markdown
366 lines
7.2 KiB
Markdown
# 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 <tu-repo> 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. |