A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
Merge PR #98: feat(merchant-keys) API key inspection, rotation, and flexible key resolution
rishabh767b6314166e
diff --cc apps/checkout-portal/src/__tests__/checkout-portal.test.jsindex bbc7122,3ecb4fe..050080e--- a/apps/checkout-portal/src/__tests__/checkout-portal.test.js+++ b/apps/checkout-portal/src/__tests__/checkout-portal.test.js@@@ -205,23 -197,24 +205,44 @@@ describe('Checkout Portal Integration Tassert.ok(res.text.includes('sanitizeRedirectUrl'));});+ test('renders dynamic branding when DEFAULT_APP_NAME or merchant branding is configured', async () => {+ const origEnv = { ...process.env };+ process.env.DEFAULT_APP_NAME = 'CustomPay Gateway';+ process.env.DEFAULT_PRIMARY_COLOR = '#0ea5e9';++ const portalServer = new CheckoutServer();+ const html = portalServer.renderHtml('pay_123', {+ merchantName: 'My Super Store',+ amount: '299.00'+ });++ assert.ok(html.includes('CustomPay Gateway Checkout'));+ assert.ok(html.includes('CustomPay Gateway Verified Business'));+ assert.ok(html.includes('200+ orders verified this month by CustomPay Gateway'));+ assert.ok(html.includes('CustomPay Gateway Help & Support'));++ process.env = { ...origEnv };+ });+++ test('GET /checkout/:id has balanced DOM structure so ypgStickyFooter stays inside ypg-pc-workspace (Issue #90)', async () => {+ const res = await get('/checkout/pay_test_uuid_12345');+ assert.equal(res.status, 200);++ // Must NOT have a duplicate <div class="ypg-body"> wrapper around <main class="ypg-body">+ assert.equal(res.text.includes('<div class="ypg-body">'), false, 'checkout.html must not wrap partials in a duplicate <div class="ypg-body">');+ assert.ok(res.text.includes('<main class="ypg-body">'), 'header partial must open <main class="ypg-body">');++ // Verify ypgStickyFooter is closed BEFORE END ypg-pc-workspace, and there are balanced <div> / </div> tags inside ypg-pc-workspace+ const wsStart = res.text.indexOf('<div class="ypg-pc-workspace">');+ const footerIdx = res.text.indexOf('id="ypgStickyFooter"');+ const wsEnd = res.text.indexOf('<!-- END ypg-pc-workspace -->');+ assert.ok(wsStart > 0 && footerIdx > wsStart && wsEnd > footerIdx, 'ypgStickyFooter must sit inside ypg-pc-workspace');++ const workspaceSlice = res.text.slice(wsStart, wsEnd);+ const openDivs = (workspaceSlice.match(/<div\b/g) || []).length;+ const closeDivs = (workspaceSlice.match(/<\/div>/g) || []).length;+ assert.equal(openDivs, closeDivs, `ypg-pc-workspace must have balanced <div> (${openDivs}) and </div> (${closeDivs}) tags so ypgStickyFooter is not ejected as a 3rd flex column on macOS/iOS`);+ });++ });});});diff --cc apps/payment-api/src/index.jsindex 9804754,156c2df..e1d9bf1--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@@ -373,18 -328,17 +380,24 @@@ export function createPaymentApp(custompollIntervalMs: Number(process.env.OBSERVER_POLL_INTERVAL_MS || 1500),minSweepCooldownMs: Number(process.env.OBSERVER_SWEEP_COOLDOWN_MS || 2000),smsPort: Number(process.env.SMS_OBSERVER_PORT || 6002),- gmailPort: Number(process.env.GMAIL_OBSERVER_PORT || 6003)+ gmailPort: Number(process.env.GMAIL_OBSERVER_PORT || 6003),+ smsBaseUrl: process.env.SMS_OBSERVER_URL,+ gmailBaseUrl: process.env.GMAIL_OBSERVER_URL});- // Execute crash recovery on boot+ // Execute crash recovery on boot (AFTER event listeners are wired so recovered terminal transitions emit webhooks)const recoveryStats = recoveryEngine.recover();+ // Replay only outboxed transitions that lack a durable delivery record.+ webhookEngine.recoverOutbox().catch(err => {+ console.error('[webhook] Failed to recover terminal-event outbox:', err.message);+ });++ // Immediately kick off a background retry sweep for any recovered in-flight or backfilled webhooks+ try {+ const initialRetry = webhookEngine.retryPending();+ if (initialRetry && typeof initialRetry.catch === 'function') initialRetry.catch(() => {});+ } catch {}+// Health check routesconst healthHandler = (req, res) => {HttpServer.json(res, 200, {diff --cc packages/core/src/webhook-engine.jsindex c21ae57,ef15690..e68fc86--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@@ -14,12 -13,67 +14,69 @@@ export class WebhookEngineconstructor(options) {this.db = options.db;this.merchantRepo = options.merchantRepo;- this.maxRetries = options.maxRetries || 5;+ this.sessionRepo = options.sessionRepo || new PaymentSessionRepository(this.db);+ this.maxRetries = Math.max(2, Math.min(20, Number(options.maxRetries) || 5));}+ /**+ * Builds the canonical webhook payload object for a payment session and outcome.+ * @param {string} publicOutcome+ * @param {any} session+ * @param {string} deliveryId+ * @param {number} timestampNum+ */+ _buildPayload(publicOutcome, session, deliveryId, timestampNum) {+ // Resolve UTR / bank reference number if attributed.+ // The bank reference (UTR/RRN) lives on the attributed observation, not on the+ // session row. Merchants need it to reconcile a webhook against their bank+ // statement, and it is part of the documented webhook contract.+ let utr = session.utr || session.bankReferenceNumber || session.bank_reference_number || '';+ const attributedObsId = session.attributedObservationId || session.attributed_observation_id;+ if (!utr && attributedObsId) {+ try {+ const obsRow = this.db.queryOne(+ 'SELECT bank_reference_number FROM payment_observations WHERE id = ?',+ [attributedObsId]+ );+ if (obsRow?.bank_reference_number) utr = obsRow.bank_reference_number;+ } catch {}+ }++ const amountPaiseVal = session.amountPaise !== undefined ? session.amountPaise : session.amount_paise;+ const orderIdVal = session.orderId || session.order_id;+ const attemptIdVal = session.attemptId || session.attempt_id || session.id;+ const completedAtRaw = session.completedAt || session.completed_at;+ let metadataVal = session.metadata;+ if (typeof metadataVal === 'string') {+ try { metadataVal = JSON.parse(metadataVal); } catch { metadataVal = {}; }+ }++ return {+ event: publicOutcome,+ deliveryId,+ timestamp: timestampNum,+ paymentId: session.id,+ orderId: orderIdVal,+ attemptId: attemptIdVal,+ amount: toRupeesString(amountPaiseVal),+ amountPaise: Number(amountPaiseVal),+ currency: session.currency || 'INR',+ method: session.method || 'UPI',+ utr: String(utr || ''),+ verificationTag: session.verificationTag || session.verification_tag || (session.method === 'COD' ? 'COD_ORDER_PLACED' : 'UNVERIFIED'),+ verificationLevel: session.verificationLevel != null ? Number(session.verificationLevel) : (session.verification_level != null ? Number(session.verification_level) : (session.method === 'COD' ? 1 : 0)),+ completedAt: completedAtRaw ? (typeof completedAtRaw.toISOString === 'function' ? completedAtRaw.toISOString() : String(completedAtRaw)) : new Date().toISOString(),- metadata: metadataVal || {}++ metadata: metadataVal || {},++ settlementState: settlementStateFor(publicOutcome)+ };+ }+/*** Formats and dispatches a signed webhook for a payment event.+ * Persists the pending delivery row in `webhook_deliveries` BEFORE making the outbound+ * HTTP call so that if the process crashes while the first delivery is in flight,+ * `retryPending()` will pick up and deliver the webhook upon restart.+ ** @param {string} event E.g. 'SUCCESS', 'FAILED', 'EXPIRED', 'CANCELLED'* @param {any} session The payment session entity* @returns {Promise<{ delivered: boolean, deliveryId: string, status?: number, error?: string }>}@@@ -194,10 -214,11 +265,10 @@@} catch (err) {responseBody = err.message || 'Network timeout';}--+ // 4. Finalize the delivery record in webhook_deliveriesconst nextRetryAt = isSuccessful? null- : new Date(Date.now() + 5000).toISOString(); // initial 5s backoff+ : new Date(Date.now() + 5000).toISOString();this.db.execute(`UPDATE webhook_deliveries@@@ -213,33 -244,79 +294,106 @@@};}+ /**+ * Prepare and send terminal events committed before a crash but not yet turned+ * into delivery records. The trigger records only new terminal transitions;+ * historic SUCCESS rows are never swept into webhooks on upgrade.+ */+ async recoverOutbox() {+ const rows = this.db.query(`+ SELECT o.payment_id, o.event_type+ FROM payment_webhook_outbox o+ WHERE NOT EXISTS (+ SELECT 1 FROM webhook_deliveries d+ WHERE d.payment_id = o.payment_id AND d.event_type = o.event_type+ )+ ORDER BY o.created_at, o.payment_id LIMIT 20+ `);+ const outcomes = [];+ for (const row of rows) {+ const session = this.sessionRepo.findById(row.payment_id);+ if (!session) continue;+ const merchant = this.merchantRepo.findById(session.merchantId);+ // Keep unconfigured merchants' events in the outbox for human remediation.+ if (!merchant?.webhookUrl || !merchant.webhookSecret) continue;+ outcomes.push(await this.dispatch(row.event_type, session));+ }+ return outcomes;+ }++ /**+ * Recovers webhook deliveries that were interrupted mid-flight by a process crash+ * or terminal payment sessions that transitioned just before `dispatch()` could run.+ *+ * @param {{ resetInFlight?: boolean }} [options]+ * @returns {number} Number of recovered/backfilled webhook delivery rows+ */+ recoverMissingDeliveries(options = {}) {+ const { resetInFlight = false } = options;+ const nowIso = new Date().toISOString();+ let recoveredCount = 0;++ if (resetInFlight) {+ // Any row with attempt_count = 0 and response_status IS NULL was in-flight when the previous process died.+ // Reset its next_retry_at to now so retryPending() claims it immediately on boot.+ const res = this.db.execute(`+ UPDATE webhook_deliveries+ SET next_retry_at = ?+ WHERE is_successful = 0 AND attempt_count = 0 AND response_status IS NULL+ `, [nowIso]);+ recoveredCount += Number(res?.changes || 0);+ }++ // Find terminal payment sessions for merchants with configured webhooks that have NO webhook_deliveries row at all.+ const orphanedSessions = this.db.query(`+ SELECT ps.*+ FROM payment_sessions ps+ JOIN merchants m ON m.id = ps.merchant_id+ WHERE ps.status IN ('SUCCESS', 'FAILED', 'EXPIRED', 'CANCELLED')+ AND m.webhook_url IS NOT NULL AND m.webhook_url != ''+ AND m.webhook_secret IS NOT NULL AND m.webhook_secret != ''+ AND NOT EXISTS (+ SELECT 1 FROM webhook_deliveries wd WHERE wd.payment_id = ps.id+ )+ LIMIT 100+ `);++ for (const sessionRow of orphanedSessions) {+ const merchant = this.merchantRepo.findById(sessionRow.merchant_id);+ if (!merchant || !merchant.webhookUrl || !merchant.webhookSecret) continue;++ const endpointCheck = validateOutboundWebhookUrl(merchant.webhookUrl);+ if (!endpointCheck.valid) continue;++ const publicOutcome = isTerminalStatus(sessionRow.status)+ ? toPublicOutcome(sessionRow.status)+ : sessionRow.status;+ const deliveryId = crypto.randomUUID();+ const timestampNum = Date.now();+ const payloadObj = this._buildPayload(publicOutcome, sessionRow, deliveryId, timestampNum);+ const payloadString = JSON.stringify(payloadObj);++ this.db.execute(`+ INSERT INTO webhook_deliveries (+ id, merchant_id, payment_id, event_type, payload, endpoint_url,+ response_status, response_body, attempt_count, is_successful, next_retry_at, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, 0, 0, ?, ?)+ `, [+ deliveryId,+ merchant.id,+ sessionRow.id,+ publicOutcome,+ payloadString,+ merchant.webhookUrl,+ nowIso,+ nowIso+ ]);+ recoveredCount++;+ }++ return recoveredCount;+ }+/*** Retries overdue pending webhook deliveries with atomic claim & exponential backoff.* Backoff strategy: 5s, 30s, 2m, 10m, 1h