"use client"; import React, { useCallback, useEffect, useRef, useState } from "react"; import { useParams } from "next/navigation"; import { Navbar } from "@/components/layout/Navbar"; import { Footer } from "@/components/layout/Footer"; import { apiFetch, ApiError } from "@/lib/api"; import { CreditCard } from "lucide-react"; type ProviderForm = { action: string; fields: Record }; type PayPage = { id: string; status: "open" | "paid"; amount: number; description: string; provider: string | null; providers: { id: string; label: string }[]; cancelUrl: string | null; redirectUrl: string | null; form: ProviderForm | null; }; /** * The payer's page for an online checkout (/pay/): choose how to pay when several payment * providers are enabled, or — for a provider that takes a signed form (PayFast) — post that * form. Payment links in emails, WhatsApp and invoice QR codes can point here. */ export default function PayPage() { const params = useParams<{ id: string }>(); const id = params?.id; const [page, setPage] = useState(null); const [form, setForm] = useState(null); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); const formRef = useRef(null); const go = useCallback((res: { redirectUrl: string | null; form: ProviderForm | null }) => { if (res.form) setForm(res.form); else if (res.redirectUrl) window.location.href = res.redirectUrl; }, []); useEffect(() => { if (!id) return; apiFetch(`/api/payments/pay/${encodeURIComponent(id)}`) .then(p => { setPage(p); if (p.status === "open") go(p); }) .catch(e => setError(e instanceof ApiError ? e.message : "Couldn't load this payment.")); }, [id, go]); // Once a provider's form is known, the browser posts it to the provider. useEffect(() => { if (form) formRef.current?.submit(); }, [form]); const choose = async (provider: string) => { if (!id) return; setBusy(provider); setError(null); try { go(await apiFetch<{ redirectUrl: string | null; form: ProviderForm | null }>(`/api/payments/pay/${encodeURIComponent(id)}`, { method: "POST", body: { provider } })); } catch (e) { setError(e instanceof ApiError ? e.message : "Couldn't start the payment. Please try again."); setBusy(null); } }; const choosing = page?.status === "open" && !page.provider && !form; return (

Pay online

{error &&
{error}
} {!page && !error &&
Loading…
} {page && (
{page.description &&
{page.description}
}
R{page.amount.toFixed(2)}
{page.status === "paid" ? (

This has been paid. Thank you!

) : choosing ? ( page.providers.length === 0 ? (

Online payments aren't available right now. Please pay at the door or contact the organiser.

) : (

How would you like to pay?

{page.providers.map(p => ( ))}
) ) : (

Taking you to the payment page…

)} {form && (
{Object.entries(form.fields).map(([name, value]) => )}
)} {page.status === "open" && page.cancelUrl && ( Cancel )}
)}
); }