# Troubleshooting

### Common Issues

#### 1. Webhook Verification Fails

**Problem:** GET webhook returns 403

**Solution:**
```typescript
// Ensure verify token matches
const whatsapp = createWhatsAppHandler({
  webhookVerifyToken: 'same_token_in_meta_dashboard'
});
```

---

#### 2. Signature Verification Fails

**Problem:** POST webhook returns 401

**Solution:**
```typescript
// Add app secret and enable verification
const whatsapp = createWhatsAppHandler({
  appSecret: 'your_app_secret',
  webhook: {
    verifySignature: true,
    appSecret: 'your_app_secret'
  }
});
```

---

#### 3. Messages Not Sending

**Problem:** Messages fail silently

**Solution:**
```typescript
// Listen for errors
whatsapp.on('messageFailed', (data) => {
  console.error('Failed:', data.error);
});

// Check API credentials
console.log('Token:', process.env.WHATSAPP_TOKEN);
console.log('Phone ID:', process.env.WHATSAPP_PHONE_NUMBER_ID);
```

---

#### 4. Webhook Not Receiving Events

**Problem:** No events received

**Checklist:**
- ✅ Webhook URL is publicly accessible
- ✅ SSL certificate is valid
- ✅ Webhook is subscribed in Meta dashboard
- ✅ Verify token matches
- ✅ Server is running and reachable

**Test webhook:**
```bash
# Test GET (verification)
curl "http://your-domain.com/webhook?hub.mode=subscribe&hub.verify_token=YOUR_TOKEN&hub.challenge=test"

# Test POST (message)
curl -X POST http://your-domain.com/webhook \
  -H "Content-Type: application/json" \
  -d '{"object":"whatsapp_business_account","entry":[]}'
```

---

#### 5. Rate Limiting

**Problem:** 429 Too Many Requests

**Solution:**
```typescript
// Enable queue to handle rate limits
const whatsapp = createWhatsAppHandler({
  queueEnabled: true,
  maxQueueSize: 1000,
  maxRetries: 3
});

// Send with queue
await whatsapp.sendMessage(to, message, { queueIfBusy: true });
```

---

### Debug Mode

```typescript
// Enable verbose logging
whatsapp.on('messageSent', console.log);
whatsapp.on('messageFailed', console.error);
whatsapp.on('messageRead', console.log);

// Log all webhook events
whatsapp.setWebhookHandlers({
  onMessage: (msg, meta) => console.log('Message:', msg, meta),
  onMessageStatus: (status) => console.log('Status:', status),
  onError: (error) => console.error('Error:', error),
  onUnknown: (event) => console.log('Unknown:', event)
});
```

---