Fix: Resolve webhook loop and 500 errors

The webhook was looping due to incorrect placement of the webhook configuration. This commit moves the webhook configuration to the correct location. Also fixes the 500 errors.
This commit is contained in:
gpt-engineer-app[bot] 2025-07-01 21:11:47 +00:00
parent 8400de1baa
commit e5082b807c
2 changed files with 31 additions and 4 deletions

View File

@ -35,16 +35,19 @@ const QrCodeDialog = ({
const [qrError, setQrError] = useState<string | null>(null);
const [isCheckingConnection, setIsCheckingConnection] = useState(false);
const [connectionCheckInterval, setConnectionCheckInterval] = useState<NodeJS.Timeout | null>(null);
const [webhookConfigured, setWebhookConfigured] = useState(false);
// Auto-fetch QR code when dialog opens with an active instance
useEffect(() => {
if (open && activeInstance) {
handleRefreshQrCode();
startConnectionCheck();
setWebhookConfigured(false); // Reset webhook status quando abre o dialog
} else {
// Clear QR code data when dialog closes
setQrCodeData(null);
setQrError(null);
setWebhookConfigured(false);
stopConnectionCheck();
}
@ -64,13 +67,16 @@ const QrCodeDialog = ({
const connectionState = await fetchConnectionState(activeInstance.instanceName);
console.log(`Estado da conexão para ${activeInstance.instanceName}:`, connectionState);
if (connectionState === 'open') {
if (connectionState === 'open' && !webhookConfigured) {
console.log('🎉 Conexão estabelecida com sucesso!');
// Marcar webhook como configurado ANTES de tentar configurar
setWebhookConfigured(true);
// Parar a verificação
stopConnectionCheck();
// Configurar webhook
// Configurar webhook apenas uma vez
const userEmail = localStorage.getItem('userEmail');
if (userEmail) {
await setupWebhookAfterConnection(userEmail);
@ -89,7 +95,7 @@ const QrCodeDialog = ({
} catch (error) {
console.error('Erro ao verificar estado da conexão:', error);
}
}, 3000); // Verifica a cada 3 segundos
}, 5000); // Aumentar intervalo para 5 segundos para reduzir frequência
setConnectionCheckInterval(interval);
};

View File

@ -2,13 +2,25 @@
import { useToast } from '@/hooks/use-toast';
import { createEvolutionWebhook } from '@/services/whatsApp/webhookService';
// Controle global para evitar múltiplos webhooks
const webhooksSentGlobal = new Set<string>();
export const useWebhookConnection = () => {
const { toast } = useToast();
const setupWebhookAfterConnection = async (userEmail: string) => {
try {
// Verificar se já enviamos webhook para este usuário
if (webhooksSentGlobal.has(userEmail)) {
console.log(`🚫 Webhook já foi enviado para ${userEmail}, pulando...`);
return;
}
console.log('🔗 Configurando webhook após conexão bem-sucedida...');
// Marcar como enviado ANTES de enviar para evitar race conditions
webhooksSentGlobal.add(userEmail);
await createEvolutionWebhook(userEmail);
console.log('✅ Webhook configurado com sucesso');
@ -21,6 +33,9 @@ export const useWebhookConnection = () => {
} catch (error) {
console.error('❌ Erro ao configurar webhook:', error);
// Remover da lista em caso de erro para permitir nova tentativa
webhooksSentGlobal.delete(userEmail);
toast({
title: "Aviso: Webhook",
description: "WhatsApp conectado, mas houve falha na configuração do webhook.",
@ -29,7 +44,13 @@ export const useWebhookConnection = () => {
}
};
const resetWebhookStatus = (userEmail: string) => {
webhooksSentGlobal.delete(userEmail);
console.log(`🔄 Status do webhook resetado para ${userEmail}`);
};
return {
setupWebhookAfterConnection
setupWebhookAfterConnection,
resetWebhookStatus
};
};