openapi: 3.1.0
info:
  title: AquaPay Merchant API
  version: 2.0.0
  summary: Pay-ins, payouts, balance and signed webhooks for one gateway account.
  description: |
    The server-to-server API a merchant's backend calls. It replaces the v1 merchant API (`/api/v1/deposit-sessions`,
    `/api/v1/withdrawals`, the status lookups and the v1 callbacks).

    ## The account is the key

    A secret key belongs to exactly one **gateway account**, and a gateway account is bound to exactly one gateway and
    so to one provider. Every request acts on that account. No path names a provider or an account: the key implies
    both. `GET /account` says what the account can do.

    ## Conventions

    - **Keys** of JSON objects are `camelCase`. **Machine values** (statuses, error codes, scopes, event types, payout
      methods, providers) are `lower_snake_case`, with a dot or colon only as a namespace separator
      (`payout.succeeded`, `payouts:write`).
    - **IDs** are opaque strings with a type prefix: `ga_` gateway account, `payin_`, `payout_`, `entry_` ledger entry,
      `event_`, `hook_` webhook endpoint, `kid_` API key. Never parse them.
    - **Money** is a decimal string, never a JSON number. Requests take up to two decimals (`"500"`, `"500.5"`,
      `"500.50"`). Responses render every amount in one canonical form: at least two and at most six decimals, with no
      trailing zero after the second (`"500.00"`, `"10.0001"`), so equal strings mean equal amounts. More than two
      decimals occur only in an amount a provider reported. Every money-bearing object carries `currency`
      (ISO 4217: `INR` or `USD`).
    - **Times** are RFC 3339 in UTC with a `Z` offset.
    - **Requests** are `application/json`, at most 16 KiB. Unknown request fields are refused (`validation_failed`).
    - **Responses** return the resource itself, with no wrapper. Lists are `{"items": [...], "nextCursor": "..."}`.
      Clients must ignore response fields, enum values and event types they do not know.

    ## Headers

    | Header | Direction | Use |
    | --- | --- | --- |
    | `Authorization: Bearer aqk_live_…` | request | The secret key. `aqk_test_…` keys belong to sandbox accounts. |
    | `Idempotency-Key` | request | Required on every `POST`. See Idempotency. |
    | `AquaPay-Payment-Password` | request | The account's payment password, on payout creation and webhook changes. |
    | `AquaPay-Request-Id` | response | Always set. Quote it to AquaPay support, and find the request in the console's logs. Error bodies repeat it as `requestId`. |
    | `AquaPay-Idempotent-Replay: true` | response | The answer is a stored replay, not a new execution. |
    | `Retry-After` | response | Seconds to wait, on `423`, `429` and `503`. |
    | `AquaPay-Signature` | webhook | `t=<unix seconds>,sha256=<hex>[,sha256=<hex>]`. See Webhooks. |

    ## Idempotency

    Every `POST` needs an `Idempotency-Key` (8 to 64 characters of `A-Z a-z 0-9 _ -`; use a UUID). Keys are scoped to
    the gateway account, so a retry still replays after the key that sent it was rotated.

    - A request is fingerprinted by method, path and the SHA-256 of its body. `AquaPay-Payment-Password` is not part
      of the fingerprint.
    - An answer is stored once AquaPay starts to act on the request: every `2xx`, every `409` about the resource,
      and the `422`, `424` and `502` of a create (`POST /payins`, `POST /payouts`) and of a refused UTR. The `424` of a
      refresh or a UTR binding learnt nothing and changed nothing, so it is not stored and `retry: same_key` asks
      again. Answers from authentication, scope, payment-password, validation, rate-limit and unexpected server
      failures (`400`, `401`, `403`, `423`, `429`, `500`, `503`) are not stored either, so the same key may be sent
      again.
    - The same key with the same fingerprint returns the stored status and body with `AquaPay-Idempotent-Replay: true`.
      The same key with a different fingerprint is `409 idempotency_conflict`. The same key while the first request
      is still running is `409 idempotency_key_busy`.
    - Stored answers are kept for **24 hours**. A payout's key is also its **attempt key** and is never forgotten: it
      can create at most one payout, ever. After 24 hours a repeat of the same payout request answers `200` with the
      payout's current state, and `POST /payout-attempts/{attemptKey}/close` can retire an unused key for good.

    ## Payment password

    Payout creation, and creating, deleting or rotating a webhook endpoint, always need the account's payment
    password in `AquaPay-Payment-Password`: it is a person's approval, typed for each action, and no key is exempt. A
    password that is sent is always checked.

    Wrong passwords lock only the key and client IP that sent them: five in a row lock that pair for 15 minutes
    (`423 payment_password_locked`). Twenty wrong passwords on one account within an hour also lock, for the rest of
    that hour, every key and IP pair that has never sent a correct password. Pairs that have sent a correct password
    in the last 30 days keep working, so a leaked key cannot be used to block the merchant's own payouts. API
    failures never count towards the console's lockout.

    ## Errors

    Every error has the same body (`Error`). Branch on `code`, never on `message`; `docUrl` links the code's page in
    the docs, and `requestId` names the request in AquaPay's logs. `retry` says what to do next:
    `same_key` (send the same request again with the same key, after `Retry-After` if set), `new_key` (nothing blocks a
    new attempt; it needs a new key), `refresh` (the outcome is unknown: do not send again; refresh the resource or
    wait for its webhook) and `no` (it fails the same way until the request or the account changes). `provider`
    carries the provider's own words when a provider caused the error.

    ## Versioning

    The version is in the URL only. Within `/api/v2` changes are additive: new fields, new enum values, new event
    types, new endpoints. Anything else is `/api/v3`.

    ## Test mode

    Accounts in `test` mode are bound to the sandbox provider, which imitates one real provider's rules (currency,
    whole amounts, payout methods, limits, UTR binding) and is driven by magic amounts and beneficiaries. Payments
    move no money, and webhooks fire as in live mode. The magic values are on the sandbox page of the docs.
  license:
    name: Proprietary
    identifier: LicenseRef-AquaPay-Proprietary
  contact:
    name: AquaPay
    url: https://aquapay.bhimpay.online
servers:
  - url: https://api.bhimpay.online/api/v2
    description: Live and sandbox. The key's mode picks which.
security:
  - secretKey: []
tags:
  - name: account
    description: The gateway account the key belongs to, its balance and its ledger.
  - name: payins
    description: Money in from a payer.
  - name: payouts
    description: Money out to a beneficiary.
  - name: events
    description: The webhook stream, for polling.
  - name: webhooks
    description: Where events are delivered.

