Every payment collection gateway, UPI autopay/mandate provider, disbursement banking rail, and co-lending partner los-backend talks to — real endpoint URLs, internal triggers, credential resolution, and every webhook route that confirms money actually moved.
src/features/payment/ and src/features/lendbox-v1/, grep-verified endpoint URLsDirectory: src/features/payment/collection/providers/ — 6 files, 5 distinct vendors (Cashfree, Razorpay across 2 merchant accounts, Easebuzz across 2 products, Paytring, PayU). Orchestration runs through CollectionPaymentService (src/features/payment/collection/collection-payment.service.ts), the single point every gateway order and every gateway webhook passes through. Controller: PaymentController (src/features/payment/collection/payment.controller.ts, base route /payment).
CollectionPaymentService.getCollectionProvider(brandId, loanNbfcId) reads brandProvider rows of type=FULL_PAYMENT, ranks an NBFC-scoped provider above a brand-wide one when the loan has an NBFC (so a borrower's money settles into the correct lending entity), and exposes { primary, available }. Every order-creation path calls assertCollectionGatewayAllowed() first, which re-derives available and 400s if the requested method isn't in it — enforced server-side even though the frontend also hides unavailable options.
Hosted payment link / order checkout for loan EMI/closure repayments.
{CASHFREE_BASE_URL}/links — create a payment link (createPaymentLink){CASHFREE_BASE_URL}/orders — create an order (createOrder; returns a payment_session_id used to build the frontend checkout URL https://{web_hostname}/payment/cashfree?session_id=...){CASHFREE_BASE_URL}/links/{paymentLinkId} — fetch link details{CASHFREE_BASE_URL}/links/{paymentLinkId}/cancel — cancel a link{CASHFREE_BASE_URL}/links/{paymentLinkId}/orders — list orders under a linksrc/features/payment/collection/providers/cashfree.service.ts
TriggerPOST /payment/create, POST /payment/manual-payment, POST /payment/public/loan-inquiry/create-payment → CollectionPaymentService.createPaymentOrder() → CashfreeService.createOrder/createPaymentLink. Also GET /payment/cashfree/payment-link/:paymentLinkId/orders in PaymentController.
AuthHeaders x-client-id/x-client-secret from CASHFREE_CLIENT_ID/CASHFREE_CLIENT_SECRET, resolved via BrandProviderKeyReader.resolve(brandId, "FULL_PAYMENT"|"PART_PAYMENT", "CASHFREE", [...]).
WebhookPOST /payment/cashfree/callback in payment.controller.ts → CashfreeService.handleWebhookCallback(). Handles 3 event types: PAYMENT_LINK_EVENT, PAYMENT_SUCCESS_WEBHOOK, PAYMENT_CHARGES_WEBHOOK. Signature verified via HMAC-SHA256 of the raw body against CASHFREE_WEBHOOK_SECRET — the signature-mismatch branch is currently commented out (it logs but does not reject). Every raw webhook payload is persisted to logs/cashfree-webhooks/*.json for audit before processing.
CASHFREE_BASE_URL = https://sandbox.cashfree.com/pg; API version header x-api-version: 2025-01-01. Transaction lookup on webhook falls through 5 strategies (payment_transaction_id in order_tags → link_id → cf_link_id → externalRef → payment_request_id) because Cashfree's webhook shape has drifted across event types. Auto-approval (COLLECTION_AUTO_APPROVE_ENABLED=true) only fires for genuine COLLECTION-type successes, never for informational PAYMENT_CHARGES_WEBHOOK events.Hosted payment-link checkout; supports two independently-configured merchant accounts (RAZORPAY, RAZORPAY_V2) on one shared service.
{baseUrl}/payment_links — create payment link{baseUrl}/payment_links/{id} — fetch link{baseUrl}/orders/{id} — fetch order{baseUrl}/payments/{id} — fetch payment{baseUrl}/payment_links/{id}/cancel — cancel link{baseUrl}/payment_links/{id}/payments — list payments under a linksrc/features/payment/collection/providers/razorpay.service.ts
TriggerSame CollectionPaymentService.createPaymentOrder() dispatch as Cashfree, for method = RAZORPAY | RAZORPAY_V2.
AuthHTTP Basic auth, Authorization: Basic base64(keyId:keySecret); env RAZORPAY_KEY_ID/RAZORPAY_KEY_SECRET (account 1) or RAZORPAY_V2_KEY_ID/RAZORPAY_V2_KEY_SECRET (account 2), resolved per-brand via BrandProviderKeyReader.
WebhookPOST /payment/razorpay/callback and POST /payment/razorpay-v2/callback in payment.controller.ts → CollectionPaymentService.handleRazorpayCallback(body, account). Handles payment.captured, payment.failed, payment_link.paid, payment_link.cancelled. Signature verification (verifyRazorpayWebhookSignature against RAZORPAY_WEBHOOK_SECRET) is implemented on the service but currently commented out at the controller call site.
{RAZORPAY_BASE_URL} / {RAZORPAY_V2_BASE_URL} = https://api.razorpay.com/v1. payment.captured handling re-fetches the order from Razorpay to recover internal notes (loan_id, payment_request_id, payment_transaction_id, transaction_type) rather than trusting the webhook body directly — guards against spoofed/incomplete webhook payloads. Refuses to re-process a transaction already opsApprovalStatus=APPROVED.Hosted checkout page, access-key based flow (distinct from the EasyCollect product below).
{baseUrl}/payment/initiateLink — initiate payment, returns an access_key; checkout URL built client-side as {baseUrl}/pay/{access_key}{dashboardBaseUrl}/transaction/v1/retrieve — status lookup (dashboard host differs: https://dashboard.easebuzz.in prod / https://testdashboard.easebuzz.in else)src/features/payment/collection/providers/easebuzz.service.ts
TriggerCollectionPaymentService.createPaymentOrder() for method=EASEBUZZ.
AuthSHA-512 request hash: key|txnid|amount|productinfo|firstname|email|udf1..udf10|salt. Env EASEBUZZ_KEY/EASEBUZZ_SALT, resolved via BrandProviderKeyReader.
WebhookPOST /payment/easebuzz/callback in payment.controller.ts (browser redirect/callback, not pure server-to-server — returns an HTML page via generateEasebuzzCallbackHTML) → CollectionPaymentService.handleEasebuzzCallback(). Reverse-hash verified: SHA512(salt|status|udf10..udf1|email|firstname|productinfo|amount|txnid|key) must equal body.hash.
EASEBUZZ_BASE_URL = https://testpay.easebuzz.in. Context (loanId, paymentRequestId, paymentTransactionId, platformType, transactionType, web_hostname) is round-tripped through Easebuzz's udf1..udf6 fields. The callback redirect target is validated against PaymentService.isKnownBrandDomain() before being reflected into the HTML response — guards a reflected-XSS/open-redirect risk since udf6 (hostname) is brand-admin-controlled data echoed back by Easebuzz. Idempotency: skips update if transaction already not-SUCCESS-excluded / already APPROVED.A second Easebuzz product (merchant-initiated collection links) — separate base URL and create endpoint from the hosted-checkout product above, same key/salt.
{EASEBUZZ_EASYCOLLECT_BASE_URL}/easycollect/v1/create — create collection link (default base https://dashboard.easebuzz.in)src/features/payment/collection/providers/easebuzz-easycollect.service.ts
TriggerCollectionPaymentService.createPaymentOrder() for method=EASEBUZZ_EASYCOLLECT.
AuthSame SHA-512 hash scheme as Easebuzz but over key|merchant_txn|name|email|phone|amount|udf1..udf5|message|salt. EASEBUZZ_KEY/EASEBUZZ_SALT/EASEBUZZ_EASYCOLLECT_BASE_URL via BrandProviderKeyReader.
WebhookShares the EASEBUZZ webhook family — no separate callback route found; status presumably resolved through the same /payment/easebuzz/callback path (udf fields carry context) or polled.
+91/91 prefix) before being sent — Easebuzz requires this.Hosted payment-link checkout via PayU's OneAPI product.
{PAYU_ACCOUNTS_BASE_URL}/oauth/token — OAuth2 client-credentials token (default https://uat-accounts.payu.in){PAYU_ONEAPI_BASE_URL}/payment-links/ — create payment link (default https://uatoneapi.payu.in){PAYU_ONEAPI_BASE_URL}/payment-links/{invoiceNumber} — fetch link / check statussrc/features/payment/collection/providers/payu.service.ts
TriggerCollectionPaymentService.createPaymentOrder() for method=PAYU.
AuthOAuth2 client_credentials (PAYU_CLIENT_ID/PAYU_CLIENT_SECRET), token cached in-memory per client id until ~60s before expires_in. PAYU_MERCHANT_ID sent as mid/merchantId headers. All via BrandProviderKeyReader.
WebhookPOST /payment/payu/callback in payment.controller.ts → CollectionPaymentService.handlePayuCallback(). Signature: sha512(salt|status|udf10..udf1|email|firstname|productinfo|amount|txnid|key) against PAYU_MERCHANT_SALT — marked TODO/unverified; verification can be bypassed in UAT via PAYU_SKIP_WEBHOOK_VERIFY=true (service logs a loud warning when this is set and returns true unconditionally — must never be set in prod).
description field (rejects words like "loan" with errorCode 160) — the description is therefore a configurable env var (PAYU_LINK_DESCRIPTION, default "Repayment") rather than hardcoded. hasSuccessfulPayment's success-shape check is explicitly marked TODO/unconfirmed against live PayU docs.Hosted payment-link checkout, poll-based status (no documented webhook — status is fetched via fetchOrder).
{baseUrl}/api/v2/order/create — create order{baseUrl}/api/v2/order/fetch — fetch order / statussrc/features/payment/collection/providers/paytring.service.ts
TriggerCollectionPaymentService.createPaymentOrder() for method=PAYTRING.
AuthSHA-512 hash of sorted, pipe-joined request params + PAYTRING_PROD_KEY; Authorization: Basic {PAYTRING_API_TOKEN} header. All resolved via BrandProviderKeyReader.
WebhookPOST /payment/paytring/callback in payment.controller.ts → CollectionPaymentService.handlePaytringCallback(). This is a callback-triggers-a-fetch pattern, not a trust-the-payload webhook: the controller receives {order_id, receipt_id, key, hash} and the service then calls paytring.fetchOrder(externalRef) to get the authoritative order_status directly from Paytring, rather than trusting the posted status.
PAYTRING_BASE_URL = https://api.paytring.com. Internal context (PAN, loanId, paymentRequestId, paymentTransactionId, platformType, transactionType) carried in notes.udf1..udf6 on the order and validated present on callback before any DB write.Directory: src/features/payment/autopay/providers/ — Cashfree, Razorpay, PhonePe, implementing the shared IAutopayProvider interface (src/features/payment/autopay/providers/interfaces/autopay-provider.interface.ts). Orchestrator: AutopayService (src/features/payment/autopay/autopay.service.ts). Controller: AutopayCollectionController (src/features/payment/autopay/autopay.controller.ts, base route /payment-autopay).
createMandate(input: ICreateMandateInput): Promise<ICreateMandateResult> executeDebit(input: IExecuteDebitInput): Promise<IExecuteDebitResult> cancelMandate(subscriptionRef: string, brandId?: string): Promise<void>
brandProvider row of type=UPI_AUTOPAY per brand; isPrimary breaks ties if more than one is active. No per-loan/NBFC scoping (unlike collection's getCollectionProvider). Called at 3 sites in autopay.service.ts (mandate creation, and twice around debit execution after a successful consent).
Cashfree's v2 Subscriptions API — recurring, on-demand variable-amount UPI mandate for monthly EMI auto-debit.
{baseUrl}/api/v2/subscriptions/nonSeamless/subscription — create mandate (planInfo.type=ON_DEMAND){baseUrl}/api/v2/subscriptions/{subscriptionId}/charge — execute a debit{baseUrl}/api/v2/subscriptions/{subscriptionId}/cancel — cancel mandatesrc/features/payment/autopay/providers/cashfree-autopay.service.ts, .../interfaces/cashfree-autopay.interface.ts
TriggerPOST /payment-autopay/autopay-transaction → AutopayService.createAutopayTransaction(); POST /payment-autopay/recurring-payment → AutopayService.createRecurringPayment(). Both route here when resolveProvider() returns CASHFREE.
AuthHeaders X-Client-Id/X-Client-Secret from CASHFREE_AUTOPAY_APP_ID/CASHFREE_AUTOPAY_SECRET_KEY (distinct credential set from Cashfree collection), via BrandProviderKeyReader.resolve(brandId, "UPI_AUTOPAY", "CASHFREE", [...]).
WebhookPOST /payment-autopay/cashfree-autopay-webhook in autopay.controller.ts → AutopayService.handleCashfreeAutopayWebhook(). Parses SUBSCRIPTION.ACTIVE/CANCELLED/HALTED (mandate status) and SUBSCRIPTION_PAYMENT.SUCCESS/* (debit status) events via parseMandateWebhook/parsePaymentWebhook on the provider service.
CASHFREE_AUTOPAY_BASE_URL = https://test.cashfree.com. authAmount: 1 (₹1 token authorization) on mandate creation.Razorpay's UPI Recurring/Registration-Link API, frequency: "as_presented" — on-demand variable-amount debit with no bank-side fund block (chosen deliberately over one_time, which reserves max_amount against the customer's account).
{baseUrl}/subscription_registration/auth_links — create mandate (registration link){baseUrl}/orders — create order (pre-step for a debit){baseUrl}/customers/{customerId} — fetch customer{baseUrl}/payments/create/recurring — execute recurring debit (synchronous; no future-date scheduling on this endpoint){baseUrl}/customers/{customerId}/tokens/{tokenId}/cancel — cancel mandate token{baseUrl}/customers/{customerId}/tokens — list tokens (ops/debug tooling, not part of IAutopayProvider){baseUrl}/customers/{customerId}/tokens/{tokenId} — delete tokensrc/features/payment/autopay/providers/razorpay-autopay.service.ts
TriggerSame /payment-autopay/autopay-transaction and /payment-autopay/recurring-payment routes, when resolveProvider() returns RAZORPAY_AUTOPAY.
AuthHTTP Basic auth, RAZORPAY_KEY_ID/RAZORPAY_KEY_SECRET via BrandProviderKeyReader.resolve(brandId, "UPI_AUTOPAY", "RAZORPAY_AUTOPAY", [...]) (same key names as collection Razorpay account 1, but independently resolved per BrandProviderType).
WebhookPOST /payment-autopay/razorpay-autopay-webhook in autopay.controller.ts, header x-razorpay-signature → AutopayService.handleRazorpayAutopayWebhook(). RazorpayAutoPayService.verifyWebhookSignature() does HMAC-SHA256 against RAZORPAY_WEBHOOK_SECRET (shared with collection Razorpay's webhook secret).
https://api.razorpay.com/v1 is hardcoded, not env-driven. subscriptionRef is encoded as ${customerId}:${tokenId} — both halves are parsed back out for every debit/cancel call.PhonePe Standard/Custom Checkout Autopay — SUBSCRIPTION_SETUP flow, amountType: VARIABLE, frequency: ON_DEMAND, paymentMode: UPI_INTENT.
{oauthBaseUrl}/v1/oauth/token — OAuth2 client-credentials token (cached per client id, O-Bearer scheme){baseUrl}/subscriptions/v2/setup — create mandate (authWorkflowType: PENNY_DROP — TRANSACTION not provisioned on this merchant account per confirmed direct testing){baseUrl}/subscriptions/v2/{merchantSubscriptionId}/status?details=true — mandate status check (gates every debit — refuses if not ACTIVE){baseUrl}/subscriptions/v2/notify — notify/execute a redemption (debit), paymentFlow.autoDebit: true{baseUrl}/subscriptions/v2/redeem — follow-up explicit execute (implemented, not called anywhere yet — only needed if notify's autoDebit:true turns out not to auto-settle in practice){baseUrl}/subscriptions/v2/{subscriptionRef}/cancel — cancel mandatesrc/features/payment/autopay/providers/phonepe-autopay.service.ts, .../interfaces/phonepe-autopay.interface.ts, module wiring in .../autopay-providers.module.ts
TriggerSame /payment-autopay/autopay-transaction / /payment-autopay/recurring-payment routes, resolveProvider() → PHONEPE_AUTOPAY. Mandate creation + persistence + notification is wrapped end-to-end in PhonePeAutoPayService.createAndPersistMandate() (not a bare IAutopayProvider.createMandate call) because PhonePe returns a raw upi:// deep link that SMS/email clients can't linkify — this method also sends the SMS/email with a server-hosted https:// redirect wrapper.
AuthOAuth2 client_credentials (PHONEPE_CLIENT_ID/PHONEPE_CLIENT_SECRET/PHONEPE_CLIENT_VERSION), PHONEPE_MERCHANT_ID header, via BrandProviderKeyReader.resolve(brandId, "UPI_AUTOPAY", "PHONEPE_AUTOPAY", [...]).
WebhookPOST /payment-autopay/phonepe-autopay-webhook in autopay.controller.ts, header authorization → AutopayService.handlePhonePeAutopayWebhook(). Auth checked via PhonePeAutoPayService.verifyWebhookAuth() — SHA-256 of {PHONEPE_WEBHOOK_USERNAME}:{PHONEPE_WEBHOOK_PASSWORD} compared to the incoming header (not HMAC-of-body; a fixed shared-secret digest).
PHONEPE_BASE_URL / PHONEPE_OAUTH_BASE_URL = https://api-preprod.phonepe.com/apis/pg-sandbox. maxAmount sent to PhonePe = largestEmi * 1.20 (PHONEPE_MANDATE_BUFFER_PCT), uncapped — PhonePe's own account ceiling (confirmed ₹15,000 via direct testing) rejects anything above it rather than the code clamping it, per explicit instruction in the source. The GET /payment-autopay/phonepe/redirect/:autopayTxnId route (public) is the wrapper landing page that redirects into the real upi:// intent. Module boundary: PhonePeAutoPayService lives in its own AutopayProvidersModule (not PaymentModule) specifically to avoid a circular import: EsignModule → PaymentModule → LoansModule → LoanApplicationModule → EsignModule. Cashfree/Razorpay autopay mandate creation is separately duplicated inside EsignService for the same reason — a known follow-up, not yet extracted.Directory: src/features/payment/disbursement/providers/ — HDFC (+ a hdfc-jose/ crypto sub-folder), YES Bank, ICICI (3 concurrent versions: v1/v2/v3), IDFC (2 concurrent versions: v1/v2). Confirmed present, no other banks.
hdfc-jose/ is vendored byte-for-byte from HDFC's own official @hdfc-cbx/jose-utility Node reference package (confirmed against HDFC's published test vectors), not a hand-rolled implementation — exports encryptRequest/decryptResponse (partner-crypto-util.ts), RSA-OAEP+AES-GCM primitives (rsa-oaep-with-aes-gcm.ts), key utilities (key-utils.ts), and base64url helpers (base64url.ts).
CorpPay single/bulk fund transfer (NEFT/IMPS/RTGS) for borrower/lender payout. Asynchronous: the initiate call only ever Acks, the real outcome is learned later via a status-inquiry call.
{HDFC_OAUTH_TOKEN_URL} — OAuth2 token (default https://api.hdfcuat.bank.in/auth/oauth/v1/token), deliberately fetched fresh before every single call — HDFC's UAT gateway rejects a reused token even ~1s later, confirmed by isolated testing; do not cache{HDFC_INITIATE_PAYMENT_URL} — initiate transfer (default https://api.hdfcuat.bank.in/api/v1/corp-initiatePayment); application/jose body (JWE); response is {Transaction: "Accepted"} only — an Ack, not a result{HDFC_GET_INQUIRY_URL} — CBX_GetInquiry (default https://api.hdfcuat.bank.in/api/v1/corp-paymentInq), the only way to learn SUCCESS/FAILEDsrc/features/payment/disbursement/providers/hdfc.disbursement.service.ts (HDFCProvider), src/features/payment/disbursement/providers/hdfc-jose/*
TriggerPOST /payment/disburse-transaction → DisbursementPaymentService.handleDisbursementTransaction(..., provider: "HDFC", ...); also reached per-leg from DisbursementLegDispatcherService.sendViaHdfc() for debt-consolidation batches.
AuthOAuth2 client_credentials (HDFC_API_KEY/HDFC_API_SECRET/HDFC_API_SCOPE), mTLS client cert/key (HDFC_CLIENT_CERT_PATH/HDFC_CLIENT_KEY_PATH, via an undici Agent since Node 22's global fetch is undici-based), plus the JOSE key trio (HDFC_JOSE_PRIVATE_KEY_PATH/HDFC_JOSE_PUBLIC_KEY_PATH/HDFC_JOSE_BANK_PUBLIC_KEY_PATH). All via BrandProviderKeyReader.resolve(brandId, "DISBURSEMENT", "HDFC", [...]).
WebhookNone. HDFC has no callback mechanism at all — confirmed explicitly in the cron's own doc comment. HDFCStatusPollCronService (src/core/cron/services/hdfc-status-poll-cron.service.ts) is the only mechanism that ever learns the real outcome: runs @Cron(CronExpression.EVERY_5_MINUTES), calls HDFCProvider.pollPendingDisbursements(), which polls corp-paymentInq for every HDFC PDT PENDING and older than 5 minutes (take 50 per run). A terminal success OD_STATUS (TXCOMP/TXSETT/TXDSETT/TXPDST/TXVLSU) finalizes via settleDisbursementSuccess (PDT → SUCCESS with UTR in externalRef, payment request → SUCCESS, loan → ACTIVE, ledger recorded, post-disbursement events fired); a terminal failure code fails it; anything else stays PENDING (alerts in logs after 2 days, never auto-fails).
initiateTransfer() also schedules a one-off early status check 30s after Ack (scheduleEarlyStatusCheck) as a UX nicety — the 5-minute cron remains the real safety net regardless. Settlement is made idempotent via a conditional updateMany({ where: { id, status: PENDING } }) claim (claim.count === 0 → another caller already settled it) rather than a plain read-then-write, specifically because a prior read-based check let the same loan get double-ledgered.FTx (v1.4.2) IMPS/NEFT fund transfer API.
{YES_BANK_FTX_BASE_URL}/Payments/PayReq — initiate transfer (ftxPayReq), acceptance is always PENDING (async){YES_BANK_FTX_BASE_URL}/Payments/GetStatus — status inquiry (ftxGetStatus){YES_BANK_FTX_BASE_URL}/Payments/GetBalance — account balance (ftxGetBalance)src/features/payment/disbursement/providers/yesbank.disbursement.service.ts (YesBankProvider)
TriggerPOST /payment/disburse-transaction with provider: "YES_BANK", or per-leg via DisbursementLegDispatcherService — note: the dispatcher's send() switch only explicitly handles IDFC and HDFC, falling through to ICICI for everything else, so YES Bank legs are not wired into the multi-leg dispatcher; YES Bank disbursement is single-leg/non-consolidation only, via DisbursementPaymentService directly.
AuthHTTP Basic auth (YES_BANK_USER_ID/YES_BANK_PASSCODE) + IBM API Gateway headers (X-IBM-Client-Id/X-IBM-Client-Secret) + mTLS (YES_BANK_SSL_CERT_PATH/YES_BANK_SSL_KEY_PATH/YES_BANK_SSL_CA_PATH, cached AxiosInstance per cert/key/ca triple) + optional request hashing (SHA-256, YES_BANK_HASH_SECRET_KEY, gated by YES_BANK_HASH_ENABLED) + optional full-body AES-256-CBC encryption (YES_BANK_ENCRYPTION_KEY, gated by YES_BANK_ENCRYPTION_ENABLED; IV-prepended ciphertext, base64). All via BrandProviderKeyReader.resolve(brandId, "DISBURSEMENT", "YES_BANK", [...]).
WebhookPOST /webhooks/yesbank/ftx-callback in src/features/payment/disbursement/yesbank-callback.controller.ts (YesBankCallbackController, @AuthType("public") + manual HTTP Basic auth check against YES_BANK_CALLBACK_USERNAME/YES_BANK_CALLBACK_PASSWORD, separate from the outbound PayReq credentials). Bank pushes ftxPayCallback once a transaction reaches a final state, retrying up to 3× if not ack'd with 200. Always returns HTTP 200 (even on internal processing error) so the bank doesn't hammer retries for our-side bugs — the cron is the safety net for a callback that never lands correctly.
YES_BANK_FTX_BASE_URL — must be configured. This is the only provider with both a webhook (primary path) and a polling cron (pollPendingDisbursements, safety net, PDTs eligible once 10 minutes old) sharing one applyStatusResult() finalization function — guarantees identical logic regardless of which path resolves a given PDT, and that function is itself idempotent (status !== PENDING → no-op). Bank action-codes are mapped to one of PENDING/ALERT/FAILED via mapActionCodeToOutcome — ALERT outcomes (credential/mTLS-type errors) are logged loudly for ops but kept PENDING, never auto-failed, since they're not a property of the individual transaction.Corporate Internet Banking (CIB) fund transfer, AES/RSA-OAEP encrypted payload. Three versions exist concurrently in the codebase (distinct BrandProviderNames ICICI/ICICI_V2/ICICI_V3, independently brand-configurable) — v1/v2 use the legacy "composite-payment" API, v3 uses the newer CIB Transaction API with a richer inquiry surface.
https://apibankingone.icici.bank.in/api/v1/composite-payment — v1/v2 initiate transfer (ICICI_COMPOSITE_PAYMENT_URL)https://apibankingone.icici.bank.in/api/v1/composite-status — v1/v2 status check (ICICI_COMPOSITE_STATUS_URL)https://apibankingone.icici.bank.in/api/Corporate/CIB/v1/Transaction — v3 initiate transfer (ICICI_CIB_TRANSACTION_URL)https://apibankingone.icici.bank.in/api/Corporate/CIB/v1/TransactionInquiry — v3 status inquiry (ICICI_CIB_TRANSACTION_INQUIRY_URL)https://apibankingone.icici.bank.in/api/v1/CIBNEFTStatus — v3 incremental NEFT status (ICICI_CIB_NEFT_INCREMENTAL_STATUS_URL)src/features/payment/disbursement/providers/icici.disbursement.service.ts (ICICIProvider, v1), icici.disbursement.v2.service.ts (ICICIProviderV2), icici.disbursement.v3.service.ts (ICICIProviderV3)
TriggerPOST /payment/disburse-transaction with provider: "ICICI" | "ICICI_V2" | "ICICI_V3"; also the multi-leg dispatcher's default branch (DisbursementLegDispatcherService.sendViaIcici) — i.e. ICICI is the fallback rail for any disbursement-leg provider that isn't explicitly IDFC or HDFC.
AuthRequest/response bodies are RSA-OAEP-key-wrapped + AES-encrypted (encryptPayload/CIBEncryptedRequest envelope: encryptedKey, iv, encryptedData). Credentials ICICI_CRP_ID/ICICI_CRP_USER/ICICI_AGGR_ID/ICICI_AGGR_NAME/ICICI_URN/ICICI_DEBIT_ACCOUNT_NO (+ v1/v2-only ICICI_API_KEY/ICICI_MOBILE/ICICI_IMPS_PASSCODE/ICICI_IMPS_BCID/ICICI_IMPS_RETAILER_CODE), via BrandProviderKeyReader.resolve(brandId, "DISBURSEMENT", "ICICI"|"ICICI_V2"|"ICICI_V3", [...]).
WebhookNone found for ICICI specifically — status is pulled via the inquiry endpoints above, both on-demand (from DisbursementReconcilerService) and (implicitly) via the same multi-leg completion-gate flow.
initiateTransferWithFallback (v3) / the dispatcher's settled-check accepts a specific ActCode allow-list (["0","1","68","92","95","96","97"]) as success — deliberately kept identical between the single-leg and multi-leg code paths "so two disbursement code paths disagreeing about what 'paid' means is exactly the drift this engine exists to remove" (source comment).Generic Fund Transfer API (NEFT/IMPS), OAuth2 + JWT-signed auth, AES-encrypted payload fields.
{IDFC_AUTH_URL} — OAuth token (client credentials + JWT assertion: IDFC_CLIENT_ID/IDFC_AUDIENCE/IDFC_KID/IDFC_SCOPE); v2 caches the token in Postgres (paymentAuthState singleton row, IDFCProviderV2.SINGLETON_ID) with a cross-process lock (isLocked/retryCount) rather than in-memory — needed because multiple worker processes share one IDFC OAuth session{IDFC_BASE_URL}/... — initiateAuthGenericFundTransferAPIReq (fund transfer), paymentTransactionStatusReq (status), beneficiary validation, balance check (exact sub-paths not fully enumerated in this pass — base path assembled with IDFC_SOURCE)src/features/payment/disbursement/providers/idfc.disbursement.service.ts (IDFCProvider, v1), idfc.disbursement.v2.service.ts (IDFCProviderV2)
TriggerPOST /payment/disburse-transaction with provider: "IDFC" | "IDFC_V2"; also explicitly handled in the multi-leg dispatcher (DisbursementLegDispatcherService.sendViaIdfc).
AuthOAuth2 + JWT (IDFC_CLIENT_ID/IDFC_AUDIENCE/IDFC_KID/IDFC_SCOPE), AES payload encryption (IDFC_AES_KEY), IDFC_DEBIT_ACCOUNT/IDFC_IFSC_CODE. v2's token-fetch logic retries up to MAX_401_RETRIES = 4 and reads key material from /home/ubuntu/secure-keys (SECURE_KEYS_DIR). Via BrandProviderKeyReader.resolve(brandId, "DISBURSEMENT", "IDFC"|"IDFC_V2", [...]).
WebhookNone found — status resolved via paymentTransactionStatusReq inquiry, pulled by the reconciler/dispatcher.
NPCI: ZI as a success, not a failure (res?.data?.metaData?.code === "NPCI: ZI" is OR'd into the settled check) — a known IDFC quirk where that specific error code actually means the credit went through.The most notable non-obvious business logic in the payments module: how a single disbursement fans out into multiple bank-rail calls, and how the system refuses to guess when a bank call's outcome is ambiguous.
src/features/payment/disbursement/disbursement-payment.service.ts (single/bulk path, DisbursementPaymentService.handleDisbursementTransaction), disbursement-leg-dispatcher.service.ts (multi-leg async dispatcher, DisbursementLegDispatcherService), disbursement-batch.service.ts, disbursement-batch.controller.ts (partner/brand/:brandId/loans/:loanId/disbursement), disbursement.types.ts, disbursement-provider.util.ts, disbursement-reconciler.service.ts
TriggerSingle-leg: POST /payment/disburse-transaction in payment.controller.ts → DisbursementPaymentService.handleDisbursementTransaction(). Dispatches by provider param among "IDFC" | "IDFC_V2" | "ICICI" | "ICICI_V2" | "ICICI_V3" | "HDFC" | "LENDBOX" | "YES_BANK", or falls back to ProviderRegistryService.forMethod(method) when no explicit provider is given. Requires confirmPassword (a secure code) for any non-system-initiated provider disbursement, and supports an x-idempotency-key header: a row in idempotencyKey (status PROCESSING→COMPLETED) prevents a duplicate disbursement if the same request is retried — a PROCESSING key in flight throws ConflictException rather than re-sending.
A disbursement is a BATCH (payment_request row) made of LEGS (payment_disbursal_transaction rows, one each). A standard personal loan is a batch of exactly one leg (to the borrower). A debt-consolidation loan is a batch with one leg per selected loan_consolidation_lines row (paying off each external lender directly) plus one leg for the borrower's own residual balance. The loan only moves to ACTIVE once every leg in the batch has settled (DisbursementBatchService.runCompletionGate).
LENDER (external payoff, from lender_bank_accounts) or BORROWER (customer's own account, from user_bank_account).LENDER = 0, BORROWER = 1 — legs sharing an index run concurrently; a leg is only claimable once every lower-index leg in its batch has SUCCEEDED. This guarantees lenders are always paid off before the borrower receives any residual cash — a failed lender payoff can never leave the borrower holding funds for debts that are still outstanding.DisbursementLegDispatcherService treats payment_disbursal_transaction rows in PENDING/RETRYING as the queue itself, claimed via FOR UPDATE SKIP LOCKED so multiple worker processes never collide (MAX_IN_FLIGHT = 5 legs per poll per worker). Only runs when CRON_WORKER=true and at least one brand has is_debt_consolidation_enabled; otherwise the loop idles without ever touching the table.method on the leg at plan/retry time) wins; otherwise the brand's isPrimary DISBURSEMENT-type brandProvider is resolved at send time (not at plan time), so a provider toggled off mid-queue is never used and one toggled on takes effect immediately. The dispatcher's own send() switch explicitly branches IDFC/IDFC_V2 → sendViaIdfc, HDFC → sendViaHdfc, and everything else falls through to sendViaIcici (so YES Bank is not a valid multi-leg provider today).LegOutcomeKind deliberately has four states, not two. classifyThrow() in the dispatcher — commented in the source as "the most important twenty lines" — is what draws the line: an HTTP 4xx (the bank spoke and explicitly refused) is REJECTED; anything else (timeout, 5xx, DNS failure, garbled body) is UNKNOWN, because the money may actually have moved and retrying could pay twice.
| Outcome | What it means | Dispatch action (PaymentStateMachine.actionFor()) |
|---|---|---|
SETTLED |
Provider unambiguously confirmed success. | SETTLE_AND_GATE — leg marked SUCCESS, batch completion gate re-evaluated. |
REJECTED |
Provider explicitly spoke and refused (e.g. a clean 4xx) — no money moved. Safe to retry or terminally fail. | SETTLE_AND_GATE — leg marked FAILED, batch completion gate re-evaluated. |
UNKNOWN |
Timeout / 5xx / connection reset / unparseable body. Money may have moved — retrying could pay twice. | RECONCILE — left INITIATED, handed to DisbursementReconcilerService, never auto-retried. |
NOT_SENT |
The pre-send DB write that records "about to attempt X" itself failed — nothing was actually sent to the bank. Distinct from UNKNOWN on purpose. |
RELEASE — safe to release back to the queue immediately. |
DisbursementReconcilerService (cron) is the sole resolver of UNKNOWN/INITIATED legs, and only ever settles on an unambiguous success from the provider's own status-inquiry call — it explicitly documents that it "never auto-fails" because, e.g., ICICI's status endpoint returns the same "not successful" shape for a genuine rejection and for a transaction the bank just hasn't processed yet. This UNKNOWN/INITIATED state is this codebase's NEEDS_REVIEW-equivalent principle for money movement — no literal NEEDS_REVIEW enum exists; this is the mechanism that plays that role.
Manual legs: MANUAL is a real leg "provider" — a human makes the transfer in the bank's own portal and records the UTR via POST .../legs/:legId/settle on DisbursementBatchController. The dispatcher's claim query excludes MANUAL legs; if one is ever claimed in error it is released, never sent.
Full co-lending integration with Lendbox as an NBFC partner: borrower onboarding/credit decisioning handoff, e-sign, document upload, loan creation on Lendbox's books, wallet-order based repayment sync, and disbursal UTR confirmation — all keyed by a Lendbox-assigned lbUserId/lbLoanId.
{baseUrl}/borrower/signup?productType=... — borrower signup (credit-check/onboarding handoff){baseUrl.v3}/borrower/bank-details/secondary — secondary bank details (version-swapped path, /v1/.../v3/...){baseUrl}/create-loan?lbUserId=... — create the loan on Lendbox's books{baseUrl}/e-sign/verify?lbUserId=... — e-sign verification{baseUrl}/upload/docs?lbUserId=... — document upload{baseUrl}/webhooks/los — register this platform's webhook URL with Lendbox (LendboxOpenWebhookService; doc comment says "Endpoint: POST {baseUrl}/v1/partners/webhooks/los"){baseUrl}/wallet/orders — submit a wallet order (collection/repayment sync){baseUrl}/wallet/orders/status — check wallet-order/transaction status{baseUrl}/borrower-rps?loanId=... — repayment schedule{baseUrl}/loan/foreclosure — foreclosure amount (params lbUserId, lbLoanId, foreclosureDate){baseUrl}/download-noc — NOC document, param lbLoanId (pre-signed S3 URL response){baseUrl}/fetch/lbuserid — resolve Lendbox user id{baseUrl}/get-uploaded-docs — list uploaded docs{baseUrl}/user/loan/status — update loan status on Lendbox's sidesrc/features/lendbox-v1/ — key files: providers/lendbox.provider.ts (DI wiring/factories for every sub-service, each reading LENDBOX_BASE_URL/LENDBOX_API_KEY/LENDBOX_API_CODE, default base https://api.lendbox.com), services/lendbox-borrower.service.ts, services/lendbox-loan-creation.service.ts, services/lendbox-esign.service.ts, services/lendbox-document-upload.service.ts, services/lendbox-wallet-orders.service.ts, services/lendbox-transaction-status.service.ts, services/lendbox-get-borrower-rps.service.ts, services/lendbox-foreclosure-amount.service.ts, services/lendbox-download-noc.service.ts, services/lendbox-fetch-lbuserid.service.ts, services/lendbox-update-loan-status.service.ts, services/lendbox-get-uploaded-docs-list.service.ts, services/lendbox-disbursal-utr.service.ts (webhook handler), services/lendbox-credit-order-callback.service.ts (webhook handler), services/lendbox-payment-order-builder.service.ts (builds wallet-order payloads from internal collection transactions), controllers/lendbox-disbursal-utr.controller.ts, controllers/lendbox-credit-utr.controller.ts, controllers/lendbox-workflow.controller.ts.
TriggerPOST /payment/lendbox-sync and POST /payment/lendbox-status in payment.controller.ts → CollectionPaymentService.syncLendboxPayment() / checkLendboxPaymentStatus() (ops-triggered repayment reconciliation). Loan creation / borrower onboarding / e-sign steps are invoked from deeper in the loan-application and e-sign flows (not re-traced in this pass).
AuthLENDBOX_API_KEY/LENDBOX_API_CODE headers (x-api-key/x-api-code), resolved via BrandProviderKeyReader.resolve(brandId, "DISBURSEMENT", "LENDBOX", ["LENDBOX_BASE_URL","LENDBOX_API_KEY","LENDBOX_API_CODE"]) — keyed under DISBURSEMENT/LENDBOX even though Lendbox is a co-lending/credit partner, not a bank rail, reflecting that Lendbox disbursal is one of the provider choices in DisbursementPaymentService.handleDisbursementTransaction.
WebhookPOST /lendbox/webhook/disbursal-utr in controllers/lendbox-disbursal-utr.controller.ts (LendboxDisbursalUTRWebhookController, @AuthType("public")) — disbursal success/failure/pending + UTR, header x-lb-signature required (400 if missing) → LendboxDisbursalUTRCallbackService.handleDisbursalUTRCallback(). POST /lendbox/webhook/credit-order in controllers/lendbox-credit-utr.controller.ts (LendboxCreditOrderWebhookController, @AuthType("public")) — credit order (repayment) success/failure/pending, same x-lb-signature requirement → LendboxCreditOrderCallbackService.processCreditOrderCallback(). Both controllers also expose POST .../health for webhook-service health checks, and both wrap processing in try/catch returning a structured {status, message, txId, acknowledged:false, error} body rather than throwing, except when the signature header itself is missing (hard 400).
LendboxWalletOrdersService/LendboxTransactionStatusService are the pieces CollectionPaymentService actually depends on directly (per its constructor) for repayment sync — i.e. Lendbox is used both as a disbursal rail (loan funding via create-loan) and as a collections-sync target (wallet orders mirror this platform's own collected repayments back to Lendbox's ledger, since Lendbox co-funds the loan and needs its own repayment records).LenderOptionsService (src/app/partner/lender-options/lender-options.service.ts) is the searchable picker over the two "lender" masters — masterNBFC and masterBank — merged, searched (by lender name or by owned bank-account details: number/IFSC/holder/bank name/UPI id/brand name) and paged in a single Postgres UNION query, with results cached in Redis (lender-options:v1:*, 120s TTL by default via LENDER_OPTIONS_CACHE_TTL). This is what populates the lender-selection dropdown a debt-consolidation operator uses to pick which existing lender a loan_consolidation_lines leg should pay off — i.e. it is the human-facing config surface that ultimately determines the destKind=LENDER legs documented above, but it makes no outbound HTTP calls itself (pure Prisma/Redis). Module: lender-options.service.ts; src/app/partner/settings/lenderBankAccount/lender-bank-account.service.ts (LenderBankAccountService, CRUD over lenderBankAccount rows). When ops adds/edits a LenderBankAccount, LenderBankAccountService calls into PennyDropService (src/external/pennyDrop/pennyDrop.service.ts — covered on the KYC & e-Sign page, not a Group C provider) to verify the account/IFSC is a real, name-matched bank account before it can ever be selected as a disbursement leg destination — a verification step, not a money-movement call; the actual payout still goes through HDFC/ICICI/IDFC/YES Bank/Lendbox as documented above. No webhook — purely a request/response config API consumed by the partner-ops frontend.
Cross-cutting plumbing underneath every provider on this page — not a vendor itself, but the mechanism that makes "which credential, which URL, what happened to this leg" answerable in one place rather than per-integration.
brand-provider-key-catalog.tssrc/core/brand-provider-keys/brand-provider-key-catalog.ts defines PROVIDER_KEY_CATALOG, a static map keyed by ${BrandProviderType}/${BrandProviderName} (e.g. "FULL_PAYMENT/CASHFREE", "DISBURSEMENT/HDFC", "UPI_AUTOPAY/PHONEPE_AUTOPAY"). Each entry lists the exact env-var-named keys that a brand is allowed to override for that (type, provider) pair, plus an optional baseUrlKey naming which of those keys a health check should treat as the base URL to probe when no dedicated HEALTH_URL/BASE_URL key exists. This single catalog spans every external integration in the codebase — payments, disbursement, bureau pulls, KYC/verification, account aggregation, e-sign/e-stamp, communication/telephony — not just the payment providers on this page; it is the authoritative list of "which env vars can this (type, provider) combination be brand-overridden on."
The actual runtime resolution is BrandProviderKeyReader (src/core/brand-provider-keys/brand-provider-key-reader.service.ts), which every provider service on this page calls as providerKeys.resolve(brandId, type, providerName, [ENV_VAR_NAMES...]). For each requested name, it returns the brand's own saved value if one exists (a live, active, non-disabled brandProvider row for that (brandId, type, provider), primary-first, then most-recently-updated, with its child brandProviderKey rows decrypted via CryptoService — encrypted values use crypto.decrypt(), a failed decrypt is logged and skipped rather than thrown), and otherwise falls back to process.env[name] — so an unconfigured brand behaves exactly as a single-tenant env-var deployment always did, and a brand only diverges once ops explicitly saves a brand-specific key. Results are cached in-process for 30 seconds per (brandId, type, provider) key, invalidated explicitly via invalidate(brandId) after a settings save (so a credential rotation takes effect within 30s, not instantly, if the invalidation call is missed).
.resolve() with their own BrandProviderType (FULL_PAYMENT/PART_PAYMENT for collection, UPI_AUTOPAY for autopay, DISBURSEMENT for banking rails and Lendbox) and BrandProviderName, then fall back to a hardcoded sandbox/UAT default URL (where one exists) if neither the brand row nor process.env supplies a base URL — this is why nearly every getConfig()/config() method in these services has an inline || "https://..." default visible in the code.
src/features/payment/orchestration/A small but load-bearing layer sitting above the three money-movement surfaces (collection, autopay, disbursement):
provider-registry.service.ts) — merges COLLECTION_PAYMENT_PROVIDERS and DISBURSEMENT_PAYMENT_PROVIDERS into one Map<BrandProviderName, PaymentProviderRegistration>, each entry declaring its method (the PaymentMethodEnum it maps to) and its capabilities (a Set<PaymentProviderCapability>, e.g. COLLECTION/DISBURSEMENT). forMethod()/supports()/list() are the lookup surface other services use instead of hardcoding provider↔method tables themselves.provider-router.service.ts, .route()) — a capability-aware router: given a { brandId, provider?, method?, capability } request, resolves to a BrandProviderName or null, falling back to the brand's primary DISBURSEMENT-type brandProvider row when no explicit provider/method is given. Used by DisbursementLegDispatcherService.resolveProvider() when available (optional injection — falls back to a simpler providerForMethod() lookup if the router isn't wired in a given deployment).payment-state-machine.ts) — the LegOutcomeKind → PaymentDispatchAction mapping documented in the debt-consolidation section above, centralizing the "never guess on an ambiguous outcome" rule in one place rather than re-implementing it per bank integration.payment-event-bus.service.ts) — a minimal in-process pub/sub (payment.leg.outcome, payment.batch.activated) decoupling the dispatcher from whatever eventually needs to react to a leg/batch outcome.src/features/payment/shared/dto/ holds cross-cutting DTOs (e.g. BrandIdQueryDto) used by both collection and disbursement controllers.CollectionPaymentService.getCollectionProvider, AutopayService.resolveProvider) rather than routing everything through ProviderRouterService — the orchestration layer reads as a newer, partially-adopted abstraction rather than a mechanism every payment path already goes through uniformly.