Skip to main content

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​

GatewayCodeModeCredentialsSource
RazorpayrazorpayAPIkeyId, keySecretSettlement recon report, month by month (SDK settlements.reports)
Cashfree PaymentscashfreeAPIclientId, clientSecretPOST /pg/settlement/recon, cursor paging
PayUpayuAPImerchantKey, merchantSaltpostservice.php command get_settlement_details, one call per day, SHA-512 hash
Paytm PaymentspaytmAPImid, clientId, clientSecretmerchant-settlement/SettlementDetail, 7-day windows, HS256 JWT
StripestripeAPIsecretKeyPaid payouts, then balance_transactions?payout= per payout
PayPalpaypalAPIclientId, clientSecret/v1/reporting/transactions, 31-day windows, OAuth client credentials
PhonePe, CCAvenue, Easebuzz, Instamojo, Pine Labs, Juspayphonepe … juspayFilenoneTenant 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.

Field mappings not yet verified on live accounts

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 is not a gateway here

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​

PiecePath
Payment accounts (feature)src/modules/finance/payment-account/ — PaymentAccountService (CRUD), PaymentAccountSyncStateService (what to sync, outcomes, circuit breaker), tenant and platform-admin controllers
Portpayment-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
Adapterssrc/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 orchestrationgateway-settlement-sync.service.ts
Import and matchinggateway-settlement-import.service.ts, pure rules in gateway-settlement-line.util.ts
File importgateway-settlement-file.service.ts
Controller (day-to-day)gateway-settlement.controller.ts
Worker / schedulergateway-settlement.processor.ts, gateway-settlement.scheduler.ts
Channel payment referenceschannel-payment-reference.service.ts, payment-gateway.util.ts
Schema55-finance-accounts.prisma (PaymentAccount), 51-settlement.prisma (Payout, PayoutLine, PayoutLineResolution), 54-reconciliation-ops.prisma (GatewaySettlementMapping)
AdminConnect: 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 successful SALE/CAPTURE transactions from a recognised gateway are kept (toShopifyPaymentReferences). The payment id comes from authorizationCode or the gateway receipt.
  • WooCommerce: payment_method plus transaction_id and date_paid_gmt (toWooCommercePaymentReferences).
  • normalizePaymentGateway maps channel gateway names to the codes above. COD, bank transfer, manual and gift-card methods map to null and are not recorded.
  • ChannelPaymentReferenceService.record is 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.

FieldMeaning
typeRegistry code, e.g. RAZORPAY. Settlement data uses the lower-case form (provider = 'razorpay')
codeTenant-unique slug. Derived from the type when omitted; a second account of the same gateway gets RAZORPAY-2
syncModeAPI (credentials stored, synced daily) or FILE (no connection; settlement exports are imported)
statusACTIVE, INACTIVE (a person turned it off) or SUSPENDED (circuit breaker, after 5 consecutive failed syncs). Same rule as channels (ADR-0002)
lastSettlementSync, lastSyncError, lastSyncSummary, consecutiveFailuresSync health shown on the account

Creating or updating an API account with credentials (POST /finance/payment-accounts, PUT /finance/payment-accounts/:id):

  1. The registry keeps only the fields the gateway descriptor declares and trims them.
  2. The adapter's verify makes 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.
  3. Credentials go into an IntegrationConnection (integrationCode = type) through IntegrationConnectionService, envelope-encrypted; an update replaces the credentials on the same connection. The account's config holds only keyIdHint (last four characters of the first non-secret field).
  4. New credentials clear the circuit breaker: consecutiveFailures = 0, and a SUSPENDED account returns to ACTIVE.

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.

