# 🧪 Instruções para Testar o Webhook OpenPIX

## 📋 Passo a Passo no Servidor

### 1. Fazer Upload dos Arquivos de Teste

Copie estes arquivos para o servidor `/var/www/gestorstream`:
- `test_webhook.php`
- `test_webhook.sh`
- `check_webhook_config.php`

### 2. Verificar Configuração

```bash
cd /var/www/gestorstream
php check_webhook_config.php
```

**O que este comando faz:**
- ✅ Verifica se as rotas de webhook existem
- ✅ Verifica configurações do OpenPIX no banco e config
- ✅ Verifica variáveis do .env
- ✅ Testa se o WebhookController pode ser instanciado
- ✅ Mostra últimas linhas dos logs relacionadas ao webhook

**Resultado esperado:**
```
✅ Sistema está configurado para receber webhooks
URL do Webhook: https://gestor.jf.eng.br/api/webhooks/openpix
```

### 3. Atualizar o Código no Servidor

```bash
cd /var/www/gestorstream

# Backup
cp backend/app/Http/Controllers/Api/WebhookController.php backend/app/Http/Controllers/Api/WebhookController.php.backup.$(date +%Y%m%d_%H%M%S)

# Atualizar
git pull origin main

# Limpar cache
cd backend
php artisan config:clear
php artisan cache:clear
php artisan route:clear
php artisan route:list | grep webhook
```

**Resultado esperado:**
```
POST   api/webhooks/openpix ........... handleOpenPix
POST   api/v1/webhooks/openpix ........ handleOpenPix
```

### 4. Executar Teste do Webhook

```bash
cd /var/www/gestorstream
chmod +x test_webhook.sh
./test_webhook.sh
```

**OU**

```bash
cd /var/www/gestorstream
php test_webhook.php
```

**O que este script faz:**
- 🧪 Teste 1: Webhook SEM headers de autenticação
- 🧪 Teste 2: Webhook COM header Authorization
- 🧪 Teste 3: Webhook COM HMAC Signature

**Resultado esperado:**
```
1. Testando webhook SEM headers de autenticação...
   Status HTTP: 200
   Response Body: {"status":"ok"}
   ✅ SUCESSO! Webhook retornou 200 OK
   ✅ Webhook processou com sucesso!

========================================
✅ TESTE COMPLETO: WEBHOOK FUNCIONANDO!
========================================
```

### 5. Ver Logs em Tempo Real (Opcional)

Em outro terminal SSH, monitore os logs:

```bash
tail -f /var/www/gestorstream/backend/storage/logs/laravel.log
```

## 🔧 Configuração no Painel OpenPIX

Após o teste passar com status 200, configure no painel do OpenPIX:

### Opção 1: Sem Validação (Mais Simples)

**URL de Webhook:** `https://gestor.jf.eng.br/api/webhooks/openpix`

**Cabeçalhos HTTP:**
- `Content-Type`: `application/json`
- `Accept`: `application/json`

✅ **NÃO configure** `Authorization` nem outros headers customizados

### Opção 2: Com HMAC Signature (Recomendado)

**URL de Webhook:** `https://gestor.jf.eng.br/api/webhooks/openpix`

**Webhook Secret (HMAC):** `openpix_EtpEIRxeT+5yt4MM4E8Ern3/WVoLzuRDtlJx15jHrFc=`

**Cabeçalhos HTTP:**
- `Content-Type`: `application/json`
- `Accept`: `application/json`
- `X-OpenPix-Signature`: `Gerado por requisição` (o OpenPIX gera automaticamente)

✅ O OpenPIX gerará o `X-OpenPix-Signature` automaticamente baseado no secret

### Opção 3: Com Authorization Token

**URL de Webhook:** `https://gestor.jf.eng.br/api/webhooks/openpix`

**Cabeçalhos HTTP:**
- `Content-Type`: `application/json`
- `Accept`: `application/json`
- `Authorization`: `CosalSqzsmtGVxh9DhD5hVNwwmpKC2QTaEX99N4Vv9rSlEv4LhUoC`

