feat: enhance AbacatePay donation system with updated docs and form fields
Updated ABACATEPAY_SETUP.md with comprehensive setup guide, including environment variables, API key instructions, webhook configuration, donation flow, and field details for better integration clarity. Added required fields (phone, CPF/CNPJ) to the donation form in app/[locale]/apoiar/page.tsx to collect essential donor information and improve compliance. This ensures smoother setup and more robust donation processing.
This commit is contained in:
1 parent
00501e6699
commit
ef521876eb
9 files changed
+922
-168
No files matched your search
@@ -179,6 +179,15 @@ export default async function SupportPage({
|
||||
icon="coffee"
|
||||
badge={t("tiers.coffee.badge")}
|
||||
/>
|
||||
<DonationCard
|
||||
id="snack"
|
||||
amount={10}
|
||||
title="Um Lanche"
|
||||
description="Equivale a ~20 minutos de desenvolvimento"
|
||||
icon="pizza"
|
||||
badge="Popular"
|
||||
highlighted
|
||||
/>
|
||||
<DonationCard
|
||||
id="lunch"
|
||||
amount={25}
|
||||
@@ -186,13 +195,6 @@ export default async function SupportPage({
|
||||
description={t("tiers.lunch.description")}
|
||||
icon="pizza"
|
||||
badge={t("tiers.lunch.badge")}
|
||||
highlighted
|
||||
/>
|
||||
<DonationCard
|
||||
id="custom"
|
||||
title={t("tiers.custom.title")}
|
||||
description={t("tiers.custom.description")}
|
||||
icon="heart"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,49 +1,135 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { abacatePay } from "@/lib/abacatepay";
|
||||
import { DonationData } from "@/types/donation";
|
||||
import { DONATION_PRODUCTS, DonorData } from "@/types/donation";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body: DonationData = await request.json();
|
||||
const body = await request.json();
|
||||
|
||||
// Validação básica
|
||||
if (!body.amount || body.amount < 5 || body.amount > 10000) {
|
||||
// Validar tier
|
||||
const validTiers: Array<keyof typeof DONATION_PRODUCTS> = [
|
||||
"coffee",
|
||||
"snack",
|
||||
"lunch",
|
||||
];
|
||||
if (!body.tier || !validTiers.includes(body.tier)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Valor deve estar entre R$ 5,00 e R$ 10.000,00",
|
||||
},
|
||||
{ success: false, error: "Tier de doação inválido" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const billing = await abacatePay.createDonationBilling({
|
||||
amount: body.amount,
|
||||
donorEmail: body.donorEmail,
|
||||
donorName: body.donorName,
|
||||
message: body.message,
|
||||
});
|
||||
const product =
|
||||
DONATION_PRODUCTS[body.tier as keyof typeof DONATION_PRODUCTS];
|
||||
|
||||
// AbacatePay pode retornar diferentes formatos
|
||||
const pixCode = billing.pixCode || billing.qrCode;
|
||||
const pixQrCode = billing.pixQrCode || billing.qrCode;
|
||||
const paymentUrl = billing.url || billing.paymentUrl;
|
||||
let pixData;
|
||||
|
||||
// Fluxo: Anônimo ou Identificado
|
||||
if (body.anonymous === true) {
|
||||
// Doação anônima - sem customer
|
||||
pixData = await abacatePay.createPixQrCode({
|
||||
amount: product.price,
|
||||
description: product.name,
|
||||
expiresIn: 600,
|
||||
});
|
||||
|
||||
console.log("🔍 PIX criado (anônimo):", pixData);
|
||||
|
||||
console.log("📝 Registro de doação anônima:", {
|
||||
type: "donation_created",
|
||||
pixId: pixData.id,
|
||||
amount: product.price,
|
||||
tier: body.tier,
|
||||
anonymous: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
} else {
|
||||
// Doação identificada - validar campos obrigatórios
|
||||
if (!body.donorName || body.donorName.trim().length < 3) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Nome é obrigatório (mínimo 3 caracteres)" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!body.donorPhone || body.donorPhone.trim().length === 0) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Telefone é obrigatório" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!body.donorEmail) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Email é obrigatório para doação identificada",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!body.donorTaxId || body.donorTaxId.trim().length === 0) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "CPF/CNPJ é obrigatório" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (body.donorMessage && body.donorMessage.length > 280) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Mensagem deve ter no máximo 280 caracteres",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
pixData = await abacatePay.createPixQrCode({
|
||||
amount: product.price,
|
||||
description: product.name,
|
||||
expiresIn: 600,
|
||||
customer: {
|
||||
name: body.donorName.trim(),
|
||||
email: body.donorEmail.trim(),
|
||||
cellphone: body.donorPhone.trim(),
|
||||
taxId: body.donorTaxId.trim(),
|
||||
},
|
||||
});
|
||||
|
||||
console.log("🔍 PIX criado (identificado):", pixData);
|
||||
|
||||
console.log("📝 Registro de doação identificada:", {
|
||||
type: "donation_created",
|
||||
pixId: pixData.id,
|
||||
amount: product.price,
|
||||
tier: body.tier,
|
||||
anonymous: false,
|
||||
donor: {
|
||||
name: body.donorName,
|
||||
email: body.donorEmail,
|
||||
phone: body.donorPhone,
|
||||
taxId: body.donorTaxId,
|
||||
message: body.donorMessage,
|
||||
},
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
billingId: billing.id,
|
||||
paymentUrl, // URL para redirecionar
|
||||
pixCode,
|
||||
pixQrCode,
|
||||
expiresAt: billing.expiresAt,
|
||||
pixId: pixData.id,
|
||||
brCode: pixData.brCode,
|
||||
brCodeBase64: pixData.brCodeBase64,
|
||||
expiresAt: pixData.expiresAt,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Donation creation error:", error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error ? error.message : "Erro interno do servidor",
|
||||
error: error instanceof Error ? error.message : "Erro interno",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
|
||||
@@ -15,23 +15,47 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
const event = JSON.parse(payload);
|
||||
|
||||
if (event.type === "billing.paid") {
|
||||
// Processar doação confirmada
|
||||
console.log("Donation confirmed:", event.data.id);
|
||||
console.log("🔔 Webhook recebido:", JSON.stringify(event, null, 2));
|
||||
|
||||
// Aqui você pode:
|
||||
// 1. Salvar no banco de dados
|
||||
// 2. Enviar email de agradecimento
|
||||
// 3. Atualizar estatísticas
|
||||
// 4. Notificar a equipe
|
||||
// Capturar todos os tipos de eventos de pagamento
|
||||
const isPaidEvent =
|
||||
event.type === "pix.paid" ||
|
||||
event.type === "billing.paid" ||
|
||||
event.type === "payment.paid" ||
|
||||
event.data?.status === "PAID";
|
||||
|
||||
// Por enquanto, apenas log
|
||||
console.log("Donation details:", {
|
||||
id: event.data.id,
|
||||
if (isPaidEvent) {
|
||||
console.log("✅ Doação confirmada via webhook:", event.data.id);
|
||||
|
||||
// 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(),
|
||||
createdAt: new Date().toISOString(),
|
||||
metadata: event.data.metadata,
|
||||
paidAt: event.data.paidAt,
|
||||
});
|
||||
};
|
||||
|
||||
console.log("📝 Registro de pagamento:", donationRecord);
|
||||
|
||||
// TODO: Quando implementar banco de dados, salvar aqui:
|
||||
// await db.donations.create(donationRecord);
|
||||
|
||||
// TODO: Quando implementar email, enviar aqui:
|
||||
// if (event.data.customer?.email) {
|
||||
// await sendThankYouEmail({
|
||||
// to: event.data.customer.email,
|
||||
// donorName: event.data.customer.name,
|
||||
// amount: event.data.amount,
|
||||
// });
|
||||
// }
|
||||
|
||||
// TODO: Atualizar estatísticas
|
||||
// await updateDonationStats(event.data.amount);
|
||||
} else {
|
||||
console.log("ℹ️ Evento de webhook (não é pagamento):", event.type);
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
|
||||
Reference in new issue
Block a user