components:
  securitySchemes:
    secretKey:
      type: http
      scheme: bearer
      description: |
        `aqk_live_` or `aqk_test_`, then 32 base62 characters, then a 6-character checksum:
        `^aqk_(live|test)_[0-9A-Za-z]{38}$`. The checksum is the CRC32 (IEEE) of everything before it, written in
        base62 with the alphabet `0-9A-Za-z`, most significant digit first, left-padded with `0` to 6 characters. A
        client or a secret scanner can reject a mistyped key, or recognise a real one, without a network call;
        AquaPay checks the checksum before any lookup. Vectors: `aqk_test_Zt8kP3vQ9mW2xR6nB1cY7hJ4gF0sD5aL1ecL37`
        and `aqk_live_Zt8kP3vQ9mW2xR6nB1cY7hJ4gF0sD5aL4HwrTc` are well formed. A key
        belongs to one gateway account and carries scopes (`read`, always; `payins:write`, `payouts:write`,
        `webhooks:write` as granted), an optional IP allowlist and an optional expiry. Keys are created, rolled and
        revoked in the console and are shown once.

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Makes a retry safe. On `POST /payouts` it is also the payout's permanent attempt key.
      schema: { type: string, pattern: '^[A-Za-z0-9_-]{8,64}$' }
      example: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70
    PaymentPassword:
      name: AquaPay-Payment-Password
      in: header
      required: false
      description: |
        The gateway account's payment password, typed by the person approving the action. Required on payout
        creation and on webhook endpoint changes; checked whenever it is sent. Never logged or stored by AquaPay.
      schema: { type: string, minLength: 1, maxLength: 128 }
      example: correct-horse-battery
    PayinId:
      name: payinId
      in: path
      required: true
      schema: { type: string, pattern: '^payin_[0-9a-z]{13}$' }
      example: payin_7h2kq9w3m1zt4
    PayoutId:
      name: payoutId
      in: path
      required: true
      schema: { type: string, pattern: '^payout_[0-9a-z]{13}$' }
      example: payout_c8n4r2v6y0jd5
    AttemptKey:
      name: attemptKey
      in: path
      required: true
      description: The `Idempotency-Key` a payout was (or would be) created with.
      schema: { type: string, pattern: '^[A-Za-z0-9_-]{8,64}$' }
      example: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70
    EndpointId:
      name: endpointId
      in: path
      required: true
      schema: { type: string, pattern: '^hook_[0-9a-z]{13}$' }
      example: hook_a4s8d2f6g0h3j
    Cursor:
      name: cursor
      in: query
      description: The `nextCursor` of the previous page. Opaque.
      schema: { type: string, maxLength: 128 }
    Limit:
      name: limit
      in: query
      schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
    Reference:
      name: reference
      in: query
      description: Your reference, matched exactly.
      schema: { type: string, minLength: 1, maxLength: 64 }
      example: DEP-20261203-0042
    Signature:
      name: AquaPay-Signature
      in: header
      required: true
      description: |
        `t=<unix seconds>,sha256=<hex>`, with a second `sha256=` during a secret rotation. Each value is the
        HMAC-SHA256 of `<t>.<raw body>` keyed with an endpoint signing secret. Refuse a `t` more than 300 seconds
        from your clock.
      schema: { type: string }
      example: t=1796289307,sha256=d43246d6edb197cca25a95aec428d59625c5c64e125e731c0f0dab2d4235475e

  headers:
    RequestId:
      description: This request's id. Error bodies repeat it as `requestId`; the console's request logs find it.
      schema: { type: string, format: uuid }
      example: 5f0c2b8e-3a1d-4e7f-9b6a-8d2c4e1f0a93
    IdempotentReplay:
      description: Present, `true`, when the answer is a stored replay.
      schema: { type: string, const: 'true' }
    RetryAfter:
      description: Seconds to wait before sending again.
      schema: { type: integer, minimum: 1 }
      example: 30

  responses:
    BadRequest:
      description: The request is malformed or breaks a rule (`validation_failed`).
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            validation_failed: { $ref: '#/components/examples/ErrValidationFailed' }
            validation_failed_whole_units: { $ref: '#/components/examples/ErrValidationFailedWholeUnits' }
    Unauthorized:
      description: '`api_key_invalid`, `payment_password_required` or `payment_password_invalid`.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            api_key_invalid: { $ref: '#/components/examples/ErrApiKeyInvalid' }
            payment_password_required: { $ref: '#/components/examples/ErrPaymentPasswordRequired' }
            payment_password_invalid: { $ref: '#/components/examples/ErrPaymentPasswordInvalid' }
    Forbidden:
      description: '`ip_not_allowed`, `scope_missing` or `account_suspended`.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            ip_not_allowed: { $ref: '#/components/examples/ErrIpNotAllowed' }
            scope_missing: { $ref: '#/components/examples/ErrScopeMissing' }
            account_suspended: { $ref: '#/components/examples/ErrAccountSuspended' }
    NotFound:
      description: '`resource_not_found`: no such resource on this account.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            resource_not_found: { $ref: '#/components/examples/ErrResourceNotFound' }
    Conflict:
      description: The request conflicts with the account's state or with an earlier request.
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            idempotency_conflict: { $ref: '#/components/examples/ErrIdempotencyConflict' }
            idempotency_key_busy: { $ref: '#/components/examples/ErrIdempotencyKeyBusy' }
            duplicate_reference: { $ref: '#/components/examples/ErrDuplicateReference' }
            attempt_closed: { $ref: '#/components/examples/ErrAttemptClosed' }
            balance_insufficient: { $ref: '#/components/examples/ErrBalanceInsufficient' }
            wrong_state: { $ref: '#/components/examples/ErrWrongState' }
            utr_in_use: { $ref: '#/components/examples/ErrUtrInUse' }
    Unprocessable:
      description: '`unsupported_by_provider`, or `provider_refused`: the provider answered and refused.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            unsupported_by_provider: { $ref: '#/components/examples/ErrUnsupportedByProvider' }
            provider_refused: { $ref: '#/components/examples/ErrProviderRefused' }
    Locked:
      description: '`payment_password_locked`.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            payment_password_locked: { $ref: '#/components/examples/ErrPaymentPasswordLocked' }
    ProviderUnreachable:
      description: '`provider_unreachable`: the provider could not be reached, so nothing was sent or nothing was learnt.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            provider_unreachable: { $ref: '#/components/examples/ErrProviderUnreachable' }
    ProviderOutcomeUnknown:
      description: '`provider_outcome_unknown`: the provider may have acted.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            provider_outcome_unknown: { $ref: '#/components/examples/ErrProviderOutcomeUnknown' }
    TooManyRequests:
      description: '`too_many_requests`.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            too_many_requests: { $ref: '#/components/examples/ErrTooManyRequests' }
    ServerError:
      description: '`server_error`: AquaPay failed before acting; the same request may be sent again.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            server_error: { $ref: '#/components/examples/ErrServerError' }
    ServiceUnavailable:
      description: '`service_unavailable`: maintenance, or the account was busy.'
      headers:
        AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            service_unavailable: { $ref: '#/components/examples/ErrServiceUnavailable' }

  schemas:
    # ---------------------------------------------------------------- scalars
    Money:
      type: string
      description: A non-negative amount in canonical form (two to six decimals, no trailing zero after the second).
      pattern: '^\d{1,14}\.\d{2}(\d{0,3}[1-9])?$'
      examples: ['500.00', '1515.50', '10.0001']
    SignedMoney:
      type: string
      description: A signed amount in canonical form.
      pattern: '^-?\d{1,14}\.\d{2}(\d{0,3}[1-9])?$'
      examples: ['-1515.00', '500.00']
    MoneyInput:
      type: string
      description: A positive amount with at most two decimals.
      pattern: '^\d{1,14}(\.\d{1,2})?$'
      examples: ['500', '500.5', '500.50']
    Percent:
      type: string
      description: A percentage as a decimal string (`"2.5"` is 2.5 %).
      pattern: '^\d{1,3}(\.\d{1,4})?$'
      examples: ['2.5', '0']
    Currency:
      type: string
      description: ISO 4217, the currency of the account's gateway. Every account is `INR` today.
      enum: [INR, USD]
    Mode:
      type: string
      enum: [live, test]
    Provider:
      type: string
      description: The provider the account's gateway uses. A `test` account reports the provider its sandbox imitates.
      enum: [payme, upayrpl, cowpay, rspay]
    Scope:
      type: string
      enum: [read, 'payins:write', 'payouts:write', 'webhooks:write']
    PayoutMethod:
      type: string
      description: '`bank` (account number and IFSC), `upi` (a VPA), `upay_wallet` (a UPay wallet, paid in RPL at ₹1 each).'
      enum: [bank, upi, upay_wallet]
    PayinStatus:
      type: string
      description: |
        `pending` (waiting for the payer) → `succeeded` | `failed` | `expired` | `needs_review`.
        `failed` and `expired` can still become `succeeded` (or `needs_review`) on the provider's proof of a late
        payment. `needs_review` is resolved by AquaPay staff to `succeeded` or `failed`. `succeeded` is final.
      enum: [pending, succeeded, failed, expired, needs_review]
    PayoutStatus:
      type: string
      description: |
        `processing` (recorded, amount held, at or on its way to the provider) → `succeeded` | `failed` |
        `needs_review`. `succeeded` → `reversed` only on the provider's own word. `needs_review` (still held) is
        resolved by AquaPay staff to `succeeded`, `failed` or `reversed`. `failed` and `reversed` are final.
      enum: [processing, succeeded, failed, needs_review, reversed]
    FailureReason:
      type: string
      description: |
        `beneficiary_invalid` and `beneficiary_bank_unsupported`: fix the beneficiary. `amount_not_allowed`: the
        provider will not take this amount. `provider_balance_insufficient`: the gateway's own float at the provider
        is short; tell AquaPay. `provider_refused`: refused for another reason. `provider_unreachable`: never sent.
        `provider_failed`: accepted, then failed by the provider (for a pay-in, the payer did not complete).
        `provider_reversed`: paid, then returned. `resolved_by_aquapay`: AquaPay staff closed it after review.
      enum: [beneficiary_invalid, beneficiary_bank_unsupported, amount_not_allowed, provider_balance_insufficient, provider_refused, provider_unreachable, provider_failed, provider_reversed, resolved_by_aquapay]
    Failure:
      type: [object, 'null']
      description: Why a payment failed or was reversed; null otherwise.
      required: [reason, message]
      properties:
        reason: { $ref: '#/components/schemas/FailureReason' }
        message: { type: string, maxLength: 200, description: "The provider's words where it gave any, else AquaPay's." }

    # ---------------------------------------------------------------- account
    Limits:
      type: object
      description: The limits in force (provider floors, the gateway's and the account's own, combined). null is no limit.
      required: [min, max]
      properties:
        min: { oneOf: [{ $ref: '#/components/schemas/Money' }, { type: 'null' }] }
        max: { oneOf: [{ $ref: '#/components/schemas/Money' }, { type: 'null' }] }
    Fee:
      type: object
      description: The fee is `amount × percent / 100 + fixed`, each part rounded half away from zero to two decimals.
      required: [percent, fixed]
      properties:
        percent: { $ref: '#/components/schemas/Percent' }
        fixed: { $ref: '#/components/schemas/Money' }
    Account:
      type: object
      required: [id, name, mode, status, provider, currency, wholeUnitsOnly, payins, payouts, key]
      properties:
        id: { type: string, pattern: '^ga_[0-9a-z]{13}$' }
        name: { type: string, description: The account's display name. }
        mode: { $ref: '#/components/schemas/Mode' }
        status: { type: string, enum: [active, suspended] }
        provider: { $ref: '#/components/schemas/Provider' }
        currency: { $ref: '#/components/schemas/Currency' }
        wholeUnitsOnly: { type: boolean, description: 'Amounts must be whole (PAYME, COWPAY); `"100.50"` is refused.' }
        payins:
          type: object
          required: [enabled, limits, fee, utrBinding, payerIpRequired]
          properties:
            enabled: { type: boolean }
            limits: { $ref: '#/components/schemas/Limits' }
            fee: { $ref: '#/components/schemas/Fee' }
            utrBinding: { type: boolean, description: '`POST /payins/{payinId}/bind-utr` works.' }
            payerIpRequired: { type: boolean, description: '`payer.ip` is required.' }
        payouts:
          type: object
          required: [enabled, methods, limits, fee, paymentPasswordRequired]
          properties:
            enabled: { type: boolean }
            methods: { type: array, items: { $ref: '#/components/schemas/PayoutMethod' } }
            limits: { $ref: '#/components/schemas/Limits' }
            fee: { $ref: '#/components/schemas/Fee' }
            paymentPasswordRequired: { type: boolean, description: 'Whether this key must send `AquaPay-Payment-Password` to create a payout: always true.' }
        key:
          type: object
          description: The key that made this request.
          required: [id, name, scopes, ipAllowlist, expiresAt]
          properties:
            id: { type: string, pattern: '^kid_[0-9a-z]{13}$' }
            name: { type: string }
            scopes: { type: array, items: { $ref: '#/components/schemas/Scope' } }
            ipAllowlist: { type: array, maxItems: 16, items: { type: string, description: An IPv4 or IPv6 address or CIDR. } }
            expiresAt: { type: [string, 'null'], format: date-time, description: Set while the key is being rolled out of use. }
    Balance:
      type: object
      required: [currency, available, held, asOf]
      properties:
        currency: { $ref: '#/components/schemas/Currency' }
        available: { $ref: '#/components/schemas/SignedMoney', description: 'What payouts may spend now: the sum of the ledger, holds already taken off.' }
        held: { $ref: '#/components/schemas/Money', description: 'What `processing` and `needs_review` payouts hold, included in the ledger as holds.' }
        asOf: { type: string, format: date-time }
    LedgerEntry:
      type: object
      required: [id, type, amount, balanceAfter, paymentId, note, createdAt]
      properties:
        id: { type: string, pattern: '^entry_[0-9a-z]{13}$' }
        type:
          type: string
          enum: [payin_credit, fee, payout_hold, payout_release, payout_settle, adjustment]
        amount: { $ref: '#/components/schemas/SignedMoney' }
        balanceAfter: { $ref: '#/components/schemas/SignedMoney' }
        paymentId: { type: [string, 'null'], description: The pay-in or payout the entry belongs to; null for an adjustment. }
        note: { type: [string, 'null'], description: An adjustment's reason. }
        createdAt: { type: string, format: date-time }
    LedgerPage:
      type: object
      required: [items, nextCursor]
      properties:
        items: { type: array, maxItems: 100, items: { $ref: '#/components/schemas/LedgerEntry' } }
        nextCursor: { type: [string, 'null'], description: null on the last page. }

    # ---------------------------------------------------------------- pay-ins
    CreatePayinRequest:
      type: object
      additionalProperties: false
      required: [amount, currency, reference, payer, returnUrl]
      properties:
        amount: { $ref: '#/components/schemas/MoneyInput' }
        currency: { $ref: '#/components/schemas/Currency' }
        reference: { type: string, minLength: 1, maxLength: 64, description: 'Your id for the order. Not unique: a retried order may reuse it.' }
        payer:
          type: object
          additionalProperties: false
          required: [id]
          properties:
            id: { type: string, minLength: 1, maxLength: 64, description: Your id for the payer. Providers use it for risk checks. }
            ip: { type: string, description: The payer's public IPv4 or IPv6 address. Required when `payins.payerIpRequired`. }
        returnUrl: { type: string, format: uri, maxLength: 2048, description: Where the payment page sends the payer afterwards. }
    NextAction:
      type: [object, 'null']
      description: |
        What to show the payer, while the pay-in is `pending`; null otherwise. Redirect to `redirectUrl`, or, where
        `upiUri` is set, open it on a phone (UPI intent) or render it as a QR code on a desktop.
      required: [redirectUrl, upiUri]
      properties:
        redirectUrl: { type: string, format: uri }
        upiUri: { type: [string, 'null'], description: 'A `upi://pay?…` URI (COWPAY).' }
    Payin:
      type: object
      required: [id, reference, status, amount, paidAmount, currency, fee, net, utr, orderId, providerOrderId, nextAction, expiresAt, failure, version, createdAt, updatedAt]
      properties:
        id: { type: string, pattern: '^payin_[0-9a-z]{13}$' }
        reference: { type: string }
        status: { $ref: '#/components/schemas/PayinStatus' }
        amount: { $ref: '#/components/schemas/Money', description: The order amount. }
        paidAmount: { oneOf: [{ $ref: '#/components/schemas/Money' }, { type: 'null' }], description: 'What the provider reports was paid; null until it reports. On `succeeded` it is what was credited, before the fee.' }
        currency: { $ref: '#/components/schemas/Currency' }
        fee: { $ref: '#/components/schemas/Money', description: The fee on this pay-in (on `paidAmount` once succeeded). }
        net: { $ref: '#/components/schemas/Money', description: 'What the balance gains when it succeeds: `paidAmount` (or `amount`) minus `fee`.' }
        utr: { type: [string, 'null'], description: The bank's reference for the payment. }
        orderId: { type: string, description: The order number AquaPay sent the provider. The same value v1 called `orderId`. }
        providerOrderId: { type: [string, 'null'], description: The provider's own id for the order. }
        nextAction: { $ref: '#/components/schemas/NextAction' }
        expiresAt: { type: string, format: date-time, description: 'Two hours after creation. A pay-in still `pending` then is checked with the provider once and, if still unpaid, becomes `expired`.' }
        failure: { $ref: '#/components/schemas/Failure' }
        version: { type: integer, minimum: 1, description: Grows by one on every change. Apply a webhook only if its version is newer than the one you hold. }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    PayinPage:
      type: object
      required: [items, nextCursor]
      properties:
        items: { type: array, maxItems: 100, items: { $ref: '#/components/schemas/Payin' } }
        nextCursor: { type: [string, 'null'], description: null on the last page. }
    BindUtrRequest:
      type: object
      additionalProperties: false
      required: [utr]
      properties:
        utr: { type: string, pattern: '^[0-9]{12}$', description: The 12-digit UTR from the payer's bank or UPI app. }

    # ---------------------------------------------------------------- payouts
    BankBeneficiary:
      type: object
      additionalProperties: false
      required: [type, name, accountNumber, ifsc]
      properties:
        type: { type: string, const: bank }
        name: { type: string, minLength: 1, maxLength: 100 }
        accountNumber: { type: string, pattern: '^[0-9]{6,20}$' }
        ifsc: { type: string, pattern: '^[A-Z]{4}0[A-Z0-9]{6}$' }
    UpiBeneficiary:
      type: object
      additionalProperties: false
      required: [type, name, vpa]
      properties:
        type: { type: string, const: upi }
        name: { type: string, minLength: 1, maxLength: 100 }
        vpa: { type: string, pattern: '^[A-Za-z0-9._-]{2,256}@[A-Za-z][A-Za-z0-9.-]{1,63}$' }
    UpayWalletBeneficiary:
      type: object
      additionalProperties: false
      required: [type, address]
      properties:
        type: { type: string, const: upay_wallet }
        address: { type: string, minLength: 1, maxLength: 128 }
    Beneficiary:
      description: Where a payout goes. `type` must be one of the account's `payouts.methods`.
      oneOf:
        - $ref: '#/components/schemas/BankBeneficiary'
        - $ref: '#/components/schemas/UpiBeneficiary'
        - $ref: '#/components/schemas/UpayWalletBeneficiary'
      discriminator:
        propertyName: type
        mapping:
          bank: '#/components/schemas/BankBeneficiary'
          upi: '#/components/schemas/UpiBeneficiary'
          upay_wallet: '#/components/schemas/UpayWalletBeneficiary'
    BeneficiarySummary:
      type: object
      description: The beneficiary, masked.
      required: [type, name, masked]
      properties:
        type: { $ref: '#/components/schemas/PayoutMethod' }
        name: { type: [string, 'null'] }
        masked: { type: string, description: 'The last characters only: `••••6789`, `ra•••@okhdfcbank`, `UPW•••7n4v1`.' }
    CreatePayoutRequest:
      type: object
      additionalProperties: false
      required: [amount, currency, reference, beneficiary]
      properties:
        amount: { $ref: '#/components/schemas/MoneyInput', description: What the beneficiary receives. The fee is debited on top. }
        currency: { $ref: '#/components/schemas/Currency' }
        reference: { type: string, minLength: 1, maxLength: 64, description: Your id for the withdrawal. }
        beneficiary: { $ref: '#/components/schemas/Beneficiary' }
        narration: { type: string, minLength: 1, maxLength: 50, description: 'The remark sent to the provider. Defaults to "Payout <reference>".' }
    Payout:
      type: object
      required: [id, reference, attemptKey, status, amount, fee, total, currency, beneficiary, utr, orderId, providerOrderId, failure, version, createdAt, updatedAt]
      properties:
        id: { type: string, pattern: '^payout_[0-9a-z]{13}$' }
        reference: { type: string }
        attemptKey: { type: string, description: The `Idempotency-Key` that created it. }
        status: { $ref: '#/components/schemas/PayoutStatus' }
        amount: { $ref: '#/components/schemas/Money', description: 'What the beneficiary receives. On `succeeded` the provider confirmed exactly this.' }
        fee: { $ref: '#/components/schemas/Money' }
        total: { $ref: '#/components/schemas/Money', description: '`amount + fee`: held while `processing` or `needs_review`, debited on `succeeded`, released on `failed` or `reversed`.' }
        currency: { $ref: '#/components/schemas/Currency' }
        beneficiary: { $ref: '#/components/schemas/BeneficiarySummary' }
        utr: { type: [string, 'null'], description: "The bank's reference for the transfer, once the provider gives one." }
        orderId: { type: string, description: The order number AquaPay sent the provider. The same value v1 called `orderId`. }
        providerOrderId: { type: [string, 'null'] }
        failure: { $ref: '#/components/schemas/Failure' }
        version: { type: integer, minimum: 1, description: Grows by one on every change. Apply a webhook only if its version is newer than the one you hold. }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    PayoutPage:
      type: object
      required: [items, nextCursor]
      properties:
        items: { type: array, maxItems: 100, items: { $ref: '#/components/schemas/Payout' } }
        nextCursor: { type: [string, 'null'], description: null on the last page. }
    PayoutQuote:
      type: object
      required: [amount, fee, total, currency, sufficientBalance]
      properties:
        amount: { $ref: '#/components/schemas/Money' }
        fee: { $ref: '#/components/schemas/Money' }
        total: { $ref: '#/components/schemas/Money' }
        currency: { $ref: '#/components/schemas/Currency' }
        sufficientBalance: { type: boolean, description: Whether `available` covers `total` at this moment. }
    PayoutAttempt:
      type: object
      required: [key, state, payout]
      properties:
        key: { type: string }
        state: { type: string, enum: [unused, used, closed] }
        payout: { oneOf: [{ $ref: '#/components/schemas/Payout' }, { type: 'null' }], description: The payout when `used`. }

    # ---------------------------------------------------------------- events
    EventEnvelope:
      type: object
      required: [id, mode, account, createdAt]
      properties:
        id: { type: string, pattern: '^event_[0-9a-z]{13}$', description: Deduplicate on it. Delivery is at least once. }
        mode: { $ref: '#/components/schemas/Mode', description: Never credit anyone for a `test` event. }
        account: { type: string, pattern: '^ga_[0-9a-z]{13}$' }
        createdAt: { type: string, format: date-time }
    PayinEvent:
      allOf:
        - $ref: '#/components/schemas/EventEnvelope'
        - type: object
          required: [type, data]
          properties:
            type: { type: string, enum: [payin.succeeded, payin.failed, payin.expired, payin.needs_review] }
            data: { $ref: '#/components/schemas/Payin', description: The pay-in as it was when the event was made. }
    PayoutEvent:
      allOf:
        - $ref: '#/components/schemas/EventEnvelope'
        - type: object
          required: [type, data]
          properties:
            type: { type: string, enum: [payout.succeeded, payout.failed, payout.needs_review, payout.reversed] }
            data: { $ref: '#/components/schemas/Payout', description: The payout as it was when the event was made. }
    Event:
      oneOf:
        - $ref: '#/components/schemas/PayinEvent'
        - $ref: '#/components/schemas/PayoutEvent'
      discriminator:
        propertyName: type
        mapping:
          payin.succeeded: '#/components/schemas/PayinEvent'
          payin.failed: '#/components/schemas/PayinEvent'
          payin.expired: '#/components/schemas/PayinEvent'
          payin.needs_review: '#/components/schemas/PayinEvent'
          payout.succeeded: '#/components/schemas/PayoutEvent'
          payout.failed: '#/components/schemas/PayoutEvent'
          payout.needs_review: '#/components/schemas/PayoutEvent'
          payout.reversed: '#/components/schemas/PayoutEvent'
    EventPage:
      type: object
      required: [items, nextCursor]
      properties:
        items: { type: array, maxItems: 100, items: { $ref: '#/components/schemas/Event' } }
        nextCursor: { type: string, description: 'Never null: poll again with it. Before the first event it is `e1.0`.' }

    # ---------------------------------------------------------------- webhook endpoints
    EventType:
      type: string
      enum: [payin.succeeded, payin.failed, payin.expired, payin.needs_review, payout.succeeded, payout.failed, payout.needs_review, payout.reversed]
    WebhookEndpoint:
      type: object
      required: [id, url, description, eventTypes, createdAt, secretRotatedAt]
      properties:
        id: { type: string, pattern: '^hook_[0-9a-z]{13}$' }
        url: { type: string, format: uri }
        description: { type: string, maxLength: 200 }
        eventTypes: { type: array, items: { $ref: '#/components/schemas/EventType' }, description: The event types it receives; empty is every type. }
        createdAt: { type: string, format: date-time }
        secretRotatedAt: { type: [string, 'null'], format: date-time }
    WebhookEndpointWithSecret:
      allOf:
        - $ref: '#/components/schemas/WebhookEndpoint'
        - type: object
          required: [secret, previousSecretExpiresAt]
          properties:
            secret: { type: string, pattern: '^aqwh_[0-9A-Za-z]{40}$', description: The signing secret. Shown only in this answer. }
            previousSecretExpiresAt: { type: [string, 'null'], format: date-time, description: Until when the replaced secret also signs; null on creation. }
    WebhookEndpointList:
      type: object
      required: [items]
      properties:
        items: { type: array, maxItems: 3, items: { $ref: '#/components/schemas/WebhookEndpoint' } }
    CreateWebhookEndpointRequest:
      type: object
      additionalProperties: false
      required: [url]
      properties:
        url: { type: string, format: uri, maxLength: 2048, pattern: '^https://' }
        description: { type: string, maxLength: 200 }
        eventTypes: { type: array, items: { $ref: '#/components/schemas/EventType' }, description: The event types to receive; empty or absent is every type. }

    # ---------------------------------------------------------------- errors
    ErrorCode:
      type: string
      description: |
        | code | HTTP | retry |
        | --- | --- | --- |
        | `validation_failed` | 400 | `no` |
        | `api_key_invalid` | 401 | `no` |
        | `payment_password_required` | 401 | `no` |
        | `payment_password_invalid` | 401 | `no` |
        | `ip_not_allowed` | 403 | `no` |
        | `scope_missing` | 403 | `no` |
        | `account_suspended` | 403 | `no` |
        | `resource_not_found` | 404 | `no` |
        | `idempotency_conflict` | 409 | `new_key` |
        | `idempotency_key_busy` | 409 | `same_key` |
        | `duplicate_reference` | 409 | `no` |
        | `attempt_closed` | 409 | `new_key` |
        | `balance_insufficient` | 409 | `no` |
        | `wrong_state` | 409 | `no` |
        | `utr_in_use` | 409 | `no` |
        | `unsupported_by_provider` | 422 | `no` |
        | `provider_refused` | 422 | `new_key` |
        | `payment_password_locked` | 423 | `same_key` after `Retry-After` |
        | `provider_unreachable` | 424 | `new_key` on create, `same_key` on refresh and bind |
        | `too_many_requests` | 429 | `same_key` after `Retry-After` |
        | `server_error` | 500 | `same_key` |
        | `provider_outcome_unknown` | 502 | `refresh` for a payout, `new_key` for a pay-in |
        | `service_unavailable` | 503 | `same_key` after `Retry-After` |
      enum: [validation_failed, api_key_invalid, payment_password_required, payment_password_invalid, ip_not_allowed, scope_missing, account_suspended, resource_not_found, idempotency_conflict, idempotency_key_busy, duplicate_reference, attempt_closed, balance_insufficient, wrong_state, utr_in_use, unsupported_by_provider, provider_refused, payment_password_locked, provider_unreachable, too_many_requests, server_error, provider_outcome_unknown, service_unavailable]
    Retry:
      type: string
      enum: [same_key, new_key, refresh, 'no']
    ProviderDetail:
      type: [object, 'null']
      description: The provider's side of a provider error; null for errors AquaPay raised itself.
      required: [name, stage, reason, code, message]
      properties:
        name: { $ref: '#/components/schemas/Provider' }
        stage: { type: string, enum: [create, query, bind_utr] }
        reason: { oneOf: [{ $ref: '#/components/schemas/FailureReason' }, { type: 'null' }], description: 'Why it refused; null when the outcome is unknown.' }
        code: { type: [string, 'null'], description: "The provider's own code, as text." }
        message: { type: string, maxLength: 200, description: "The provider's own words, trimmed." }
    FieldError:
      type: object
      description: |
        One refused field. `rule` is what it broke, for example `required`, `format`, `type`, `unknown`, `min`, `max`,
        `whole_units`, `decimals`, `account_currency`, `method`, `url`, or for a webhook endpoint `unique` (the URL is
        already an endpoint of the account) and `max` (the account already has three endpoints).
      required: [field, rule, message]
      properties:
        field: { type: string }
        rule: { type: string }
        message: { type: string }
        limit: { $ref: '#/components/schemas/Money', description: 'The limit an amount broke (`min`, `max`).' }
    Error:
      type: object
      required: [status, code, message, requestId, retry, provider, docUrl]
      properties:
        status: { type: boolean, const: false, description: 'Always false, as in every AquaPay error body.' }
        code: { $ref: '#/components/schemas/ErrorCode' }
        message: { type: string, description: For people. May be reworded. }
        requestId: { type: string, format: uuid, description: Same as the `AquaPay-Request-Id` header. }
        retry: { $ref: '#/components/schemas/Retry' }
        provider: { $ref: '#/components/schemas/ProviderDetail' }
        docUrl: { type: string, format: uri, pattern: '^https://aquapay\.bhimpay\.online/docs/errors#[a-z_]+$', description: 'The code''s page in the docs: `https://aquapay.bhimpay.online/docs/errors#<code>`.' }
        details:
          type: object
          properties:
            fields: { type: array, maxItems: 10, items: { $ref: '#/components/schemas/FieldError' } }
          description: |
            Per code: `validation_failed` `{fields: [{field, rule, message, limit?}]}` (at most 10); `scope_missing`
            `{scope}`; `payment_password_invalid` `{remaining}`; `payment_password_locked` `{lockedUntil}`;
            `resource_not_found` `{resource}`; `duplicate_reference` `{payout}`; `attempt_closed` `{key}`;
            `balance_insufficient` `{available, required}`; `wrong_state` `{status}`; `utr_in_use` `{payinId}`;
            `provider_refused`, `provider_unreachable` and `provider_outcome_unknown` `{payin}` or `{payout}` when the
            error is about one.
          additionalProperties: true

  examples:
    # ---------------------------------------------------------------- resources
    AccountCowpay:
      summary: A live COWPAY account, password required for payouts.
      value:
        id: ga_3k9d2m7q1x8vb
        name: Example Store · COWPAY
        mode: live
        status: active
        provider: cowpay
        currency: INR
        wholeUnitsOnly: true
        payins:
          enabled: true
          limits: { min: '100.00', max: '50000.00' }
          fee: { percent: '2.5', fixed: '0.00' }
          utrBinding: true
          payerIpRequired: true
        payouts:
          enabled: true
          methods: [bank, upi]
          limits: { min: '100.00', max: '25000.00' }
          fee: { percent: '1', fixed: '0.00' }
          paymentPasswordRequired: true
        key:
          id: kid_p9w3k7e1y5t2r
          name: store-backend
          scopes: [read, 'payins:write', 'payouts:write', 'webhooks:write']
          ipAllowlist: [13.234.10.21/32]
          expiresAt: null
    AccountUpayRpl:
      summary: A live UPay RPL account; payouts go to UPay wallets.
      value:
        id: ga_8m2n6b4v0c3xz
        name: Example Store · UPay RPL
        mode: live
        status: active
        provider: upayrpl
        currency: INR
        wholeUnitsOnly: false
        payins:
          enabled: true
          limits: { min: '100.00', max: null }
          fee: { percent: '3', fixed: '0.00' }
          utrBinding: false
          payerIpRequired: false
        payouts:
          enabled: true
          methods: [upay_wallet]
          limits: { min: '200.00', max: null }
          fee: { percent: '0', fixed: '5.00' }
          paymentPasswordRequired: true
        key:
          id: kid_h4j8k2m6n0p3q
          name: store-backend
          scopes: [read, 'payins:write', 'payouts:write']
          ipAllowlist: [52.66.140.7/32]
          expiresAt: null
    PayinPending:
      summary: A COWPAY pay-in waiting for the payer.
      value:
        id: payin_7h2kq9w3m1zt4
        reference: DEP-20261203-0042
        status: pending
        amount: '500.00'
        paidAmount: null
        currency: INR
        fee: '12.50'
        net: '487.50'
        utr: null
        orderId: AQD2612030915000042
        providerOrderId: CP88123409
        nextAction:
          redirectUrl: https://pay.cowpay.example/c/CP88123409
          upiUri: upi://pay?pa=cowpay.col@ybl&pn=COWPAY&am=500.00&tr=CP88123409&cu=INR
        expiresAt: '2026-12-03T11:15:00Z'
        failure: null
        version: 1
        createdAt: '2026-12-03T09:15:00Z'
        updatedAt: '2026-12-03T09:15:00Z'
    PayinSucceeded:
      summary: Paid and credited.
      value: &payinSucceeded
        id: payin_7h2kq9w3m1zt4
        reference: DEP-20261203-0042
        status: succeeded
        amount: '500.00'
        paidAmount: '500.00'
        currency: INR
        fee: '12.50'
        net: '487.50'
        utr: '416512345678'
        orderId: AQD2612030915000042
        providerOrderId: CP88123409
        nextAction: null
        expiresAt: '2026-12-03T11:15:00Z'
        failure: null
        version: 3
        createdAt: '2026-12-03T09:15:00Z'
        updatedAt: '2026-12-03T09:15:07Z'
    PayinFailed:
      summary: The payer did not complete.
      value: &payinFailed
        id: payin_b6n2m8q4w0e7r
        reference: DEP-20261203-0051
        status: failed
        amount: '1000.00'
        paidAmount: null
        currency: INR
        fee: '25.00'
        net: '975.00'
        utr: null
        orderId: AQD2612030920000051
        providerOrderId: CP88123577
        nextAction: null
        expiresAt: '2026-12-03T11:20:00Z'
        failure: { reason: provider_failed, message: Payment failed or cancelled by user }
        version: 2
        createdAt: '2026-12-03T09:20:00Z'
        updatedAt: '2026-12-03T09:31:00Z'
    PayinExpired:
      summary: Unpaid at its expiry.
      value: &payinExpired
        id: payin_t1y5u9i3o7p2a
        reference: DEP-20261203-0044
        status: expired
        amount: '300.00'
        paidAmount: null
        currency: INR
        fee: '7.50'
        net: '292.50'
        utr: null
        orderId: AQD2612030915000044
        providerOrderId: CP88123411
        nextAction: null
        expiresAt: '2026-12-03T11:15:00Z'
        failure: null
        version: 2
        createdAt: '2026-12-03T09:15:00Z'
        updatedAt: '2026-12-03T11:15:02Z'
    PayinNeedsReview:
      summary: The provider reports a different amount paid.
      value: &payinNeedsReview
        id: payin_g5h9j3k7l1z4x
        reference: DEP-20261203-0047
        status: needs_review
        amount: '2000.00'
        paidAmount: '200.00'
        currency: INR
        fee: '50.00'
        net: '1950.00'
        utr: '416512349999'
        orderId: AQD2612030916000047
        providerOrderId: CP88123460
        nextAction: null
        expiresAt: '2026-12-03T11:16:00Z'
        failure: null
        version: 2
        createdAt: '2026-12-03T09:16:00Z'
        updatedAt: '2026-12-03T09:16:30Z'
    PayoutProcessing:
      summary: Recorded, held, sent to the provider.
      value: &payoutProcessing
        id: payout_c8n4r2v6y0jd5
        reference: WD-20261203-7781
        attemptKey: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70
        status: processing
        amount: '1500.00'
        fee: '15.00'
        total: '1515.00'
        currency: INR
        beneficiary: { type: bank, name: Ravi Kumar, masked: '••••6789' }
        utr: null
        orderId: AQW2612030918000781
        providerOrderId: CPW55012
        failure: null
        version: 2
        createdAt: '2026-12-03T09:18:41Z'
        updatedAt: '2026-12-03T09:18:42Z'
    PayoutSucceeded:
      summary: Paid.
      value: &payoutSucceeded
        id: payout_c8n4r2v6y0jd5
        reference: WD-20261203-7781
        attemptKey: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70
        status: succeeded
        amount: '1500.00'
        fee: '15.00'
        total: '1515.00'
        currency: INR
        beneficiary: { type: bank, name: Ravi Kumar, masked: '••••6789' }
        utr: '633712004455'
        orderId: AQW2612030918000781
        providerOrderId: CPW55012
        failure: null
        version: 3
        createdAt: '2026-12-03T09:18:41Z'
        updatedAt: '2026-12-03T09:19:55Z'
    PayoutFailed:
      summary: Refused by the provider at creation.
      value: &payoutFailed
        id: payout_v3b7n1m5q9w2e
        reference: WD-20261203-7790
        attemptKey: 4c8e2a6f-1b3d-4f5a-9c7e-0d2b4a6c8e1f
        status: failed
        amount: '1200.00'
        fee: '12.00'
        total: '1212.00'
        currency: INR
        beneficiary: { type: bank, name: Anil Sharma, masked: '••••0001' }
        utr: null
        orderId: AQW2612030918000790
        providerOrderId: null
        failure: { reason: beneficiary_bank_unsupported, message: 'This ifsc is not supported: AIRP0000001' }
        version: 2
        createdAt: '2026-12-03T09:18:42Z'
        updatedAt: '2026-12-03T09:18:43Z'
    PayoutNeedsReview:
      summary: The provider reports a partial payment; the amount stays held.
      value: &payoutNeedsReview
        id: payout_k1l5z9x3c7v2b
        reference: WD-20261203-7795
        attemptKey: 7e1c5a9d-3f2b-4d6e-8a0c-2e4f6a8c0d12
        status: needs_review
        amount: '5000.00'
        fee: '50.00'
        total: '5050.00'
        currency: INR
        beneficiary: { type: upi, name: Meena Patel, masked: 'me•••@oksbi' }
        utr: null
        orderId: AQW2612030920000795
        providerOrderId: RSW99031
        failure: null
        version: 3
        createdAt: '2026-12-03T09:20:00Z'
        updatedAt: '2026-12-03T09:25:10Z'
    PayoutReversed:
      summary: Paid, then returned by the provider.
      value: &payoutReversed
        id: payout_c8n4r2v6y0jd5
        reference: WD-20261203-7781
        attemptKey: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70
        status: reversed
        amount: '1500.00'
        fee: '15.00'
        total: '1515.00'
        currency: INR
        beneficiary: { type: bank, name: Ravi Kumar, masked: '••••6789' }
        utr: '633712004455'
        orderId: AQW2612030918000781
        providerOrderId: CPW55012
        failure: { reason: provider_reversed, message: Beneficiary account closed; amount returned }
        version: 4
        createdAt: '2026-12-03T09:18:41Z'
        updatedAt: '2026-12-04T06:02:11Z'
    AttemptUsed:
      summary: The key created a payout.
      value:
        key: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70
        state: used
        payout: *payoutProcessing
    EventPayinSucceeded:
      summary: A pay-in succeeded. This body is the test vector of the webhooks guide.
      value: &eventPayinSucceeded
        id: event_q2w8e5r1t7y3v
        type: payin.succeeded
        mode: live
        account: ga_3k9d2m7q1x8vb
        createdAt: '2026-12-03T09:15:07Z'
        data: *payinSucceeded

    # ---------------------------------------------------------------- errors (one per code)
    ErrValidationFailed:
      summary: validation_failed
      value:
        status: false
        code: validation_failed
        message: The request has 2 invalid fields.
        requestId: 5f0c2b8e-3a1d-4e7f-9b6a-8d2c4e1f0a93
        docUrl: 'https://aquapay.bhimpay.online/docs/errors#validation_failed'
        retry: 'no'
        provider: null
        details:
          fields:
            - { field: amount, rule: max, message: 'The most this account takes is 50000.00.', limit: '50000.00' }
            - { field: payer.ip, rule: required, message: COWPAY needs the payer's IP address. }
    ErrValidationFailedWholeUnits:
      summary: validation_failed (whole units)
      value:
        status: false
        code: validation_failed
        message: The request has 1 invalid field.
        requestId: 0d7a4c1e-8b2f-4a6d-9e3c-5f1b7a2d8c40
        docUrl: 'https://aquapay.bhimpay.online/docs/errors#validation_failed'
        retry: 'no'
        provider: null
        details:
          fields:
            - { field: amount, rule: whole_units, message: COWPAY takes whole rupees only; 100.50 is not whole. }
    ErrValidationFailedEndpointUnique:
      summary: validation_failed (a URL already registered)
      value:
        status: false
        code: validation_failed
        message: The request has 1 invalid field.
        requestId: 1c7e4a2b-9d3f-4e6a-8b1c-2d4f6a8b0c13
        retry: 'no'
        provider: null
        details:
          fields:
            - { field: url, rule: unique, message: This URL is already an endpoint of the account. }
        docUrl: 'https://aquapay.bhimpay.online/docs/errors#validation_failed'
    ErrValidationFailedEndpointMax:
      summary: validation_failed (three endpoints already)
      value:
        status: false
        code: validation_failed
        message: The request has 1 invalid field.
        requestId: 2d8f5b3c-0e4a-4f7b-9c2d-3e5a7b9c1d24
        retry: 'no'
        provider: null
        details:
          fields:
            - { field: url, rule: max, message: An account has at most 3 webhook endpoints. }
        docUrl: 'https://aquapay.bhimpay.online/docs/errors#validation_failed'
    ErrApiKeyInvalid:
      summary: api_key_invalid
      value: { status: false, code: api_key_invalid, message: 'The key is missing, malformed, unknown, revoked or expired.', requestId: 1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d, retry: 'no', provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#api_key_invalid' }
    ErrPaymentPasswordRequired:
      summary: payment_password_required
      value: { status: false, code: payment_password_required, message: This action needs the account's payment password in AquaPay-Payment-Password., requestId: 2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e, retry: 'no', provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#payment_password_required' }
    ErrPaymentPasswordInvalid:
      summary: payment_password_invalid
      value: { status: false, code: payment_password_invalid, message: The payment password is wrong., requestId: 3c4d5e6f-7a8b-4c9d-8e1f-2a3b4c5d6e7f, retry: 'no', provider: null, details: { remaining: 3 }, docUrl: 'https://aquapay.bhimpay.online/docs/errors#payment_password_invalid' }
    ErrIpNotAllowed:
      summary: ip_not_allowed
      value: { status: false, code: ip_not_allowed, message: "This key does not accept requests from 198.51.100.24.", requestId: 4d5e6f7a-8b9c-4d0e-9f2a-3b4c5d6e7f80, retry: 'no', provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#ip_not_allowed' }
    ErrScopeMissing:
      summary: scope_missing
      value: { status: false, code: scope_missing, message: "This key lacks the payouts:write scope.", requestId: 5e6f7a8b-9c0d-4e1f-8a3b-4c5d6e7f8091, retry: 'no', provider: null, details: { scope: 'payouts:write' }, docUrl: 'https://aquapay.bhimpay.online/docs/errors#scope_missing' }
    ErrAccountSuspended:
      summary: account_suspended
      value: { status: false, code: account_suspended, message: This gateway account is suspended. Contact AquaPay., requestId: 6f7a8b9c-0d1e-4f2a-9b4c-5d6e7f8091a2, retry: 'no', provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#account_suspended' }
    ErrResourceNotFound:
      summary: resource_not_found
      value: { status: false, code: resource_not_found, message: No pay-in payin_7h2kq9w3m1zt5 on this account., requestId: 7a8b9c0d-1e2f-4a3b-8c5d-6e7f8091a2b3, retry: 'no', provider: null, details: { resource: payin }, docUrl: 'https://aquapay.bhimpay.online/docs/errors#resource_not_found' }
    ErrIdempotencyConflict:
      summary: idempotency_conflict
      value: { status: false, code: idempotency_conflict, message: This Idempotency-Key was used for a different request., requestId: 8b9c0d1e-2f3a-4b4c-9d6e-7f8091a2b3c4, retry: new_key, provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#idempotency_conflict' }
    ErrIdempotencyKeyBusy:
      summary: idempotency_key_busy
      value: { status: false, code: idempotency_key_busy, message: A request with this Idempotency-Key is still running., requestId: 9c0d1e2f-3a4b-4c5d-8e7f-8091a2b3c4d5, retry: same_key, provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#idempotency_key_busy' }
    ErrDuplicateReference:
      summary: duplicate_reference
      value:
        status: false
        code: duplicate_reference
        message: Payout payout_c8n4r2v6y0jd5 already holds reference WD-20261203-7781 and is processing.
        requestId: 0d1e2f3a-4b5c-4d6e-9f80-91a2b3c4d5e6
        docUrl: 'https://aquapay.bhimpay.online/docs/errors#duplicate_reference'
        retry: 'no'
        provider: null
        details:
          payout: *payoutProcessing
    ErrAttemptClosed:
      summary: attempt_closed
      value: { status: false, code: attempt_closed, message: This attempt key was closed and can never create a payout., requestId: 1e2f3a4b-5c6d-4e7f-8091-a2b3c4d5e6f7, retry: new_key, provider: null, details: { key: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70 }, docUrl: 'https://aquapay.bhimpay.online/docs/errors#attempt_closed' }
    ErrBalanceInsufficient:
      summary: balance_insufficient
      value: { status: false, code: balance_insufficient, message: 'Available 1200.00 does not cover 1515.00 (amount and fee).', requestId: 2f3a4b5c-6d7e-4f80-91a2-b3c4d5e6f708, retry: 'no', provider: null, details: { available: '1200.00', required: '1515.00' }, docUrl: 'https://aquapay.bhimpay.online/docs/errors#balance_insufficient' }
    ErrWrongState:
      summary: wrong_state
      value: { status: false, code: wrong_state, message: 'A UTR can be bound only to a pending, failed or expired pay-in; this one succeeded.', requestId: 3a4b5c6d-7e8f-4091-a2b3-c4d5e6f70819, retry: 'no', provider: null, details: { status: succeeded }, docUrl: 'https://aquapay.bhimpay.online/docs/errors#wrong_state' }
    ErrUtrInUse:
      summary: utr_in_use
      value: { status: false, code: utr_in_use, message: UTR 416512345678 is already bound to another pay-in., requestId: 4b5c6d7e-8f90-41a2-b3c4-d5e6f708192a, retry: 'no', provider: null, details: { payinId: payin_7h2kq9w3m1zt4 }, docUrl: 'https://aquapay.bhimpay.online/docs/errors#utr_in_use' }
    ErrUnsupportedByProvider:
      summary: unsupported_by_provider
      value: { status: false, code: unsupported_by_provider, message: RSPAY pays out to bank accounts only; upi is not offered on this account., requestId: 5c6d7e8f-9001-42b3-84d5-e6f708192a3b, retry: 'no', provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#unsupported_by_provider' }
    ErrProviderRefused:
      summary: provider_refused
      value:
        status: false
        code: provider_refused
        message: 'COWPAY refused the payout: This ifsc is not supported: AIRP0000001'
        requestId: 6d7e8f90-0112-43c4-95e6-f708192a3b4c
        docUrl: 'https://aquapay.bhimpay.online/docs/errors#provider_refused'
        retry: new_key
        provider: { name: cowpay, stage: create, reason: beneficiary_bank_unsupported, code: '1002', message: 'This ifsc is not supported: AIRP0000001' }
        details:
          payout: *payoutFailed
    ErrPaymentPasswordLocked:
      summary: payment_password_locked
      value: { status: false, code: payment_password_locked, message: Too many wrong payment passwords from this key and address; try again after 09:33 UTC., requestId: 7e8f9001-1223-44d5-a6f7-08192a3b4c5d, retry: same_key, provider: null, details: { lockedUntil: '2026-12-03T09:33:00Z' }, docUrl: 'https://aquapay.bhimpay.online/docs/errors#payment_password_locked' }
    ErrProviderUnreachable:
      summary: provider_unreachable
      value:
        status: false
        code: provider_unreachable
        message: PAYME is unreachable; the pay-in was not submitted.
        requestId: 8f900112-2334-45e6-b708-192a3b4c5d6e
        docUrl: 'https://aquapay.bhimpay.online/docs/errors#provider_unreachable'
        retry: new_key
        provider: { name: payme, stage: create, reason: provider_unreachable, code: null, message: connect ECONNREFUSED }
        details:
          payin:
            id: payin_q8w2e6r0t4y1u
            reference: DEP-20261203-0060
            status: failed
            amount: '700.00'
            paidAmount: null
            currency: INR
            fee: '17.50'
            net: '682.50'
            utr: null
            orderId: AQD2612030925000060
            providerOrderId: null
            nextAction: null
            expiresAt: '2026-12-03T11:25:00Z'
            failure: { reason: provider_unreachable, message: connect ECONNREFUSED }
            version: 2
            createdAt: '2026-12-03T09:25:00Z'
            updatedAt: '2026-12-03T09:25:01Z'
    ErrTooManyRequests:
      summary: too_many_requests
      value: { status: false, code: too_many_requests, message: This account sent more than 25 requests a second., requestId: 90011223-3445-46f7-8819-2a3b4c5d6e7f, retry: same_key, provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#too_many_requests' }
    ErrServerError:
      summary: server_error
      value: { status: false, code: server_error, message: AquaPay failed before acting on the request., requestId: a0112233-4556-4708-992a-3b4c5d6e7f80, retry: same_key, provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#server_error' }
    ErrProviderOutcomeUnknown:
      summary: provider_outcome_unknown
      value:
        status: false
        code: provider_outcome_unknown
        message: 'COWPAY payout submission failed: no answer within 20 s. The payout is held processing; do not create it again.'
        requestId: b1223344-5667-4819-a3b4-c5d6e7f8091a
        docUrl: 'https://aquapay.bhimpay.online/docs/errors#provider_outcome_unknown'
        retry: refresh
        provider: { name: cowpay, stage: create, reason: null, code: null, message: no answer within 20 s }
        details:
          payout: *payoutProcessing
    ErrServiceUnavailable:
      summary: service_unavailable
      value: { status: false, code: service_unavailable, message: The account is busy; ask again., requestId: c2334455-6778-4920-b4c5-d6e7f8091a2b, retry: same_key, provider: null, docUrl: 'https://aquapay.bhimpay.online/docs/errors#service_unavailable' }

paths:
  # ------------------------------------------------------------------ account
  /account:
    get:
      tags: [account]
      operationId: getAccount
      summary: The gateway account, its capabilities, limits and fees, and the calling key.
      description: |
        Everything an integration needs to decide what to offer: whether pay-ins and payouts are enabled, the payout
        methods, limits and fees in force, whether amounts must be whole, whether UTR binding works, and whether
        this key must send the payment password. Scope `read`.
      responses:
        '200':
          description: The account.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Account' }
              examples:
                cowpayLive: { $ref: '#/components/examples/AccountCowpay' }
                upayrplLive: { $ref: '#/components/examples/AccountUpayRpl' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /balance:
    get:
      tags: [account]
      operationId: getBalance
      summary: What the account can pay out now, and what payouts in flight hold.
      description: Scope `read`.
      responses:
        '200':
          description: The balance.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Balance' }
              examples:
                balance:
                  value: { currency: INR, available: '184250.00', held: '15150.00', asOf: '2026-12-03T09:20:00Z' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /ledger:
    get:
      tags: [account]
      operationId: listLedgerEntries
      summary: The balance journal, newest first.
      description: Every change to the balance, signed. The balance is the sum of the entries. Scope `read`.
      parameters:
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: A page of entries.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LedgerPage' }
              examples:
                page:
                  value:
                    items:
                      - { id: entry_m5n1b7v3c9x2z, type: payout_hold, amount: '-1515.00', balanceAfter: '184250.00', paymentId: payout_c8n4r2v6y0jd5, note: null, createdAt: '2026-12-03T09:18:41Z' }
                      - { id: entry_k2j8h4g6f1d3s, type: fee, amount: '-12.50', balanceAfter: '185765.00', paymentId: payin_7h2kq9w3m1zt4, note: null, createdAt: '2026-12-03T09:15:07Z' }
                      - { id: entry_w9e3r7t1y5q2a, type: payin_credit, amount: '500.00', balanceAfter: '185777.50', paymentId: payin_7h2kq9w3m1zt4, note: null, createdAt: '2026-12-03T09:15:07Z' }
                    nextCursor: c1.eyJ0IjoiMjAyNi0xMi0wM1QwOToxNTowN1oiLCJpIjo4ODQxMn0
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  # ------------------------------------------------------------------ pay-ins
  /payins:
    post:
      tags: [payins]
      operationId: createPayin
      summary: Open a pay-in and get what to show the payer.
      description: |
        AquaPay records the pay-in, then asks the provider for an order. On success the pay-in is `pending` and
        `nextAction` holds the payment page URL and, where the provider gives one, a UPI intent URI. Scope
        `payins:write`.

        - `amount` must lie within `payins.limits`, and be whole when `wholeUnitsOnly` is true (PAYME, COWPAY).
        - `currency` must equal the account's currency.
        - `payer.ip` is required when `payins.payerIpRequired` is true (COWPAY).

        A provider refusal (`422 provider_refused`) or a request that never reached the provider
        (`424 provider_unreachable`) leaves the pay-in `failed`. An unclear provider answer
        (`502 provider_outcome_unknown`) leaves it `pending` with no `nextAction`; it expires on its own, and opening a
        new pay-in with a new key is safe because the payer was shown nothing. Each of these bodies carries the pay-in
        as `details.payin`.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreatePayinRequest' }
            examples:
              cowpay:
                value:
                  amount: '500'
                  currency: INR
                  reference: DEP-20261203-0042
                  payer: { id: player-88123, ip: 103.21.4.9 }
                  returnUrl: https://store.example/deposit/return
      responses:
        '201':
          description: The pay-in, `pending`.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Payin' }
              examples:
                pending: { $ref: '#/components/examples/PayinPending' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '424': { $ref: '#/components/responses/ProviderUnreachable' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }
        '502': { $ref: '#/components/responses/ProviderOutcomeUnknown' }
        '503': { $ref: '#/components/responses/ServiceUnavailable' }
    get:
      tags: [payins]
      operationId: listPayins
      summary: Pay-ins, newest first. Filter by status or by your reference.
      description: |
        `reference` finds every pay-in opened with that reference, newest first: this is the lookup by merchant
        reference. Answers come from AquaPay's records; use `POST /payins/{payinId}/refresh` to ask the provider.
        Scope `read`.
      parameters:
        - { $ref: '#/components/parameters/Cursor' }
        - { $ref: '#/components/parameters/Limit' }
        - name: status
          in: query
          schema: { $ref: '#/components/schemas/PayinStatus' }
        - { $ref: '#/components/parameters/Reference' }
      responses:
        '200':
          description: A page of pay-ins.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayinPage' }
              examples:
                byReference:
                  value:
                    items:
                      - *payinSucceeded
                    nextCursor: null
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /payins/{payinId}:
    get:
      tags: [payins]
      operationId: getPayin
      summary: One pay-in, as AquaPay has it recorded.
      description: Scope `read`.
      parameters:
        - $ref: '#/components/parameters/PayinId'
      responses:
        '200':
          description: The pay-in.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Payin' }
              examples:
                succeeded: { $ref: '#/components/examples/PayinSucceeded' }
                failed: { $ref: '#/components/examples/PayinFailed' }
                expired: { $ref: '#/components/examples/PayinExpired' }
                needsReview: { $ref: '#/components/examples/PayinNeedsReview' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /payins/{payinId}/refresh:
    post:
      tags: [payins]
      operationId: refreshPayin
      summary: Ask the provider about the pay-in now, and apply what it says.
      description: |
        Applies the provider's answer under the same rules as a provider callback, and sends the webhook if the status
        changed. A pay-in checked with the provider in the last 10 seconds is answered from the record without a new
        provider call. Works on `expired` pay-ins too, which is how a late payment is found. Scope `read`.

        A provider that cannot be asked answers `424 provider_unreachable` with `retry: same_key`; nothing changed.
      parameters:
        - $ref: '#/components/parameters/PayinId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: The pay-in after the check.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Payin' }
              examples:
                succeeded: { $ref: '#/components/examples/PayinSucceeded' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '424': { $ref: '#/components/responses/ProviderUnreachable' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /payins/{payinId}/bind-utr:
    post:
      tags: [payins]
      operationId: bindPayinUtr
      summary: Give the provider the UTR the payer reports, so it can match the payment.
      description: |
        For a `pending`, `failed` or `expired` pay-in on a provider with `payins.utrBinding` (PAYME, COWPAY). AquaPay
        sends the UTR to the provider, then refreshes the pay-in. A UTR is bound to at most one pay-in of the account,
        ever (`409 utr_in_use`). A provider that refuses the UTR answers `422 provider_refused` with the pay-in
        unchanged in `details.payin`. Scope `payins:write`.
      parameters:
        - $ref: '#/components/parameters/PayinId'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/BindUtrRequest' }
            examples:
              utr:
                value: { utr: '416512345678' }
      responses:
        '200':
          description: The pay-in after binding and the follow-up check.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Payin' }
              examples:
                succeeded: { $ref: '#/components/examples/PayinSucceeded' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '424': { $ref: '#/components/responses/ProviderUnreachable' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  # ------------------------------------------------------------------ payouts
  /payouts/quote:
    get:
      tags: [payouts]
      operationId: quotePayout
      summary: The fee and total debit for a payout amount, and whether the balance covers it now.
      description: |
        Pure arithmetic on the account's fees and balance; nothing is reserved. `total` is what creation would debit
        (`amount + fee`). An amount outside `payouts.limits` or not whole where it must be is `400 validation_failed`.
        Scope `read`.
      parameters:
        - name: amount
          in: query
          required: true
          schema: { $ref: '#/components/schemas/MoneyInput' }
          example: '1500'
      responses:
        '200':
          description: The quote.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayoutQuote' }
              examples:
                quote:
                  value: { amount: '1500.00', fee: '15.00', total: '1515.00', currency: INR, sufficientBalance: true }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /payouts:
    post:
      tags: [payouts]
      operationId: createPayout
      summary: Send money to a bank account, a UPI VPA or a UPay wallet.
      description: |
        Money safety, in order:

        1. Under the account's lock, AquaPay checks the balance, the reference and the attempt key, and writes the
           payout `processing`, holding `total`, before anything is sent.
        2. Then it calls the provider once. The `Idempotency-Key` is the payout's **attempt key**: it reaches a provider
           at most once, ever.
        3. A definite refusal fails the payout and releases the hold: `422 provider_refused`, or
           `424 provider_unreachable` when the request provably never left. Send a corrected payout with a new key.
        4. Anything unclear (a timeout, a `5xx`, an unreadable answer) keeps the payout `processing` with the amount
           held: `502 provider_outcome_unknown`, `retry: refresh`. Never create it again; refresh it or wait for its
           webhook.

        Each of these bodies carries the payout as `details.payout`. Needs scope `payouts:write` and the payment
        password.

        `beneficiary.type` must be one of `payouts.methods`. `reference` must not be held by another payout that is
        still `processing`, `succeeded` or `needs_review` (`409 duplicate_reference`); a failed payout's reference may
        be reused.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
        - $ref: '#/components/parameters/PaymentPassword'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreatePayoutRequest' }
            examples:
              bank:
                value:
                  amount: '1500'
                  currency: INR
                  reference: WD-20261203-7781
                  beneficiary: { type: bank, name: Ravi Kumar, accountNumber: '50100123456789', ifsc: HDFC0001234 }
                  narration: Payout from Example Store
              upi:
                value:
                  amount: '800'
                  currency: INR
                  reference: WD-20261203-7782
                  beneficiary: { type: upi, name: Ravi Kumar, vpa: ravi.kumar@okhdfcbank }
              upayWallet:
                value:
                  amount: '2500'
                  currency: INR
                  reference: WD-20261203-7783
                  beneficiary: { type: upay_wallet, address: UPW9f3kq2m8x7n4v1 }
      responses:
        '200':
          description: A repeat of a payout request whose stored answer has expired (after 24 hours); the payout as it stands now.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Payout' }
              examples:
                succeeded: { $ref: '#/components/examples/PayoutSucceeded' }
        '201':
          description: The payout, `processing` (rarely already `succeeded`).
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Payout' }
              examples:
                processing: { $ref: '#/components/examples/PayoutProcessing' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '423': { $ref: '#/components/responses/Locked' }
        '424': { $ref: '#/components/responses/ProviderUnreachable' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }
        '502': { $ref: '#/components/responses/ProviderOutcomeUnknown' }
        '503': { $ref: '#/components/responses/ServiceUnavailable' }
    get:
      tags: [payouts]
      operationId: listPayouts
      summary: Payouts, newest first. Filter by status or by your reference.
      description: Answers come from AquaPay's records. Scope `read`.
      parameters:
        - { $ref: '#/components/parameters/Cursor' }
        - { $ref: '#/components/parameters/Limit' }
        - name: status
          in: query
          schema: { $ref: '#/components/schemas/PayoutStatus' }
        - { $ref: '#/components/parameters/Reference' }
      responses:
        '200':
          description: A page of payouts.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayoutPage' }
              examples:
                processing:
                  value:
                    items:
                      - *payoutProcessing
                    nextCursor: c1.eyJ0IjoiMjAyNi0xMi0wM1QwOToxODo0MVoiLCJpIjo0MjE3fQ
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /payouts/{payoutId}:
    get:
      tags: [payouts]
      operationId: getPayout
      summary: One payout, as AquaPay has it recorded.
      description: Scope `read`.
      parameters:
        - $ref: '#/components/parameters/PayoutId'
      responses:
        '200':
          description: The payout.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Payout' }
              examples:
                succeeded: { $ref: '#/components/examples/PayoutSucceeded' }
                failed: { $ref: '#/components/examples/PayoutFailed' }
                needsReview: { $ref: '#/components/examples/PayoutNeedsReview' }
                reversed: { $ref: '#/components/examples/PayoutReversed' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /payouts/{payoutId}/refresh:
    post:
      tags: [payouts]
      operationId: refreshPayout
      summary: Ask the provider about the payout now, and apply what it says.
      description: |
        Applies only the provider's evidence about this exact order: an answer that names another order, or no order,
        changes nothing. A paid payout is reversed only by the provider's own word about it. A payout checked in the
        last 10 seconds is answered from the record. Scope `read`.
      parameters:
        - $ref: '#/components/parameters/PayoutId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: The payout after the check.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Payout' }
              examples:
                succeeded: { $ref: '#/components/examples/PayoutSucceeded' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '424': { $ref: '#/components/responses/ProviderUnreachable' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /payout-attempts/{attemptKey}:
    get:
      tags: [payouts]
      operationId: getPayoutAttempt
      summary: What became of a payout attempt key.
      description: |
        `used` with its payout, `closed` (retired; it can never create a payout) or `unused` (AquaPay never saw it).
        The answer after a lost or timed-out create call. Scope `read`.
      parameters:
        - $ref: '#/components/parameters/AttemptKey'
      responses:
        '200':
          description: The attempt.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayoutAttempt' }
              examples:
                used: { $ref: '#/components/examples/AttemptUsed' }
                unused:
                  value: { key: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70, state: unused, payout: null }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /payout-attempts/{attemptKey}/close:
    post:
      tags: [payouts]
      operationId: closePayoutAttempt
      summary: Retire an attempt key that created nothing, so it never can.
      description: |
        Under the same lock payout creation takes: if the key already created a payout, the answer is `used` with that
        payout and nothing changes; otherwise the key is retired for good and the answer is `closed`. A later create
        with it is `409 attempt_closed`. Closing is how a client that lost a create call proves that no payout will
        appear, before it tries again with a new key. Scope `payouts:write`.
      parameters:
        - $ref: '#/components/parameters/AttemptKey'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '200':
          description: The attempt after closing.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PayoutAttempt' }
              examples:
                closed:
                  value: { key: 9b2f61c4-7d0e-4a8b-b3f5-2c6e8a1d4f70, state: closed, payout: null }
                used: { $ref: '#/components/examples/AttemptUsed' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '409': { $ref: '#/components/responses/Conflict' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }
        '503': { $ref: '#/components/responses/ServiceUnavailable' }

  # ------------------------------------------------------------------ events
  /events:
    get:
      tags: [events]
      operationId: listEvents
      summary: The account's events, oldest first, for polling.
      description: |
        The same events the webhooks deliver, kept for 30 days. Unlike the other lists this one runs oldest first,
        and `nextCursor` is never null: store it and poll again with it to get only newer events. Without a cursor the
        list starts at the oldest event kept. Scope `read`.

        With `wait`, a page that would be empty is held open until an event arrives or `wait` seconds pass: a long
        poll, which follows the stream as it happens without a public endpoint.
      parameters:
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
        - name: wait
          in: query
          description: Seconds to hold an empty page open for the next event (0 to 30; 0 answers at once).
          schema: { type: integer, minimum: 0, maximum: 30, default: 0 }
      responses:
        '200':
          description: A page of events.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EventPage' }
              examples:
                page:
                  value:
                    items:
                      - *eventPayinSucceeded
                    nextCursor: e1.88412
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  # ------------------------------------------------------------------ webhook endpoints
  /webhook-endpoints:
    get:
      tags: [webhooks]
      operationId: listWebhookEndpoints
      summary: The account's webhook endpoints (at most three).
      description: Scope `read`. Signing secrets are never returned here.
      responses:
        '200':
          description: The endpoints.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookEndpointList' }
              examples:
                one:
                  value:
                    items:
                      - { id: hook_a4s8d2f6g0h3j, url: 'https://api.store.example/aquapay/webhooks/COWPAY_MAIN', description: Example Store backend, eventTypes: [], createdAt: '2026-12-03T08:00:00Z', secretRotatedAt: null }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }
    post:
      tags: [webhooks]
      operationId: createWebhookEndpoint
      summary: Add an HTTPS endpoint. The signing secret is in this answer only.
      description: |
        An endpoint receives every event of the account, or only the `eventTypes` it names. The URL must be `https`,
        public, without credentials or a fragment, and not already registered on the account; an account has at most
        three. Needs scope `webhooks:write` and the payment password.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
        - $ref: '#/components/parameters/PaymentPassword'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateWebhookEndpointRequest' }
            examples:
              url:
                value: { url: 'https://api.store.example/aquapay/webhooks/COWPAY_MAIN', description: Example Store backend }
      responses:
        '201':
          description: The endpoint and its signing secret, shown once.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookEndpointWithSecret' }
              examples:
                created:
                  value:
                    id: hook_a4s8d2f6g0h3j
                    url: 'https://api.store.example/aquapay/webhooks/COWPAY_MAIN'
                    description: Example Store backend
                    eventTypes: []
                    createdAt: '2026-12-03T08:00:00Z'
                    secretRotatedAt: null
                    secret: aqwh_Zt8kP3vQ9mW2xR6nB1cY7hJ4gF0sD5aL8eT3uK6q
                    previousSecretExpiresAt: null
        '400':
          description: '`validation_failed`: a bad URL, a URL already registered (`rule: unique`) or a fourth endpoint (`rule: max`).'
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                validation_failed: { $ref: '#/components/examples/ErrValidationFailed' }
                unique: { $ref: '#/components/examples/ErrValidationFailedEndpointUnique' }
                max: { $ref: '#/components/examples/ErrValidationFailedEndpointMax' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '409': { $ref: '#/components/responses/Conflict' }
        '423': { $ref: '#/components/responses/Locked' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /webhook-endpoints/{endpointId}:
    delete:
      tags: [webhooks]
      operationId: deleteWebhookEndpoint
      summary: Stop delivering to an endpoint.
      description: |
        Pending deliveries to it are dropped; the events stay in `/events`. Deleting an endpoint this account already
        deleted answers `204` again, so a retry is safe without an `Idempotency-Key`. Needs scope `webhooks:write` and
        the payment password.
      parameters:
        - $ref: '#/components/parameters/EndpointId'
        - $ref: '#/components/parameters/PaymentPassword'
      responses:
        '204':
          description: Deleted.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '423': { $ref: '#/components/responses/Locked' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /webhook-endpoints/{endpointId}/rotate-secret:
    post:
      tags: [webhooks]
      operationId: rotateWebhookSecret
      summary: Replace an endpoint's signing secret, with 24 hours of overlap.
      description: |
        For 24 hours every delivery to the endpoint carries two `sha256` signatures, one per secret, so a receiver that
        holds either secret keeps verifying while it switches. Needs scope `webhooks:write` and the payment password.
      parameters:
        - $ref: '#/components/parameters/EndpointId'
        - $ref: '#/components/parameters/IdempotencyKey'
        - $ref: '#/components/parameters/PaymentPassword'
      responses:
        '200':
          description: The endpoint and its new secret, shown once.
          headers:
            AquaPay-Request-Id: { $ref: '#/components/headers/RequestId' }
            AquaPay-Idempotent-Replay: { $ref: '#/components/headers/IdempotentReplay' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookEndpointWithSecret' }
              examples:
                rotated:
                  value:
                    id: hook_a4s8d2f6g0h3j
                    url: 'https://api.store.example/aquapay/webhooks/COWPAY_MAIN'
                    description: Example Store backend
                    eventTypes: []
                    createdAt: '2026-12-03T08:00:00Z'
                    secretRotatedAt: '2026-12-10T08:00:00Z'
                    secret: aqwh_Qm4nX8bV2cZ6aS0dF3gH7jK1lP5oW9eR2tY4uI8o
                    previousSecretExpiresAt: '2026-12-11T08:00:00Z'
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '423': { $ref: '#/components/responses/Locked' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

# ------------------------------------------------------------------ outbound webhooks
webhooks:
  payin.succeeded:
    post:
      operationId: onPayinSucceeded
      summary: The payer paid, the amount matches, and `net` was credited.
      description: Credit the payer `paidAmount`. Also sent for a late payment on a `failed` or `expired` pay-in.
      parameters: [{ $ref: '#/components/parameters/Signature' }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayinEvent' }
            examples:
              event: { $ref: '#/components/examples/EventPayinSucceeded' }
      responses:
        '200': { description: Any 2xx within 10 seconds is a delivery. The body is ignored. }
  payin.failed:
    post:
      operationId: onPayinFailed
      summary: The provider refused or failed the pay-in. Nothing was credited.
      parameters: [{ $ref: '#/components/parameters/Signature' }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayinEvent' }
            examples:
              event:
                value:
                  id: event_f3g7h1j5k9l2m
                  type: payin.failed
                  mode: live
                  account: ga_3k9d2m7q1x8vb
                  createdAt: '2026-12-03T09:31:00Z'
                  data: *payinFailed
      responses:
        '200': { description: Any 2xx within 10 seconds is a delivery. }
  payin.expired:
    post:
      operationId: onPayinExpired
      summary: Nobody paid before `expiresAt`. A later payment still arrives as `payin.succeeded`.
      parameters: [{ $ref: '#/components/parameters/Signature' }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayinEvent' }
            examples:
              event:
                value:
                  id: event_x7c3v9b5n1m8q
                  type: payin.expired
                  mode: live
                  account: ga_3k9d2m7q1x8vb
                  createdAt: '2026-12-03T11:15:02Z'
                  data: *payinExpired
      responses:
        '200': { description: Any 2xx within 10 seconds is a delivery. }
  payin.needs_review:
    post:
      operationId: onPayinNeedsReview
      summary: The provider's evidence does not settle the pay-in (a different amount, a partial payment). Nothing was credited; AquaPay staff resolve it.
      parameters: [{ $ref: '#/components/parameters/Signature' }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayinEvent' }
            examples:
              event:
                value:
                  id: event_r5t9y3u7i1o4p
                  type: payin.needs_review
                  mode: live
                  account: ga_3k9d2m7q1x8vb
                  createdAt: '2026-12-03T09:16:30Z'
                  data: *payinNeedsReview
      responses:
        '200': { description: Any 2xx within 10 seconds is a delivery. }
  payout.succeeded:
    post:
      operationId: onPayoutSucceeded
      summary: The provider confirmed the beneficiary was paid exactly `amount`.
      parameters: [{ $ref: '#/components/parameters/Signature' }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayoutEvent' }
            examples:
              event:
                value:
                  id: event_d2f6g0h4j8k1l
                  type: payout.succeeded
                  mode: live
                  account: ga_3k9d2m7q1x8vb
                  createdAt: '2026-12-03T09:19:55Z'
                  data: *payoutSucceeded
      responses:
        '200': { description: Any 2xx within 10 seconds is a delivery. }
  payout.failed:
    post:
      operationId: onPayoutFailed
      summary: The payout failed and its hold was released. Nothing reached the beneficiary.
      parameters: [{ $ref: '#/components/parameters/Signature' }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayoutEvent' }
            examples:
              event:
                value:
                  id: event_s8d4f2g6h0j3k
                  type: payout.failed
                  mode: live
                  account: ga_3k9d2m7q1x8vb
                  createdAt: '2026-12-03T09:18:43Z'
                  data: *payoutFailed
      responses:
        '200': { description: Any 2xx within 10 seconds is a delivery. }
  payout.needs_review:
    post:
      operationId: onPayoutNeedsReview
      summary: The provider's evidence is contradictory (a different amount, partial, frozen). The amount stays held; AquaPay staff resolve it.
      parameters: [{ $ref: '#/components/parameters/Signature' }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayoutEvent' }
            examples:
              event:
                value:
                  id: event_z1x5c9v3b7n2m
                  type: payout.needs_review
                  mode: live
                  account: ga_3k9d2m7q1x8vb
                  createdAt: '2026-12-03T09:25:10Z'
                  data: *payoutNeedsReview
      responses:
        '200': { description: Any 2xx within 10 seconds is a delivery. }
  payout.reversed:
    post:
      operationId: onPayoutReversed
      summary: The provider returned a paid payout. `total` is back in the balance.
      parameters: [{ $ref: '#/components/parameters/Signature' }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PayoutEvent' }
            examples:
              event:
                value:
                  id: event_n6m2b8v4c0x7z
                  type: payout.reversed
                  mode: live
                  account: ga_3k9d2m7q1x8vb
                  createdAt: '2026-12-04T06:02:11Z'
                  data: *payoutReversed
      responses:
        '200': { description: Any 2xx within 10 seconds is a delivery. }
