Files
agenciapsilmno/docs/whatsapp.md

244 lines
5.9 KiB
Markdown

# 📱 Disparando WhatsApp Local — AgênciaPsi
Guia completo para rodar o sistema de lembretes por WhatsApp no ambiente local de desenvolvimento.
---
## 🧱 O que você precisa ter rodando
| Serviço | Como subir | Porta |
|---|---|---|
| Supabase local | `npx supabase start` | 54321 |
| Evolution API | Docker Desktop | 8080 |
---
## 🚀 Passo 1 — Subir o Supabase local
Abre o PowerShell na pasta do projeto e roda:
```powershell
cd D:\leonohama\AgenciaPsi.com.br\Sistema\agenciapsi-primesakai
npx supabase start
```
Aguarda aparecer as URLs e credenciais. Confirma que está rodando acessando:
```
http://127.0.0.1:54323
```
---
## 🐳 Passo 2 — Subir a Evolution API
Abre o Docker Desktop e confirma que está com o status **Engine running**.
Abre outro PowerShell e roda:
```powershell
cd D:\leonohama\AgenciaPsi.com.br\Sistema\agenciapsi-primesakai\evolution-api
docker compose up -d
```
Confirma que está rodando acessando:
```
http://localhost:8080
```
Deve retornar:
```json
{"status":200,"message":"Welcome to the Evolution API, it is working!"}
```
---
## 📱 Passo 3 — Conectar o WhatsApp
Acessa o painel da Evolution API:
```
http://localhost:8080/manager
```
- Loga com a API key: `minha_chave_123`
- Verifica se a instância `agenciapsi-teste` está com status **Connected**
- Se estiver **Disconnected**, clica na instância → **Get QR Code** → escaneia com o celular
**Para escanear no celular:**
WhatsApp → ⋮ (três pontinhos) → Aparelhos conectados → Conectar um aparelho
---
## ⚡ Passo 4 — Subir a Edge Function
Abre outro PowerShell e roda:
```powershell
cd D:\leonohama\AgenciaPsi.com.br\Sistema\agenciapsi-primesakai
npx supabase functions serve process-notification-queue --no-verify-jwt
```
Aguarda aparecer:
```
- http://127.0.0.1:54321/functions/v1/process-notification-queue
```
---
## 🗄️ Passo 5 — Popular a fila manualmente
Acessa o Supabase Studio em `http://127.0.0.1:54323`, vai em **SQL Editor** e roda:
```sql
-- Popula a fila com sessões das próximas 48h
select populate_notification_queue();
-- Verifica o que foi gerado
select id, status, scheduled_at, channel, recipient_address, resolved_vars
from notification_queue
order by created_at desc
limit 10;
```
Se precisar corrigir o número do destinatário:
```sql
update notification_queue
set recipient_address = '5516999999999' -- coloca o número real aqui
where status = 'pendente';
```
Se precisar reenviar um item que falhou:
```sql
update notification_queue
set status = 'pendente'
where id = 'cole-o-uuid-aqui';
```
---
## 📤 Passo 6 — Disparar a fila
Abre outro PowerShell e roda:
```powershell
Invoke-WebRequest `
-Uri "http://127.0.0.1:54321/functions/v1/process-notification-queue" `
-Method POST `
-Headers @{"Authorization"="Bearer sb_secret_N7UND0UgjKTVK-Uodkm0Hg_xSvEMPvz"} `
-TimeoutSec 30 `
| Select-Object -ExpandProperty Content
```
**Resposta esperada:**
```json
{"processados":[{"id":"...","status":"enviado"}]}
```
---
## 🔄 Passo 7 — Simular o cron (disparo automático a cada 5 min)
Para simular o `pg_cron` localmente, cria um arquivo `cron-local.ps1` na raiz do projeto:
```powershell
while ($true) {
Write-Host "$(Get-Date) - Populando fila..."
Invoke-WebRequest `
-Uri "http://127.0.0.1:54321/functions/v1/process-notification-queue" `
-Method POST `
-Headers @{"Authorization"="Bearer sb_secret_N7UND0UgjKTVK-Uodkm0Hg_xSvEMPvz"} `
-TimeoutSec 30 `
| Select-Object -ExpandProperty Content
Write-Host "$(Get-Date) - Aguardando 5 minutos..."
Start-Sleep -Seconds 300
}
```
Roda com:
```powershell
cd D:\leonohama\AgenciaPsi.com.br\Sistema\agenciapsi-primesakai
.\cron-local.ps1
```
---
## ✅ Passo 8 — Verificar logs
No Supabase Studio, roda:
```sql
-- Ver histórico de envios
select id, status, channel, recipient_address, sent_at, failure_reason
from notification_logs
order by created_at desc
limit 10;
-- Ver status da fila
select status, count(*)
from notification_queue
group by status;
```
---
## 🧪 Teste rápido de envio direto (sem fila)
Para testar se o WhatsApp está funcionando sem passar pela fila:
```powershell
$body = '{"number":"5516999999999","text":"Teste direto AgênciaPsi!"}'
$headers = @{"apikey"="minha_chave_123"; "Content-Type"="application/json"}
Invoke-WebRequest `
-Uri "http://localhost:8080/message/sendText/agenciapsi-teste" `
-Method POST `
-Headers $headers `
-Body $body `
-TimeoutSec 30 `
| Select-Object -ExpandProperty Content
```
---
## ⚠️ Problemas comuns
| Problema | Causa | Solução |
|---|---|---|
| `Function not found` | Terminal na pasta errada | `cd` para a raiz do projeto antes de rodar o `functions serve` |
| `{"count":0}` no QR Code | Bug da versão | Usar imagem `evoapicloud/evolution-api:latest` |
| `Nenhum item na fila` | Item já processado ou com status diferente | Resetar com `update notification_queue set status = 'pendente'` |
| Timeout no envio | Redis não está rodando | Verificar se o container `evolution-redis` está up no Docker |
| `undefined/message/sendText/undefined` | Campos errados nas credenciais | Verificar se `credentials` tem `api_url` e `instance_name` |
---
## 📋 Resumo das credenciais locais
```
Supabase URL: http://127.0.0.1:54321
Supabase Studio: http://127.0.0.1:54323
Supabase Secret Key: sb_secret_N7UND0UgjKTVK-Uodkm0Hg_xSvEMPvz
Evolution API URL: http://localhost:8080
Evolution API Key: minha_chave_123
Instância WhatsApp: agenciapsi-teste
```
---
## 🚀 Quando for para produção
1. Subir a Evolution API em um VPS (Hostinger, Contabo ~R$30/mês)
2. Atualizar `api_url` em `notification_channels` para a URL do VPS
3. Configurar o `pg_cron` no Supabase cloud:
```sql
select cron.schedule(
'populate-notification-queue',
'*/5 * * * *',
$$ select populate_notification_queue(); $$
);
```
4. Configurar o disparo da Edge Function via `pg_net` ou webhook externo
5. Migrar para API Oficial da Meta quando tiver volume de clientes