A registry row is required

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-sync on settlement_queue, concurrency 2. The payload carries the account id and dates, never credentials.
  • jobId is gateway-sync:{paymentAccountId}:{fromDay}:{toDay}, so identical pending requests collapse. removeOnComplete and removeOnFail are 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 an ACTIVE account to SUSPENDED; an INACTIVE account 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/sync with { 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:

  1. Split and dedupe. Each gateway entry becomes up to four payout lines: the amount (PRINCIPAL, or CHARGEBACK), 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's dedupeHash is the entry hash (gatewayLineDedupeHash) plus its component, so a re-import inserts nothing. Its identityKey ({provider}:{paymentId}:{entryType}:{settlementId}:{component}) lets a restated fee supersede the old one.
  2. 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 against orderNo or channelOrderId, 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 left PENDING, and payments already attributed to a different account are not candidates.
  3. Resolve. The lines of a matched entry resolve to the order (PayoutLineResolution, method ORDER_ONLY). The comparison of amounts happens on the order's gateway receivable, not on the line:
SituationLine resolutionReceivable
Order payment foundRESOLVED to the orderSettled when captured and settled amounts agree within ₹0.50; refunds and chargebacks net against the capture
No order payment foundPENDING, retried nightly—
Order paid with Shopify PaymentsNOT_APPLICABLE—
  1. Learn the fee. Channel imports cannot know the gateway fee, so the order payment is created with gatewayFee = 0. On a match, fee + tax from the gateway is written onto the payment only where gatewayFee is still 0.
  2. Learn the account. A matched (or amount-mismatched) payment gets paymentAccountId set 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.
Why amounts only

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) with partnerId = 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 payout DAY-<date> that stays open.
  • Bank statement import matches any payout whose utr or externalPayoutId equals the statement reference, gateway payouts included, and creates a BankAllocation.
  • Manual allocation (POST /finance/settlement/bank/statements/:id/allocate) takes payoutId per 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:

  1. The admin uploads through the settlement-imports file store (proxied upload, CSV/XLS/XLSX, 50 MB). The upload records a File row against the tenant.
  2. POST /accounts/:accountId/file/preview with { fileKey }. The service refuses a key that is not a File of 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.
  3. 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.
  4. POST /accounts/:accountId/file/import with { fileKey, mapping, saveMapping }. paymentId and amount columns are required. The mapping is saved per account in GatewaySettlementMapping.

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:

MethodPathPermissionNotes
GET/SETTLEMENT:READLive accounts, no secrets; optional type, status
GET/unmapped-gatewaysSETTLEMENT:READGateways on the last 30 days of order payments with no account, with their store names
GET/:idSETTLEMENT:READ
POST/SETTLEMENT:UPDATE{ type, name, code?, currency?, credentials? }
PUT/:idSETTLEMENT:UPDATERename, ACTIVE/INACTIVE, replace credentials
DELETE/:idSETTLEMENT:UPDATESoft 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:

MethodPathPermissionNotes
GET/gatewaysSETTLEMENT:READDescriptors for API and file gateways
POST/accounts/:accountId/syncSETTLEMENT:CREATEQueues one month
POST/accounts/:accountId/file/previewSETTLEMENT:CREATE
POST/accounts/:accountId/file/importSETTLEMENT:CREATE
POST/importSETTLEMENT:CREATE{ paymentAccountId, lines }, kept for scripted imports; same matcher
GET/payoutsSETTLEMENT:READGateway payouts (same shape as GET /finance/settlement); optional paymentAccountId
GET/reconciliationSETTLEMENT:READGateway 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​

  1. Write src/integrations/payments/gateways/<code>.adapter.ts implementing PaymentGatewayAdapter: a descriptor, verify, and fetchSettlements returning { payouts, lines }. Use gatewayRequest for HTTP so credential rejections become 422.
  2. Keep mapping in a static, pure method (toLines, toBatch) and unit-test it with a recorded response.
  3. Register the adapter in PaymentsModule providers and in the PaymentGatewayRegistry constructor.
  4. Add an IntegrationRegistry seed row (category payment) whose code is the upper-cased gateway code and whose credentialsSchema keys match the descriptor. The App Directory then lists it under Payments, and the shared connect form renders the descriptor's fields.
  5. Add the gateway's names to normalizePaymentGateway and its receipt keys to extractGatewayPaymentId so channel imports record its payment ids.
  6. 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​

SymptomLikely cause
Adding an account returns 422Gateway 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 PENDINGOrders were imported before payment references were recorded: re-sync orders
A line with an order number stays PENDINGThe number fits orders in more than one store, or the order's payment belongs to another account
Gateway receivable SHORT by a small amountPartial 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