# 🔧 Correção: Webhook OpenPIX Retornando 404

## 🐛 Problema Identificado

O webhook do OpenPIX está retornando erro **404 Not Found**.

### URL Configurada no OpenPIX:
```
https://gestor.jf.eng.br/api/webhooks/openpix?authorization=...
```

### Causa Raiz:

1. **Rota não encontrada**: A rota estava apenas em `/api/v1/webhooks/openpix`
2. **Query parameter errado**: A autorização não deve ir na URL, mas no **header**

## ✅ Correções Aplicadas

### 1. Adicionada Rota Legada (SEM v1)

**Arquivo**: `backend/routes/api.php`

**Antes**: Rota apenas em `/api/v1/webhooks/openpix`

**Depois**: Rota também em `/api/webhooks/openpix` (legado)

```php
// LEGACY: Webhooks sem prefixo v1
Route::prefix('webhooks')->group(function () {
    // OpenPIX webhook (legado sem v1)
    Route::post('openpix', [\App\Http\Controllers\Api\WebhookController::class, 'handleOpenPix']);
});
```

Agora ambas as rotas funcionam:
- ✅ `/api/v1/webhooks/openpix` (nova)
- ✅ `/api/webhooks/openpix` (legado - compatível com config atual)

## 🔧 Como Corrigir no Servidor

### Opção 1: Atualizar Código (Recomendado)

```bash
cd /var/www/gestorstream

# Backup
cp backend/routes/api.php backend/routes/api.php.backup

# Atualizar código
git pull origin main

# Limpar cache de rotas
cd backend
php artisan route:clear
php artisan config:clear
php artisan cache:clear

# Verificar se rota foi adicionada
php artisan route:list | grep webhooks
```

### Opção 2: Editar Manualmente

```bash
nano backend/routes/api.php
```

Adicione antes da linha final:

```php
// LEGACY: Webhooks sem prefixo v1
Route::prefix('webhooks')->group(function () {
    Route::post('openpix', [\App\Http\Controllers\Api\WebhookController::class, 'handleOpenPix']);
});
```

Salvar e limpar cache:

```bash
cd backend
php artisan route:clear
```

## 📋 Verificar Rota

```bash
cd /var/www/gestorstream/backend
php artisan route:list | grep webhooks
```

**Saída esperada**:
```
POST   api/webhooks/openpix ........... handleOpenPix
POST   api/v1/webhooks/openpix ........ handleOpenPix
```

## 🧪 Testar Webhook

### 1. Testar Localmente

```bash
curl -X POST http://localhost:8000/api/webhooks/openpix \
  -H "Content-Type: application/json" \
  -H "Authorization: SEU_TOKEN_AQUI" \
  -d '{
    "event": "OPENPIX:CHARGE_COMPLETED",
    "charge": {
      "correlationID": "test123",
      "transactionID": "test456",
      "status": "COMPLETED"
    }
  }'
```

### 2. Testar no Servidor

```bash
curl -X POST https://gestor.jf.eng.br/api/webhooks/openpix \
  -H "Content-Type: application/json" \
  -H "Authorization: SEU_TOKEN_AQUI" \
  -d '{
    "event": "OPENPIX:CHARGE_COMPLETED",
    "charge": {
      "correlationID": "test123",
      "transactionID": "test456",
      "status": "COMPLETED"
    }
  }'
```

**Resposta esperada**: `{"status":"ok"}` (HTTP 200)

## ⚠️ Configuração Correta no OpenPIX

### URL do Webhook

**❌ ERRADO** (com query parameter):
```
https://gestor.jf.eng.br/api/webhooks/openpix?authorization=CosalSqzsmt...
```

**✅ CORRETO** (sem query parameter):
```
https://gestor.jf.eng.br/api/webhooks/openpix
```

### Headers

Configure no painel do OpenPIX:

```
Authorization: CosalSqzsmtGVxh9DhD5hVNwwmpKC2QTaEX99N4Vv9rSlEv4LhUoC
```

Ou se o OpenPIX suportar HMAC:

```
x-webhook-signature: [assinatura HMAC-SHA256]
```

## 📊 Fluxo Correto

```
OpenPIX detecta pagamento
    ↓
POST /api/webhooks/openpix
    Header: Authorization: TOKEN
    Body: {event: "OPENPIX:CHARGE_COMPLETED", ...}
    ↓
WebhookController::handleOpenPix()
    ↓
Valida Authorization header
    ↓
Processa pagamento
    ↓
Ativa subscription
    ↓
Retorna {"status":"ok"} (200)
```

## 🔍 Debug de Webhooks

### Ver Logs

```bash
tail -f /var/www/gestorstream/backend/storage/logs/laravel.log | grep "OpenPIX Webhook"
```

### Verificar Webhooks Recebidos

```bash
grep "OpenPIX Webhook" /var/www/gestorstream/backend/storage/logs/laravel.log | tail -20
```

### Ver Último Erro

```bash
tail -100 /var/www/gestorstream/backend/storage/logs/laravel.log | grep "404\|OpenPIX"
```

## ✅ Checklist de Verificação

- [ ] Código atualizado (git pull)
- [ ] Cache de rotas limpo (`php artisan route:clear`)
- [ ] Rota aparece em `php artisan route:list`
- [ ] URL no OpenPIX está **SEM** query parameter
- [ ] Token de autorização configurado no **header**
- [ ] Teste com curl retorna 200
- [ ] Logs mostram webhook sendo recebido

## 🎯 Resultado Esperado

Após a correção:

```
12-01-2026 20:30    200    ✓    https://gestor.jf.eng.br/api/webhooks/openpix
```

**Status**: ✅ Webhook recebido e processado com sucesso!

---

**Data**: 2026-01-12  
**Tipo**: Correção de Rota (404)  
**Prioridade**: Alta (bloqueava webhooks)