⚠️ **ATENÇÃO**: Só use esta opção se o painel do OpenPIX permitir configurar headers customizados

## 🐛 Solução de Problemas

### Erro: Status 401 Unauthorized

**Causa:** O sistema está tentando validar autorização mas o token não confere

**Solução:**
```bash
# 1. Verificar se há token configurado
cd /var/www/gestorstream/backend
grep OPENPIX_WEBHOOK_AUTHORIZATION .env

# 2. Se estiver configurado, remover ou corrigir
nano .env
# Comentar ou remover: #OPENPIX_WEBHOOK_AUTHORIZATION=...

# 3. Limpar cache
php artisan config:clear

# 4. Testar novamente
cd ..
php test_webhook.php
```

### Erro: Status 404 Not Found

**Causa:** A rota não está registrada

**Solução:**
```bash
# 1. Verificar rotas
cd /var/www/gestorstream/backend
php artisan route:list | grep webhook

# 2. Se não aparecer nada, verificar routes/api.php
cat routes/api.php | grep openpix

# 3. Limpar cache de rotas
php artisan route:clear

# 4. Recarregar rotas
php artisan route:cache
```

### Erro: Status 500 Internal Server Error

**Causa:** Erro no código PHP

**Solução:**
```bash
# 1. Ver o erro exato nos logs
cd /var/www/gestorstream/backend
tail -100 storage/logs/laravel.log | grep ERROR

# 2. Verificar permissões
ls -la storage/logs/

# 3. Se necessário, dar permissão
chmod -R 775 storage/
chown -R www-data:www-data storage/
```

### Erro: cURL Error

**Causa:** Problema de conexão SSL ou DNS

**Solução:**
```bash
# 1. Testar SSL
curl -v https://gestor.jf.eng.br/api/webhooks/openpix

# 2. Se falhar SSL, testar HTTP (temporário)
curl -v http://gestor.jf.eng.br/api/webhooks/openpix

# 3. Verificar certificado
openssl s_client -connect gestor.jf.eng.br:443 -servername gestor.jf.eng.br
```

## ✅ Checklist Final

Antes de registrar o webhook no OpenPIX, certifique-se:

- [ ] `php check_webhook_config.php` retorna ✅
- [ ] `php test_webhook.php` retorna status 200
- [ ] Logs mostram "OpenPIX Webhook recebido"
- [ ] Código atualizado com `git pull`
- [ ] Cache limpo (`php artisan config:clear`)
- [ ] Rotas aparecem em `php artisan route:list`

## 📊 Exemplo de Log Correto

Quando o webhook funcionar, você verá nos logs:

```log
[2026-01-12 21:30:00] OpenPIX Webhook: Processando sem validação de autorização
  has_auth_token_config: false
  has_authorization_header: false
  ip: 177.71.190.123

[2026-01-12 21:30:00] OpenPIX Webhook: Processando sem validação de assinatura HMAC
  has_secret_config: false
  has_signature_header: false

[2026-01-12 21:30:00] OpenPIX Webhook recebido
  has_signature: false
  has_authorization: false

[2026-01-12 21:30:01] OpenPIX Webhook processado com sucesso
  payment_id: 123
  status: approved
```

## 🎯 Teste Final no Painel OpenPIX

Após registrar o webhook:

1. **Criar cobrança de teste** no painel do OpenPIX
2. **Simular pagamento** (modo teste)
3. **Verificar nos logs** se o webhook foi recebido:
   ```bash
   tail -f /var/www/gestorstream/backend/storage/logs/laravel.log
   ```
4. **Verificar no banco** se a subscription foi ativada:
   ```bash
   cd /var/www/gestorstream/backend
   php artisan tinker
   >>> \App\Models\Payment::latest()->first();
   >>> \App\Models\Subscription::latest()->first();
   ```

---

**Data:** 2026-01-12  
**Objetivo:** Garantir que o webhook retorne status 200 para ser aceito pelo OpenPIX
