From 490ac533ac41dc372c98e420f2c59510cc511f9b Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Mon, 19 May 2025 13:30:19 +0000 Subject: [PATCH] feat: Implement WhatsApp QR code flow - Store instanceId and instanceName after instance creation. - Add "Ver QR Code" button to fetch and display QR code from API. - Implement QR code refresh functionality. - Display success/error messages. --- src/pages/WhatsApp.tsx | 248 ++++++++++++++++++++++++++++++++--------- 1 file changed, 195 insertions(+), 53 deletions(-) diff --git a/src/pages/WhatsApp.tsx b/src/pages/WhatsApp.tsx index 64495f1..802d324 100644 --- a/src/pages/WhatsApp.tsx +++ b/src/pages/WhatsApp.tsx @@ -6,7 +6,8 @@ import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; import { useToast } from '@/hooks/use-toast'; import { Label } from '@/components/ui/label'; -import { MessageCircle } from 'lucide-react'; +import { MessageCircle, QrCode, RefreshCw } from 'lucide-react'; +import { Alert, AlertDescription } from '@/components/ui/alert'; interface WhatsAppInstance { instanceName: string; @@ -18,13 +19,28 @@ interface WhatsAppInstance { const WhatsApp = () => { const { toast } = useToast(); const [loading, setLoading] = useState(false); + const [loadingQR, setLoadingQR] = useState(false); const [instanceName, setInstanceName] = useState(() => { // Get user's name from localStorage as default value const userName = localStorage.getItem('userName') || ''; return userName; }); const [phoneNumber, setPhoneNumber] = useState(''); - const [instance, setInstance] = useState(null); + const [instance, setInstance] = useState(() => { + // Check if we have a stored instance + const storedInstanceId = localStorage.getItem('whatsappInstanceId'); + const storedInstanceName = localStorage.getItem('whatsappInstanceName'); + + if (storedInstanceId && storedInstanceName) { + return { + instanceName: storedInstanceName, + instanceId: storedInstanceId + }; + } + return null; + }); + const [qrCodeData, setQrCodeData] = useState(null); + const [qrError, setQrError] = useState(null); const createInstance = async () => { // Validate form fields @@ -74,20 +90,28 @@ const WhatsApp = () => { } // Handle successful response - setInstance({ + const newInstance = { instanceName, instanceId: data.instanceId, status: data.status, qrcode: data.qrcode - }); + }; + + setInstance(newInstance); - // Save the instance ID for later use + // Save the instance details for later use localStorage.setItem('whatsappInstanceId', data.instanceId); + localStorage.setItem('whatsappInstanceName', instanceName); toast({ title: "Sucesso!", description: "Instância do WhatsApp criada com sucesso!" }); + + // If there's a QR code in the response, set it + if (data.qrcode) { + setQrCodeData(data.qrcode); + } } catch (error) { console.error("Error creating WhatsApp instance:", error); toast({ @@ -95,11 +119,61 @@ const WhatsApp = () => { description: "Ocorreu um erro ao conectar com a API. Tente novamente mais tarde.", variant: "destructive", }); + setQrError("Falha ao obter QR Code. Tente novamente."); } finally { setLoading(false); } }; + const fetchQrCode = async () => { + if (!instance?.instanceId) { + toast({ + title: "Erro", + description: "Nenhuma instância disponível. Crie uma instância primeiro.", + variant: "destructive", + }); + return; + } + + setLoadingQR(true); + setQrError(null); + + try { + const serverUrl = "evolutionapi2.innova1001.com.br"; + const apiKey = "beeb77fbd7f48f91db2cd539a573c130"; + + const response = await fetch(`https://${serverUrl}/instance/qrcode/${instance.instanceId}`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + 'apikey': apiKey + } + }); + + const data = await response.json(); + + if (!response.ok) { + throw new Error(data.message || 'Erro ao obter QR Code'); + } + + if (data && data.qrcode) { + setQrCodeData(data.qrcode); + } else { + setQrError("QR Code não disponível. A instância pode já estar conectada."); + } + } catch (error) { + console.error("Error fetching QR code:", error); + setQrError("Falha ao obter QR Code. Tente novamente."); + toast({ + title: "Erro ao obter QR Code", + description: "Não foi possível obter o QR Code. Tente novamente mais tarde.", + variant: "destructive", + }); + } finally { + setLoadingQR(false); + } + }; + return (
@@ -107,57 +181,125 @@ const WhatsApp = () => {

Conectar WhatsApp

- - -
- - Vincular WhatsApp ao App -
- - Preencha os campos abaixo para conectar sua conta WhatsApp - -
- -
- - setInstanceName(e.target.value)} - placeholder="Digite um nome para a instância" - required - /> -

O nome será usado para identificar esta conexão

-
- -
- - setPhoneNumber(e.target.value)} - placeholder="559999999999" - required - /> -

Digite o número com DDD e código do país

-
- - - - {instance && instance.instanceId && ( -
+ {!instance?.instanceId ? ( + + +
+ + Vincular WhatsApp ao App +
+ + Preencha os campos abaixo para conectar sua conta WhatsApp + +
+ +
+ + setInstanceName(e.target.value)} + placeholder="Digite um nome para a instância" + required + /> +

O nome será usado para identificar esta conexão

+
+ +
+ + setPhoneNumber(e.target.value)} + placeholder="559999999999" + required + /> +

Digite o número com DDD e código do país

+
+ + +
+
+ ) : ( + + +
+ + WhatsApp - {instance.instanceName} +
+ + Escaneie o QR Code com seu WhatsApp para finalizar a conexão + +
+ +

Instância criada com sucesso!

ID da instância: {instance.instanceId}

- )} -
-
+ + {!qrCodeData && !qrError && !loadingQR && ( + + )} + + {loadingQR && ( +
+

Carregando QR Code...

+
+ )} + + {qrCodeData && ( +
+
+ QR Code WhatsApp +
+

+ Escaneie este QR Code com seu WhatsApp para finalizar a conexão. +

+ +
+ )} + + {qrError && ( +
+ + {qrError} + + +
+ )} + + + )}
);