/** * Online payment providers. * * Every provider implements the same interface (see providers/yoco.js, providers/payfast.js): * id, label * capabilities { refund, getTransaction, listTransactions } — what its API supports * isConfigured() → Promise credentials are set * createCheckout(input) → Promise<{ externalId?, redirectUrl? } | { form: { action, fields } }> * input: { checkoutId, amountCents, currency, metadata, lineItems, * successUrl, cancelUrl, failureUrl, payer?, description, * idempotencyKey }; lineItems: [{ name, quantity, unitCents }] * (negative unitCents = a deduction). A provider that takes the * payer with a signed form (PayFast) returns { form }; the payer's * browser posts it from /pay/. * verifyWebhook(req) → Promise<{ ok: true } | { ok: false, status, message, details? }> * parseWebhook(body) → { type: 'payment.succeeded' | , transaction } * body: the request body as the provider sent it (JSON or form) * transaction: { externalId, amountCents, currency, createdDate, * checkoutId, methodType, metadata, status } * readWebhookBody(raw) → (optional) turns req.rawBody into the body; default JSON.parse * getTransaction / refund / listTransactions — only when the capability is true * * Every checkout is recorded as a ProviderCheckout (amount, what it's for, return URLs), so * the payment that comes back can be matched and checked, and so the payer can be sent to * /pay/: there they choose a provider when several are enabled, or their browser posts a * provider's form. Admins switch providers on and off and set their order in Site settings → * Payments (AppSetting `payment_providers`). Provider fees are never deducted or added: * payments are recorded at the full amount and fees are handled at cashup. */ const prisma = require('../config/db'); const { getSetting } = require('../utils/settingsCache'); const PROVIDERS = [require('./providers/yoco'), require('./providers/payfast')]; const BY_ID = new Map(PROVIDERS.map(p => [p.id, p])); // One minimum for every provider: online payments must be at least R15. const MIN_ONLINE_AMOUNT = 15; const SETTINGS_KEY = 'payment_providers'; function paymentError(message, statusCode = 400) { const err = new Error(message); err.statusCode = statusCode; return err; } /** A provider by id, or null. */ function getProvider(id) { return BY_ID.get(String(id || '')) || null; } /** * Enabled flags and order from the stored setting. Pure. Unknown ids are dropped; providers * not in the setting yet come last — Yoco enabled (it was the only provider before), others off. * @param {string} raw - JSON: { order: string[], enabled: { [id]: boolean } } * @param {string[]} [ids] - known provider ids, in default order * @returns {{ id: string, enabled: boolean }[]} */ function parseProviderSettings(raw, ids = PROVIDERS.map(p => p.id)) { let stored = {}; try { stored = raw ? JSON.parse(raw) : {}; } catch { stored = {}; } const order = Array.isArray(stored.order) ? stored.order.filter(id => ids.includes(id)) : []; const all = [...new Set([...order, ...ids])]; const enabled = stored.enabled && typeof stored.enabled === 'object' ? stored.enabled : {}; return all.map(id => ({ id, enabled: typeof enabled[id] === 'boolean' ? enabled[id] : id === 'yoco' })); } /** Every provider with its settings and whether it's configured, in display order. */ async function providerSettings() { const list = parseProviderSettings(await getSetting(SETTINGS_KEY)); return Promise.all(list.map(async ({ id, enabled }) => { const p = getProvider(id); return { id, label: p.label, enabled, configured: await p.isConfigured(), capabilities: p.capabilities }; })); } /** Providers people can pay with now (enabled and configured), in display order. */ async function availableProviders() { return (await providerSettings()).filter(p => p.enabled && p.configured); } /** The setting value to store for an ordered list of { id, enabled }. */ function serializeProviderSettings(list) { const ids = list.map(p => p.id).filter(id => getProvider(id)); return JSON.stringify({ order: ids, enabled: Object.fromEntries(list.filter(p => getProvider(p.id)).map(p => [p.id, p.enabled === true])) }); } /** The payer's page for a checkout: /pay/ on the frontend. */ function payPageUrl(checkoutId) { const base = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3000').split(',')[0].trim().replace(/\/$/, ''); return `${base}/pay/${encodeURIComponent(checkoutId)}`; } /** Throws unless `provider` may take payments now (enabled; and set up, or it explains). */ async function assertUsable(provider) { const state = (await providerSettings()).find(p => p.id === provider.id); if (!state?.enabled) throw paymentError(`Paying with ${provider.label} is turned off.`); } /** * Starts a recorded checkout with a provider. Idempotent for a provider that was already * started with a redirect (Yoco); form providers rebuild their (deterministic) form. * @returns {Promise<{ provider, redirectUrl, form? }>} */ async function startCheckout(checkout, provider) { if (checkout.provider === provider.id && checkout.redirectUrl) return { provider: provider.id, redirectUrl: checkout.redirectUrl }; const request = checkout.request || {}; const started = await provider.createCheckout({ ...request, checkoutId: checkout.id, amountCents: checkout.amountCents, currency: checkout.currency, metadata: checkout.metadata, }); if (started.form) { if (checkout.provider !== provider.id) await prisma.providerCheckout.update({ where: { id: checkout.id }, data: { provider: provider.id } }); return { provider: provider.id, redirectUrl: payPageUrl(checkout.id), form: started.form }; } await prisma.providerCheckout.update({ where: { id: checkout.id }, data: { provider: provider.id, externalId: started.externalId || null, redirectUrl: started.redirectUrl }, }); return { provider: provider.id, redirectUrl: started.redirectUrl }; } /** * Starts a checkout with `providerId`, or the only available provider; with several * available, the payer chooses on /pay/. * @param {object} input - { amountCents, metadata, lineItems, successUrl, cancelUrl, failureUrl, * payer?: { name, email }, description?, idempotencyKey? } * @returns {Promise<{ checkoutId, redirectUrl, provider: string|null }>} */ async function createCheckout(providerId, input) { if (!(input.amountCents >= MIN_ONLINE_AMOUNT * 100)) { throw paymentError(`Online payments must be at least R${MIN_ONLINE_AMOUNT}. Please pay at the door or contact the organiser.`); } let provider = null; const available = await availableProviders(); if (providerId) { provider = getProvider(providerId); if (!provider) throw paymentError('Unknown payment provider.'); await assertUsable(provider); } else if (available.length === 1) { provider = getProvider(available[0].id); } else if (available.length === 0) { // Nothing enabled: say so. Enabled but not set up: the provider explains what's missing. const enabled = (await providerSettings()).find(p => p.enabled); if (!enabled) throw paymentError('Online payments are turned off. Please pay at the door or contact the organiser.', 503); provider = getProvider(enabled.id); } const { amountCents, metadata, currency, ...request } = input; const checkout = await prisma.providerCheckout.create({ data: { amountCents, currency: currency || 'ZAR', metadata: metadata || {}, request }, }); if (!provider) return { checkoutId: checkout.id, redirectUrl: payPageUrl(checkout.id), provider: null }; try { const started = await startCheckout(checkout, provider); return { checkoutId: checkout.id, redirectUrl: started.redirectUrl, provider: started.provider }; } catch (e) { await prisma.providerCheckout.delete({ where: { id: checkout.id } }).catch(() => {}); throw e; } } /** The checkout a webhook is about: by our id, or by the provider's own checkout id. */ async function findCheckout(providerId, ref) { if (!ref) return null; const ours = await prisma.providerCheckout.findUnique({ where: { id: String(ref) } }).catch(() => null); if (ours) return ours; return prisma.providerCheckout.findFirst({ where: { provider: providerId, externalId: String(ref) } }); } module.exports = { PROVIDERS, MIN_ONLINE_AMOUNT, SETTINGS_KEY, paymentError, getProvider, parseProviderSettings, serializeProviderSettings, providerSettings, availableProviders, payPageUrl, assertUsable, createCheckout, startCheckout, findCheckout, };