Skip to content

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

fix(webhook): include the bank reference (UTR) in the webhook payload

rishabh3fe33cedfd1d
diff --git a/packages/core/src/__tests__/webhook-engine.test.js b/packages/core/src/__tests__/webhook-engine.test.js
index 9839346..271c0cb 100644
--- a/packages/core/src/__tests__/webhook-engine.test.js
+++ b/packages/core/src/__tests__/webhook-engine.test.js
@@ -2,7 +2,7 @@ import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import '../../../../scripts/test-support.js';
-import { Database, runMigrations, MerchantRepository, PaymentSessionRepository } from '@youpi/db';
+import { Database, runMigrations, MerchantRepository, PaymentSessionRepository, ObservationRepository } from '@youpi/db';
import { WebhookEngine } from '../webhook-engine.js';
import { verifyHmac } from '@youpi/common';
@@ -111,6 +111,55 @@ describe('Webhook Engine Integration Tests', () => {
assert.equal(delivery.response_status, 200);
});
+ test('carries the bank reference (UTR) from the attributed observation', async () => {
+ const merchant = merchantRepo.create({
+ businessName: 'UTR Store',
+ slug: 'utr-store',
+ contactEmail: '[email protected]',
+ contactPhone: '9876543210',
+ webhookUrl: `http://localhost:${receiverPort}/webhook-utr`,
+ webhookSecret: 'test_secret_for_utr_signatures_123'
+ });
+
+ const session = sessionRepo.create({
+ merchantId: merchant.id,
+ orderId: 'HOOK-ORD-UTR',
+ amountPaise: 20000n,
+ receivingAccountId: '00000000-0000-0000-0000-000000000002'
+ });
+
+ // The UTR lives on the observation, not on the session row.
+ const observation = new ObservationRepository(db).create({
+ receivingAccountId: session.receivingAccountId,
+ source: 'GOOGLE_MESSAGES',
+ rawText: 'Rs 200.00 credited UPI ref 412345678901',
+ amountPaise: 20000n,
+ bankReferenceNumber: '412345678901',
+ observedAt: new Date(),
+ fingerprintHash: 'fp_utr_test'
+ });
+ db.execute('UPDATE payment_sessions SET attributed_observation_id = ? WHERE id = ?', [observation.id, session.id]);
+
+ receivedWebhooks = [];
+ shouldReceiverFail = false;
+
+ const result = await webhookEngine.dispatch('SUCCESS', sessionRepo.findById(session.id));
+ assert.equal(result.delivered, true);
+
+ const hook = receivedWebhooks.find(h => h.body.orderId === 'HOOK-ORD-UTR');
+ assert.ok(hook, 'webhook not received');
+ assert.equal(hook.body.utr, '412345678901');
+
+ // The signature must still cover the body that now includes the UTR.
+ const rawSig = hook.headers['x-gateway-signature'].replace('sha256=', '');
+ assert.equal(verifyHmac(JSON.stringify(hook.body), merchant.webhookSecret, rawSig), true);
+
+ // The documented webhook contract must expose every field.
+ for (const field of ['event', 'paymentId', 'orderId', 'amount', 'amountPaise', 'currency', 'method', 'utr', 'completedAt', 'metadata']) {
+ assert.ok(field in hook.body, `missing documented webhook field: ${field}`);
+ }
+ });
+
test('records failure and supports retry on merchant HTTP 500 error', async () => {
const merchant = merchantRepo.create({
businessName: 'Failing Store',
diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.js
index 22c4acd..3c5c5a0 100644
--- a/packages/core/src/webhook-engine.js
+++ b/packages/core/src/webhook-engine.js
@@ -37,6 +37,20 @@ export class WebhookEngine {
const publicOutcome = isTerminalStatus(event) ? toPublicOutcome(event) : event;
+ // 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 || '';
+ if (!utr && session.attributedObservationId) {
+ try {
+ const obsRow = this.db.queryOne(
+ 'SELECT bank_reference_number FROM payment_observations WHERE id = ?',
+ [session.attributedObservationId]
+ );
+ if (obsRow?.bank_reference_number) utr = obsRow.bank_reference_number;
+ } catch {}
+ }
+
const payloadObj = {
event: publicOutcome,
paymentId: session.id,
@@ -45,6 +59,7 @@ export class WebhookEngine {
amountPaise: Number(session.amountPaise),
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: session.completedAt ? (typeof session.completedAt.toISOString === 'function' ? session.completedAt.toISOString() : String(session.completedAt)) : new Date().toISOString(),