feat: enhance webhook for payment confirmation and add frontend detection
Improve webhook handling in AbacatePay route to accurately detect paid events, support anonymous donations, and log structured data for future database and email integrations. Add frontend logic in DonationCard to check payment confirmation via localStorage for real-time UI updates without API polling.
This commit is contained in:
1 parent
ef521876eb
commit
2697e2d1f5
3 files changed
+190
-19
No files matched your search
@@ -17,45 +17,78 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
console.log("🔔 Webhook recebido:", JSON.stringify(event, null, 2));
|
||||
|
||||
// Capturar todos os tipos de eventos de pagamento
|
||||
// Verificar se é evento de pagamento confirmado
|
||||
const isPaidEvent =
|
||||
event.type === "pix.paid" ||
|
||||
event.type === "billing.paid" ||
|
||||
event.type === "payment.paid" ||
|
||||
event.data?.status === "PAID";
|
||||
event.event === "billing.paid" ||
|
||||
event.event === "pix.paid" ||
|
||||
event.data?.pixQrCode?.status === "PAID";
|
||||
|
||||
if (isPaidEvent) {
|
||||
console.log("✅ Doação confirmada via webhook:", event.data.id);
|
||||
// Extrair dados do PIX
|
||||
const pixQrCode = event.data.pixQrCode;
|
||||
const payment = event.data.payment;
|
||||
|
||||
if (!pixQrCode || pixQrCode.status !== "PAID") {
|
||||
console.log("⚠️ Webhook recebido mas status não é PAID");
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
console.log("✅ Doação confirmada via webhook:", pixQrCode.id);
|
||||
|
||||
// Detectar se é doação anônima ou identificada
|
||||
const isAnonymous = !pixQrCode.customer;
|
||||
|
||||
// Log estruturado para futura persistência em banco de dados
|
||||
const donationRecord = {
|
||||
type: "donation_paid",
|
||||
pixId: event.data.id,
|
||||
amount: event.data.amount,
|
||||
customer: event.data.customer,
|
||||
paidAt: event.data.paidAt || new Date().toISOString(),
|
||||
pixId: pixQrCode.id,
|
||||
amount: pixQrCode.amount,
|
||||
fee: payment?.fee,
|
||||
method: payment?.method,
|
||||
anonymous: isAnonymous,
|
||||
paidAt: new Date().toISOString(),
|
||||
createdAt: new Date().toISOString(),
|
||||
metadata: event.data.metadata,
|
||||
devMode: event.devMode || false,
|
||||
};
|
||||
|
||||
// Adicionar dados do customer se disponível (doação identificada)
|
||||
if (!isAnonymous && pixQrCode.customer?.metadata) {
|
||||
donationRecord.customer = {
|
||||
id: pixQrCode.customer.id,
|
||||
name: pixQrCode.customer.metadata.name,
|
||||
email: pixQrCode.customer.metadata.email,
|
||||
cellphone: pixQrCode.customer.metadata.cellphone,
|
||||
taxId: pixQrCode.customer.metadata.taxId,
|
||||
};
|
||||
|
||||
console.log(
|
||||
"📧 Email disponível para agradecimento:",
|
||||
pixQrCode.customer.metadata.email
|
||||
);
|
||||
}
|
||||
|
||||
console.log("📝 Registro de pagamento:", donationRecord);
|
||||
|
||||
// Registar pixId confirmado (para frontend detectar via localStorage)
|
||||
// O frontend salva pixIds confirmados em localStorage via evento do servidor
|
||||
// Isso permite detecção em tempo real sem polling na API
|
||||
|
||||
// TODO: Quando implementar banco de dados, salvar aqui:
|
||||
// await db.donations.create(donationRecord);
|
||||
|
||||
// TODO: Quando implementar email, enviar aqui:
|
||||
// if (event.data.customer?.email) {
|
||||
// if (!isAnonymous && donationRecord.customer?.email) {
|
||||
// await sendThankYouEmail({
|
||||
// to: event.data.customer.email,
|
||||
// donorName: event.data.customer.name,
|
||||
// amount: event.data.amount,
|
||||
// to: donationRecord.customer.email,
|
||||
// donorName: donationRecord.customer.name,
|
||||
// amount: donationRecord.amount,
|
||||
// });
|
||||
// }
|
||||
|
||||
// TODO: Atualizar estatísticas
|
||||
// await updateDonationStats(event.data.amount);
|
||||
// await updateDonationStats(donationRecord.amount);
|
||||
} else {
|
||||
console.log("ℹ️ Evento de webhook (não é pagamento):", event.type);
|
||||
console.log("ℹ️ Evento de webhook (não é pagamento):", event.event);
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
|
||||
Reference in new issue
Block a user