Payment gateway settlements
Why this exists
Marketplace orders (Amazon, Flipkart, Meesho, Shopify with Shopify Payments) are paid out through settlement reports with one line per order item. Those reconcile in the order-line engine described in Settlements.
D2C store orders (WooCommerce, BigCommerce, Shopify on a third-party gateway, manual orders) are paid through a payment gateway or COD. They never appear on a settlement report. Their money trail is:
Gateway payouts are ordinary rows on the shared payout spine (Payout with source = PAYMENT_GATEWAY), so bank matching, the journal and the dashboards treat them like any other payout. COD is covered by courier remittances (Settlements).
Supported gateways
| Gateway | Code | Mode | Credentials | Source |
|---|---|---|---|---|
| Razorpay | razorpay | API | keyId, keySecret | Settlement recon report, month by month (SDK settlements.reports) |
| Cashfree Payments | cashfree | API | clientId, clientSecret | POST /pg/settlement/recon, cursor paging |
| PayU | payu | API | merchantKey, merchantSalt | postservice.php command get_settlement_details, one call per day, SHA-512 hash |
| Paytm Payments | paytm | API | mid, clientId, clientSecret | merchant-settlement/SettlementDetail, 7-day windows, HS256 JWT |
| Stripe | stripe | API | secretKey | Paid payouts, then balance_transactions?payout= per payout |
| PayPal | paypal | API | clientId, clientSecret | /v1/reporting/transactions, 31-day windows, OAuth client credentials |
| PhonePe, CCAvenue, Easebuzz, Instamojo, Pine Labs, Juspay | phonepe … juspay | File | none | Tenant uploads the gateway's settlement export |
Descriptors (label, mode, credential fields) are declared on each adapter and listed by GET /finance/gateway-settlements/gateways. The admin connect form is generated from them.
Razorpay, Stripe and PayPal follow documented, stable responses. Cashfree, PayU and Paytm were mapped from public documentation and read several candidate field names tolerantly. Run one live month sync per gateway before relying on their numbers. See Open questions.
Shopify Payments payouts stay on the marketplace settlement path. If a gateway line resolves to an order paid with Shopify Payments, its resolution is NOT_APPLICABLE and it settles nothing, so the same cash is never counted twice. See settlement-channel.util.ts.
Code map
| Piece | Path |
|---|---|
| Payment accounts (feature) | src/modules/finance/payment-account/ — PaymentAccountService (CRUD), PaymentAccountSyncStateService (what to sync, outcomes, circuit breaker), tenant and platform-admin controllers |
| Port | payment-account/ports/payment-gateway.port.ts — PAYMENT_GATEWAY_PORT, batch, payout and line shapes |
| Registry (implements the port) | payment-gateway.registry.ts — verifies and stores credentials, fetches settlements |
| Adapters | src/integrations/payments/gateways/ — one *.adapter.ts per API gateway, file-import.gateways.ts for file-only descriptors, payment-gateway-adapter.ts for the shared HTTP helper |
| Sync orchestration | gateway-settlement-sync.service.ts |
| Import and matching | gateway-settlement-import.service.ts, pure rules in gateway-settlement-line.util.ts |
| File import | gateway-settlement-file.service.ts |
| Controller (day-to-day) | gateway-settlement.controller.ts |
| Worker / scheduler | gateway-settlement.processor.ts, gateway-settlement.scheduler.ts |
| Channel payment references | channel-payment-reference.service.ts, payment-gateway.util.ts |
| Schema | 55-finance-accounts.prisma (PaymentAccount), 51-settlement.prisma (Payout, PayoutLine, PayoutLineResolution), 54-reconciliation-ops.prisma (GatewaySettlementMapping) |
| Admin | Connect: src/components/integrations/connectors/payment/ (App Directory → Payments) and My Integrations. Reconcile: src/features/settlements/components/payment-account*.tsx, gateway-*.tsx (Settlements → Payouts → Payment gateway). Shared API: src/lib/finance-accounts/ |
Dependencies run one way: finance/settlement → finance/payment-account → port ← src/integrations/payments. Settlement never owns accounts and payment-account never imports settlement. Gateway SDKs, HTTP calls and credentials stay inside src/integrations/payments. See ADR-0004.
Step 1: payment references on order import
Matching needs the gateway's payment id on the order. Shopify and WooCommerce order imports record it as an OrderPaymentTransaction (type SALE, status SUCCEEDED).
- Shopify: the order GraphQL query reads
transactions. Only successfulSALE/CAPTUREtransactions from a recognised gateway are kept (toShopifyPaymentReferences). The payment id comes fromauthorizationCodeor the gateway receipt. - WooCommerce:
payment_methodplustransaction_idanddate_paid_gmt(toWooCommercePaymentReferences). normalizePaymentGatewaymaps channel gateway names to the codes above. COD, bank transfer, manual and gift-card methods map tonulland are not recorded.ChannelPaymentReferenceService.recordis idempotent per order and payment (channel:{orderId}:{provider}:{paymentId}). A payment id already recorded on another order is left alone, because(provider, providerTransactionId)is unique across the platform.
Orders imported before this existed get their references on the next order sync. A manual order sync with no date filter re-reads them.
paidAmount on the order is not derived from these rows.
Step 2: payment accounts
A PaymentAccount is the tenant's merchant account at one gateway, connected from Integrations → App Directory → Payments, like a channel or courier. It owns its IntegrationConnection through connectionId; settlement lines, payouts, saved file mappings and (once known) order payments reference the account by id.
| Field | Meaning |
|---|---|
type | Registry code, e.g. RAZORPAY. Settlement data uses the lower-case form (provider = 'razorpay') |
code | Tenant-unique slug. Derived from the type when omitted; a second account of the same gateway gets RAZORPAY-2 |
syncMode | API (credentials stored, synced daily) or FILE (no connection; settlement exports are imported) |
status | ACTIVE, INACTIVE (a person turned it off) or SUSPENDED (circuit breaker, after 5 consecutive failed syncs). Same rule as channels (ADR-0002) |
lastSettlementSync, lastSyncError, lastSyncSummary, consecutiveFailures | Sync health shown on the account |
Creating or updating an API account with credentials (POST /finance/payment-accounts, PUT /finance/payment-accounts/:id):
- The registry keeps only the fields the gateway descriptor declares and trims them.
- The adapter's
verifymakes the cheapest authenticated call. A 401/403 from the gateway becomes 422 "X rejected the credentials" (not 401, which the admin treats as an expired session). Other failures are 502. - Credentials go into an
IntegrationConnection(integrationCode = type) throughIntegrationConnectionService, envelope-encrypted; an update replaces the credentials on the same connection. The account'sconfigholds onlykeyIdHint(last four characters of the first non-secret field). - New credentials clear the circuit breaker:
consecutiveFailures = 0, and aSUSPENDEDaccount returns toACTIVE.
Deleting an account soft-deletes it (history references it), renames its code so it can be reused, and removes the stored credentials. One gateway account commonly serves several stores, so accounts are deliberately not tied to channels; see Step 4.
Account creation needs an active IntegrationRegistry row with category payment. Rows for RAZORPAY, CASHFREE, PAYU, PAYTM, STRIPE, PAYPAL and the file gateways PHONEPE, CCAVENUE, EASEBUZZ, INSTAMOJO, PINELABS, JUSPAY live in integration-registry.seed.ts. An existing database only gets them when the seed runs.
Credentials are decrypted only inside the worker job, through ConnectorContextResolver.resolveConnectionContext(connectionId).
Step 3: syncing
- Job name
gateway-synconsettlement_queue, concurrency 2. The payload carries the account id and dates, never credentials. jobIdisgateway-sync:{paymentAccountId}:{fromDay}:{toDay}, so identical pending requests collapse.removeOnCompleteandremoveOnFailare both true: a retained failed job with the same id would make Bull silently ignore a manual retry.- 2 attempts, exponential backoff from 60s. A failure is written to the account (
lastSyncError,consecutiveFailures + 1) and rethrown so Bull retries. The fifth consecutive failure moves anACTIVEaccount toSUSPENDED; anINACTIVEaccount is never changed. - The scheduler runs at 05:00 in system context (after the 04:00 COD remittance pull) and covers the previous 10 days, because gateways settle T+1 to T+3 and occasionally amend.
POST /accounts/:accountId/syncwith{ year, month }checks the account can sync (API,ACTIVE, has credentials) and returns{ queued, jobId }. Results appear when the job finishes.
Step 4: matching lines to orders
Rules live in classifyGatewayLine and importBatch:
- Split and dedupe. Each gateway entry becomes up to four payout lines: the amount (
PRINCIPAL, orCHARGEBACK), the fee (GATEWAY_FEE), the GST on the fee (GATEWAY_TAX), and a difference line when the gateway's net disagrees with amount less fees. Each line'sdedupeHashis the entry hash (gatewayLineDedupeHash) plus its component, so a re-import inserts nothing. ItsidentityKey({provider}:{paymentId}:{entryType}:{settlementId}:{component}) lets a restated fee supersede the old one. - Find the order payment. First by
(provider, providerTransactionId = paymentId); gateway payment ids are unique across the gateway, so this needs no store or account routing. If none, by merchant reference againstorderNoorchannelOrderId, ignoring a leading#and case. The reference fallback refuses to guess: a reference that fits more than one order (two stores both using#1001) is leftPENDING, and payments already attributed to a different account are not candidates. - Resolve. The lines of a matched entry resolve to the order (
PayoutLineResolution, methodORDER_ONLY). The comparison of amounts happens on the order's gateway receivable, not on the line:
| Situation | Line resolution | Receivable |
|---|---|---|
| Order payment found | RESOLVED to the order | Settled when captured and settled amounts agree within ₹0.50; refunds and chargebacks net against the capture |
| No order payment found | PENDING, retried nightly | — |
| Order paid with Shopify Payments | NOT_APPLICABLE | — |
- Learn the fee. Channel imports cannot know the gateway fee, so the order payment is created with
gatewayFee = 0. On a match,fee + taxfrom the gateway is written onto the payment only wheregatewayFeeis still 0. - Learn the account. A matched (or amount-mismatched) payment gets
paymentAccountIdset to the account the line came from, where it was still null. At channel import the account is stamped straight away when the tenant has exactly one live account of that gateway; with two or more, attribution waits for this step.
An earlier version compared the fee too. Every channel-recorded payment has fee 0, so every line showed "Amount differs". The fee is now learnt, not compared.
Step 5: payouts and the bank
A gateway payout is one bank transfer from the gateway, with its UTR: a Payout with source = PAYMENT_GATEWAY.
- Payouts belong to an account: unique on
(tenantId, source, partnerId, externalPayoutId)withpartnerId = paymentAccountId, because payout ids are unique per merchant account, not per gateway. - Stripe and PayPal report payouts directly; they are stored as reported, even before any line arrives. For the others, payouts are derived from lines: one per settlement id (or UTR), with the declared net totalled from its lines (
derivePayouts). Lines with no settlement id go to a day payoutDAY-<date>that stays open. - Bank statement import matches any payout whose
utrorexternalPayoutIdequals the statement reference, gateway payouts included, and creates aBankAllocation. - Manual allocation (
POST /finance/settlement/bank/statements/:id/allocate) takespayoutIdper allocation, for payouts of any source. - After a batch, the touched orders are reconciled and the payouts' journal vouchers posted.
File import
For file-only gateways, or any gateway when the tenant prefers its export:
- The admin uploads through the
settlement-importsfile store (proxied upload, CSV/XLS/XLSX, 50 MB). The upload records aFilerow against the tenant. POST /accounts/:accountId/file/previewwith{ fileKey }. The service refuses a key that is not aFileof this tenant, so one tenant cannot read another's upload by guessing a key. It returns headers, five sample rows, the row count, and a mapping.- The mapping is the account's saved mapping if all its columns exist in the file, otherwise a suggestion from header names seen in PhonePe, CCAvenue, PayU, Easebuzz, Razorpay and Cashfree exports.
POST /accounts/:accountId/file/importwith{ fileKey, mapping, saveMapping }.paymentIdandamountcolumns are required. The mapping is saved per account inGatewaySettlementMapping.
Parsing rules: amounts like 1,299.00, ₹ 1,299 and (25.00) (negative); dates as ISO or day-first DD/MM/YYYY; a negative amount with no type column is a refund. Rows without a payment id or amount are counted as rejected. Limit 100,000 rows per file.
API surface
Accounts (connected from Integrations), under /v1/finance/payment-accounts, @TenantScoped(), audit-logged mutations:
| Method | Path | Permission | Notes |
|---|---|---|---|
GET | / | SETTLEMENT:READ | Live accounts, no secrets; optional type, status |
GET | /unmapped-gateways | SETTLEMENT:READ | Gateways on the last 30 days of order payments with no account, with their store names |
GET | /:id | SETTLEMENT:READ | |
POST | / | SETTLEMENT:UPDATE | { type, name, code?, currency?, credentials? } |
PUT | /:id | SETTLEMENT:UPDATE | Rename, ACTIVE/INACTIVE, replace credentials |
DELETE | /:id | SETTLEMENT:UPDATE | Soft delete, credentials removed |
Platform admins read a tenant's accounts at GET /v1/finance/admin/payment-accounts?tenantId= (read-only).
Reconciliation, under /v1/finance/gateway-settlements:
| Method | Path | Permission | Notes |
|---|---|---|---|
GET | /gateways | SETTLEMENT:READ | Descriptors for API and file gateways |
POST | /accounts/:accountId/sync | SETTLEMENT:CREATE | Queues one month |
POST | /accounts/:accountId/file/preview | SETTLEMENT:CREATE | |
POST | /accounts/:accountId/file/import | SETTLEMENT:CREATE | |
POST | /import | SETTLEMENT:CREATE | { paymentAccountId, lines }, kept for scripted imports; same matcher |
GET | /payouts | SETTLEMENT:READ | Gateway payouts (same shape as GET /finance/settlement); optional paymentAccountId |
GET | /reconciliation | SETTLEMENT:READ | Gateway payout lines with their resolution; optional paymentAccountId, state |
An account of another tenant is 404. A sync request for a file account, or one that is not ACTIVE, is 422. Request shapes are in OpenAPI.
Adding a gateway
- Write
src/integrations/payments/gateways/<code>.adapter.tsimplementingPaymentGatewayAdapter: adescriptor,verify, andfetchSettlementsreturning{ payouts, lines }. UsegatewayRequestfor HTTP so credential rejections become 422. - Keep mapping in a static, pure method (
toLines,toBatch) and unit-test it with a recorded response. - Register the adapter in
PaymentsModuleproviders and in thePaymentGatewayRegistryconstructor. - Add an
IntegrationRegistryseed row (categorypayment) whose code is the upper-cased gateway code and whosecredentialsSchemakeys match the descriptor. The App Directory then lists it under Payments, and the shared connect form renders the descriptor's fields. - Add the gateway's names to
normalizePaymentGatewayand its receipt keys toextractGatewayPaymentIdso channel imports record its payment ids. - Run
yarn di:check(see Running tests).
A gateway with no usable API needs a descriptor in file-import.gateways.ts, a registry seed row without credentialsSchema, and, if its headers are unusual, hints in HEADER_HINTS.
Failure modes
| Symptom | Likely cause |
|---|---|
| Adding an account returns 422 | Gateway rejected the credentials, or a field is missing |
| Adding an account returns 400 "Payment gateway 'X' is not supported or active" | Registry row missing or inactive: run the seed |
| Account shows "Suspended after failures" | Five syncs in a row failed; the last reason is on the account. Replace the credentials, or turn it back on in Integrations |
Every line PENDING | Orders were imported before payment references were recorded: re-sync orders |
A line with an order number stays PENDING | The number fits orders in more than one store, or the order's payment belongs to another account |
Gateway receivable SHORT by a small amount | Partial capture or currency rounding above ₹0.50 |
| "Upload the settlement file again" | File key not owned by the tenant, or the upload record is missing |