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.
This commit is contained in:
parent
70dd4fc790
commit
490ac533ac
@ -6,7 +6,8 @@ import { Input } from '@/components/ui/input';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { useToast } from '@/hooks/use-toast';
|
import { useToast } from '@/hooks/use-toast';
|
||||||
import { Label } from '@/components/ui/label';
|
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 {
|
interface WhatsAppInstance {
|
||||||
instanceName: string;
|
instanceName: string;
|
||||||
@ -18,13 +19,28 @@ interface WhatsAppInstance {
|
|||||||
const WhatsApp = () => {
|
const WhatsApp = () => {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [loadingQR, setLoadingQR] = useState(false);
|
||||||
const [instanceName, setInstanceName] = useState(() => {
|
const [instanceName, setInstanceName] = useState(() => {
|
||||||
// Get user's name from localStorage as default value
|
// Get user's name from localStorage as default value
|
||||||
const userName = localStorage.getItem('userName') || '';
|
const userName = localStorage.getItem('userName') || '';
|
||||||
return userName;
|
return userName;
|
||||||
});
|
});
|
||||||
const [phoneNumber, setPhoneNumber] = useState('');
|
const [phoneNumber, setPhoneNumber] = useState('');
|
||||||
const [instance, setInstance] = useState<WhatsAppInstance | null>(null);
|
const [instance, setInstance] = useState<WhatsAppInstance | null>(() => {
|
||||||
|
// 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<string | null>(null);
|
||||||
|
const [qrError, setQrError] = useState<string | null>(null);
|
||||||
|
|
||||||
const createInstance = async () => {
|
const createInstance = async () => {
|
||||||
// Validate form fields
|
// Validate form fields
|
||||||
@ -74,20 +90,28 @@ const WhatsApp = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handle successful response
|
// Handle successful response
|
||||||
setInstance({
|
const newInstance = {
|
||||||
instanceName,
|
instanceName,
|
||||||
instanceId: data.instanceId,
|
instanceId: data.instanceId,
|
||||||
status: data.status,
|
status: data.status,
|
||||||
qrcode: data.qrcode
|
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('whatsappInstanceId', data.instanceId);
|
||||||
|
localStorage.setItem('whatsappInstanceName', instanceName);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: "Sucesso!",
|
title: "Sucesso!",
|
||||||
description: "Instância do WhatsApp criada com 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) {
|
} catch (error) {
|
||||||
console.error("Error creating WhatsApp instance:", error);
|
console.error("Error creating WhatsApp instance:", error);
|
||||||
toast({
|
toast({
|
||||||
@ -95,11 +119,61 @@ const WhatsApp = () => {
|
|||||||
description: "Ocorreu um erro ao conectar com a API. Tente novamente mais tarde.",
|
description: "Ocorreu um erro ao conectar com a API. Tente novamente mais tarde.",
|
||||||
variant: "destructive",
|
variant: "destructive",
|
||||||
});
|
});
|
||||||
|
setQrError("Falha ao obter QR Code. Tente novamente.");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
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 (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
@ -107,57 +181,125 @@ const WhatsApp = () => {
|
|||||||
<h1 className="text-2xl font-bold tracking-tight">Conectar WhatsApp</h1>
|
<h1 className="text-2xl font-bold tracking-tight">Conectar WhatsApp</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card className="max-w-md mx-auto">
|
{!instance?.instanceId ? (
|
||||||
<CardHeader>
|
<Card className="max-w-md mx-auto">
|
||||||
<div className="flex items-center mb-2">
|
<CardHeader>
|
||||||
<MessageCircle className="h-6 w-6 mr-2 text-green-600" />
|
<div className="flex items-center mb-2">
|
||||||
<CardTitle>Vincular WhatsApp ao App</CardTitle>
|
<MessageCircle className="h-6 w-6 mr-2 text-green-600" />
|
||||||
</div>
|
<CardTitle>Vincular WhatsApp ao App</CardTitle>
|
||||||
<CardDescription>
|
</div>
|
||||||
Preencha os campos abaixo para conectar sua conta WhatsApp
|
<CardDescription>
|
||||||
</CardDescription>
|
Preencha os campos abaixo para conectar sua conta WhatsApp
|
||||||
</CardHeader>
|
</CardDescription>
|
||||||
<CardContent className="space-y-4">
|
</CardHeader>
|
||||||
<div className="space-y-2">
|
<CardContent className="space-y-4">
|
||||||
<Label htmlFor="instanceName">Nome da Instância</Label>
|
<div className="space-y-2">
|
||||||
<Input
|
<Label htmlFor="instanceName">Nome da Instância</Label>
|
||||||
id="instanceName"
|
<Input
|
||||||
value={instanceName}
|
id="instanceName"
|
||||||
onChange={(e) => setInstanceName(e.target.value)}
|
value={instanceName}
|
||||||
placeholder="Digite um nome para a instância"
|
onChange={(e) => setInstanceName(e.target.value)}
|
||||||
required
|
placeholder="Digite um nome para a instância"
|
||||||
/>
|
required
|
||||||
<p className="text-xs text-muted-foreground">O nome será usado para identificar esta conexão</p>
|
/>
|
||||||
</div>
|
<p className="text-xs text-muted-foreground">O nome será usado para identificar esta conexão</p>
|
||||||
|
</div>
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="phoneNumber">Número do WhatsApp</Label>
|
<div className="space-y-2">
|
||||||
<Input
|
<Label htmlFor="phoneNumber">Número do WhatsApp</Label>
|
||||||
id="phoneNumber"
|
<Input
|
||||||
value={phoneNumber}
|
id="phoneNumber"
|
||||||
onChange={(e) => setPhoneNumber(e.target.value)}
|
value={phoneNumber}
|
||||||
placeholder="559999999999"
|
onChange={(e) => setPhoneNumber(e.target.value)}
|
||||||
required
|
placeholder="559999999999"
|
||||||
/>
|
required
|
||||||
<p className="text-xs text-muted-foreground">Digite o número com DDD e código do país</p>
|
/>
|
||||||
</div>
|
<p className="text-xs text-muted-foreground">Digite o número com DDD e código do país</p>
|
||||||
|
</div>
|
||||||
<Button
|
|
||||||
className="w-full mt-4"
|
<Button
|
||||||
onClick={createInstance}
|
className="w-full mt-4"
|
||||||
disabled={loading}
|
onClick={createInstance}
|
||||||
>
|
disabled={loading}
|
||||||
{loading ? "Criando..." : "Criar Instância"}
|
>
|
||||||
</Button>
|
{loading ? "Criando..." : "Criar Instância"}
|
||||||
|
</Button>
|
||||||
{instance && instance.instanceId && (
|
</CardContent>
|
||||||
<div className="p-3 bg-green-50 text-green-800 rounded-md mt-4 text-sm">
|
</Card>
|
||||||
|
) : (
|
||||||
|
<Card className="max-w-md mx-auto">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center mb-2">
|
||||||
|
<QrCode className="h-6 w-6 mr-2 text-green-600" />
|
||||||
|
<CardTitle>WhatsApp - {instance.instanceName}</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>
|
||||||
|
Escaneie o QR Code com seu WhatsApp para finalizar a conexão
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="p-3 bg-green-50 text-green-800 rounded-md text-sm">
|
||||||
<p><strong>Instância criada com sucesso!</strong></p>
|
<p><strong>Instância criada com sucesso!</strong></p>
|
||||||
<p className="text-xs mt-1">ID da instância: {instance.instanceId}</p>
|
<p className="text-xs mt-1">ID da instância: {instance.instanceId}</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</CardContent>
|
{!qrCodeData && !qrError && !loadingQR && (
|
||||||
</Card>
|
<Button
|
||||||
|
className="w-full"
|
||||||
|
onClick={fetchQrCode}
|
||||||
|
disabled={loadingQR}
|
||||||
|
>
|
||||||
|
Ver QR Code
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loadingQR && (
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<p>Carregando QR Code...</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{qrCodeData && (
|
||||||
|
<div className="flex flex-col items-center space-y-4">
|
||||||
|
<div className="border p-4 bg-white rounded-md">
|
||||||
|
<img
|
||||||
|
src={qrCodeData}
|
||||||
|
alt="QR Code WhatsApp"
|
||||||
|
className="w-full h-auto max-w-[250px]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-center">
|
||||||
|
Escaneie este QR Code com seu WhatsApp para finalizar a conexão.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={fetchQrCode}
|
||||||
|
disabled={loadingQR}
|
||||||
|
className="flex items-center"
|
||||||
|
>
|
||||||
|
<RefreshCw className="w-4 h-4 mr-2" />
|
||||||
|
Atualizar QR Code
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{qrError && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>{qrError}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
<Button
|
||||||
|
onClick={fetchQrCode}
|
||||||
|
disabled={loadingQR}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
Tentar Novamente
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</Layout>
|
</Layout>
|
||||||
);
|
);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user