Payment provider interface: Yoco behind it, Site settings → Payments

- src/payments: provider registry and PaymentProvider interface
  (createCheckout, verifyWebhook/parseWebhook, getTransaction, refund,
  listTransactions as capabilities), Yoco as the first provider. All four
  direct Yoco checkout calls go through payments.createCheckout.
- Webhook split into the provider part (signature, parsing) and shared
  processing; same URL (/api/webhooks/yoco), same behaviour.
- YocoTransaction renamed in place to ProviderTransaction (+ provider,
  unique per provider + externalId); Payment.provider added and
  backfilled to "yoco". Payment.method stays the wallet type so cashups
  are unchanged.
- Site settings → Payments: Enabled toggle and order per provider; Yoco's
  settings shown while it's enabled. R15 minimum for all online payments.
- New endpoint names (/api/payments/checkout, /api/provider-transactions);
  the old /yoco-checkout and /yoco-transactions paths still work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-23 12:17:29 +02:00
co-authored by Claude Opus 5.5
parent 608f3ccec5
commit 2116d727b9
37 changed files with 1551 additions and 1243 deletions
@@ -11,13 +11,13 @@ import { ColorPickerField } from "@/components/admin/ColorPickerField";
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
import { BackupsTab } from "@/components/admin/BackupsTab";
import { JobsTab } from "@/components/admin/JobsTab";
import { YocoTab } from "@/components/admin/YocoTab";
import { PaymentsTab } from "@/components/admin/PaymentsTab";
import { extractDominantColors } from "@/lib/extractColors";
import { mapsSearchUrl } from "@/lib/maps";
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
type TabId = "organisation" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "yoco" | "backups" | "jobs";
type TabId = "organisation" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "backups" | "jobs";
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "organisation", label: "Organisation", icon: Building2 },
@@ -26,7 +26,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "email", label: "Email", icon: Mail },
{ id: "legal", label: "Legal", icon: Scale },
{ id: "whatsapp", label: "WhatsApp", icon: MessageCircle },
{ id: "yoco", label: "Yoco", icon: CreditCard },
{ id: "payments", label: "Payments", icon: CreditCard },
{ id: "backups", label: "Backups", icon: DatabaseBackup },
{ id: "jobs", label: "Background jobs", icon: Timer },
];
@@ -97,7 +97,9 @@ function SiteSettingsPageInner() {
const searchParams = useSearchParams();
const { reload: reloadSettings } = useSiteSettings();
const initialTab = TABS.some(t => t.id === searchParams.get("tab")) ? (searchParams.get("tab") as TabId) : "organisation";
// ?tab=yoco is the Payments tab's older name.
const tabParam = searchParams.get("tab") === "yoco" ? "payments" : searchParams.get("tab");
const initialTab = TABS.some(t => t.id === tabParam) ? (tabParam as TabId) : "organisation";
const [activeTab, setActiveTab] = useState<TabId>(initialTab);
const [loadingInitial, setLoadingInitial] = useState(true);
@@ -703,7 +705,7 @@ function SiteSettingsPageInner() {
{activeTab === "whatsapp" && <WhatsAppTab active={activeTab === "whatsapp"} />}
{/* ── Yoco ──────────────────────────────────────────────────────────── */}
{activeTab === "yoco" && <YocoTab active={activeTab === "yoco"} />}
{activeTab === "payments" && <PaymentsTab active={activeTab === "payments"} />}
{/* ── Backups ───────────────────────────────────────────────────────── */}
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
@@ -35,16 +35,18 @@ function refundMethodForOriginal(method: string | null | undefined): string {
type Outstanding = Record<string, { totalDue: number; totalPaid: number; outstanding: number }>;
// An unreconciled Yoco transaction (GET /api/yoco-transactions/unreconciled). `raw` is the
// webhook as Yoco sent it; its checkout metadata says who/what the payment was for.
type YocoTx = {
// An unreconciled payment provider transaction (GET /api/provider-transactions/unreconciled).
// `metadata` is the checkout metadata: who/what the payment was for.
type ProviderTx = {
id: string;
provider: string;
providerLabel: string;
amount: number;
checkoutId?: string | null;
externalId?: string | null;
methodType?: string | null;
createdDate?: string | null;
raw?: { payload?: { metadata?: { userId?: string; eventId?: string } } } | null;
metadata?: { userId?: string; eventId?: string } | null;
};
function RegistrationOptions({ regs, regOutstanding }: {
@@ -278,7 +280,7 @@ function PaymentsContent() {
if (!amt || amt <= 0) { setError("Enter a valid amount"); return; }
try {
setLinkGenerating(true);
const res = await apiFetch<{ redirectUrl?: string; checkoutId?: string; amount?: number; priceUpdated?: boolean; message?: string }>("/api/payments/yoco-checkout", {
const res = await apiFetch<{ redirectUrl?: string; checkoutId?: string; amount?: number; priceUpdated?: boolean; message?: string }>("/api/payments/checkout", {
method: "POST",
authToken: token,
body: {
@@ -319,7 +321,7 @@ function PaymentsContent() {
setError(null); setInfo(null);
try {
setLinkSending(channel);
await apiFetch("/api/payments/yoco-checkout/send", {
await apiFetch("/api/payments/checkout/send", {
method: "POST",
authToken: token,
body: { registrationId: linkResult.registrationId, redirectUrl: linkResult.redirectUrl, channel },
@@ -421,34 +423,34 @@ function PaymentsContent() {
const [mode, setMode] = useState<'payment'|'refund'|'donation'|'reconcile'|'link'>("payment");
// Yoco unreconciled list and actions
const [yocoLoading, setYocoLoading] = useState(false);
const [yocoTxs, setYocoTxs] = useState<YocoTx[]>([]);
const loadYocoUnreconciled = useCallback(async () => {
// Unreconciled online payments (from payment providers) and actions
const [txLoading, setTxLoading] = useState(false);
const [providerTxs, setProviderTxs] = useState<ProviderTx[]>([]);
const loadUnreconciled = useCallback(async () => {
if (!token) return;
try {
setYocoLoading(true);
const res = await apiFetch<{ data?: YocoTx[] } | YocoTx[]>("/api/yoco-transactions/unreconciled", { authToken: token });
setTxLoading(true);
const res = await apiFetch<{ data?: ProviderTx[] } | ProviderTx[]>("/api/provider-transactions/unreconciled", { authToken: token });
const items = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : []);
setYocoTxs(items);
setProviderTxs(items);
} catch {
// ignore silently, shown on demand via error state if needed
} finally {
setYocoLoading(false);
setTxLoading(false);
}
}, [token]);
useEffect(() => { loadYocoUnreconciled(); }, [loadYocoUnreconciled]);
useEffect(() => { loadUnreconciled(); }, [loadUnreconciled]);
// Inline reconcile form state per-row
const [reconcileForm, setReconcileForm] = useState<{ txId: string | null; type: 'reg' | 'don' | null; userId: string; registrationId: string; eventId: string; submitting: boolean }>({ txId: null, type: null, userId: '', registrationId: '', eventId: '', submitting: false });
const openReconcileToRegistration = (tx: YocoTx) => {
const metaUser = tx?.raw?.payload?.metadata?.userId ? String(tx.raw.payload.metadata.userId) : '';
const openReconcileToRegistration = (tx: ProviderTx) => {
const metaUser = tx.metadata?.userId ? String(tx.metadata.userId) : '';
setReconcileForm({ txId: tx.id, type: 'reg', userId: metaUser, registrationId: '', eventId: '', submitting: false });
};
const openReconcileAsDonation = (tx: YocoTx) => {
const metaEvent = tx?.raw?.payload?.metadata?.eventId ? String(tx.raw.payload.metadata.eventId) : '';
const openReconcileAsDonation = (tx: ProviderTx) => {
const metaEvent = tx.metadata?.eventId ? String(tx.metadata.eventId) : '';
setReconcileForm({ txId: tx.id, type: 'don', userId: '', registrationId: '', eventId: metaEvent, submitting: false });
};
@@ -467,7 +469,7 @@ function PaymentsContent() {
setReconcileForm(prev => ({ ...prev, submitting: true }));
if (type === 'reg') {
if (!registrationId) { setError('Please select a registration'); return; }
await apiFetch(`/api/yoco-transactions/${encodeURIComponent(txId)}/reconcile`, {
await apiFetch(`/api/provider-transactions/${encodeURIComponent(txId)}/reconcile`, {
method: 'POST',
authToken: token,
body: { registrationId }
@@ -475,7 +477,7 @@ function PaymentsContent() {
setInfo('Reconciled to registration');
} else {
if (!eventId) { setError('Please select an event'); return; }
await apiFetch(`/api/yoco-transactions/${encodeURIComponent(txId)}/reconcile`, {
await apiFetch(`/api/provider-transactions/${encodeURIComponent(txId)}/reconcile`, {
method: 'POST',
authToken: token,
body: { eventId, userId: userId || undefined }
@@ -483,7 +485,7 @@ function PaymentsContent() {
setInfo('Reconciled as donation');
}
setReconcileForm({ txId: null, type: null, userId: '', registrationId: '', eventId: '', submitting: false });
await Promise.all([loadYocoUnreconciled(), loadPayments(), loadRegistrations()]);
await Promise.all([loadUnreconciled(), loadPayments(), loadRegistrations()]);
} catch (e) {
setError(errorMessage(e) || 'Failed to reconcile');
} finally {
@@ -547,21 +549,22 @@ function PaymentsContent() {
<div className="grid lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
{/* Yoco reconciliation panel */}
{/* Online payment reconciliation panel */}
{mode === 'reconcile' && (
<div className="border rounded-xl p-4 bg-white shadow-sm">
<div className="flex items-center justify-between mb-3">
<div className="text-lg font-semibold">Unreconciled Yoco Payments</div>
<button className="px-3 py-1.5 text-sm rounded bg-gray-100 hover:bg-gray-200 text-gray-800" onClick={loadYocoUnreconciled} disabled={yocoLoading}>{yocoLoading ? 'Refreshing…' : 'Refresh'}</button>
<div className="text-lg font-semibold">Unreconciled Online Payments</div>
<button className="px-3 py-1.5 text-sm rounded bg-gray-100 hover:bg-gray-200 text-gray-800" onClick={loadUnreconciled} disabled={txLoading}>{txLoading ? 'Refreshing…' : 'Refresh'}</button>
</div>
{yocoTxs.length === 0 ? (
<div className="text-sm text-gray-500">No unreconciled Yoco transactions.</div>
{providerTxs.length === 0 ? (
<div className="text-sm text-gray-500">No unreconciled online payments.</div>
) : (
<div className="overflow-x-auto w-full">
<table className="min-w-full text-sm">
<thead>
<tr className="text-left border-b">
<th className="py-2 pr-3">Created</th>
<th className="py-2 pr-3">Provider</th>
<th className="py-2 pr-3">External ID</th>
<th className="py-2 pr-3">Amount</th>
<th className="py-2 pr-3">Checkout</th>
@@ -570,10 +573,11 @@ function PaymentsContent() {
</tr>
</thead>
<tbody>
{yocoTxs.map(tx => (
{providerTxs.map(tx => (
<React.Fragment key={tx.id}>
<tr className="border-b hover:bg-gray-50">
<td className="py-2 pr-3 whitespace-nowrap">{tx.createdDate ? new Date(tx.createdDate).toLocaleString() : '-'}</td>
<td className="py-2 pr-3">{tx.providerLabel}</td>
<td className="py-2 pr-3 font-mono text-xs break-all max-w-[10rem]">{tx.externalId}</td>
<td className="py-2 pr-3">R {(Number(tx.amount || 0)/100).toFixed(2)}</td>
<td className="py-2 pr-3 break-all max-w-[8rem]">{tx.checkoutId || '-'}</td>
@@ -586,9 +590,9 @@ function PaymentsContent() {
const ok = window.confirm('Ignore this transaction? It will be marked as ignored and reconciled.');
if (!ok) return;
try {
await apiFetch(`/api/yoco-transactions/${encodeURIComponent(tx.id)}/ignore`, { method: 'POST', authToken: token });
await apiFetch(`/api/provider-transactions/${encodeURIComponent(tx.id)}/ignore`, { method: 'POST', authToken: token });
setInfo('Transaction ignored');
await loadYocoUnreconciled();
await loadUnreconciled();
} catch (e) {
setError(errorMessage(e) || 'Failed to ignore');
}
@@ -597,7 +601,7 @@ function PaymentsContent() {
</tr>
{reconcileForm.txId === tx.id && (
<tr className="bg-gray-50">
<td colSpan={6} className="p-3">
<td colSpan={7} className="p-3">
{reconcileForm.type === 'reg' ? (
<div className="grid sm:grid-cols-3 gap-3 items-end">
<div>
@@ -39,7 +39,7 @@ export default function DonatePage() {
setError(null);
setInfo(null);
setLoading(true);
const res = await apiFetch<{ redirectUrl: string }>("/api/payments/yoco-checkout", {
const res = await apiFetch<{ redirectUrl: string }>("/api/payments/checkout", {
method: "POST",
body: {
eventId,