openapi: 3.1.0
info:
  title: NuruPay API
  version: "2026-09-29"
  summary: Collect mobile-money payments in Tanzania with one API.
  description: |
    The NuruPay API is organised around REST. Requests and responses are JSON,
    amounts are integers in the currency's minor unit (TZS has no minor unit:
    `15000` means TZS 15,000), and every response carries an `X-Request-Id`.

    Use a **test** key (`np_test_sk_…`) to build against the simulator; no real
    money moves. Switch to a **live** key (`np_live_sk_…`) once NuruPay has
    enabled live mode for your account.
  contact:
    name: NuruPay
    url: https://docs.nurupay.io
servers:
  - url: https://api.nurupay.io
    description: Production (test and live mode are chosen by the API key)
security:
  - apiKey: []
tags:
  - name: Collections
    description: Charge a customer's mobile-money wallet with a USSD push (PIN prompt on their phone).
  - name: Balance
    description: Pending, available, and reserved funds per mode.
  - name: Events
    description: The event objects that webhooks deliver, fetchable by ID.
  - name: Account
    description: Check which merchant and mode an API key belongs to.
  - name: Webhooks
    description: Events NuruPay POSTs to your webhook endpoints.

paths:
  /v1/whoami:
    get:
      operationId: whoami
      tags: [Account]
      summary: Identify the API key
      description: Returns the merchant and mode the API key belongs to. Useful to check a key works.
      responses:
        "200":
          description: The authenticated principal.
          headers: {X-Request-Id: {$ref: "#/components/headers/X-Request-Id"}}
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Principal"}
        "401": {$ref: "#/components/responses/Unauthorized"}
        "403": {$ref: "#/components/responses/Forbidden"}
        "429": {$ref: "#/components/responses/RateLimited"}

  /v1/collections:
    post:
      operationId: createCollection
      tags: [Collections]
      summary: Create a collection
      description: |
        Starts a USSD push to the customer's phone. The response is `202` with
        `status: created`; the customer then approves the PIN prompt. Listen for
        the `collection.succeeded` / `collection.failed` / `collection.expired`
        webhooks, or poll `GET /v1/collections/{id}`.

        The fee is fixed at creation and deducted from the amount you receive.
      parameters:
        - {$ref: "#/components/parameters/IdempotencyKey"}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/CreateCollectionRequest"}
            example: {amount: 15000, phone: "0754123456", reference: "ORDER-1029", description: "Order 1029", metadata: {cart_id: abc}}
      responses:
        "202":
          description: Collection created; the USSD push is being sent.
          headers:
            X-Request-Id: {$ref: "#/components/headers/X-Request-Id"}
            Idempotent-Replayed: {$ref: "#/components/headers/Idempotent-Replayed"}
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Collection"}
        "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"}
        "429": {$ref: "#/components/responses/RateLimited"}
    get:
      operationId: listCollections
      tags: [Collections]
      summary: List collections
      description: Newest first. Page with `starting_after` set to the last `id` of the previous page while `has_more` is true.
      parameters:
        - name: limit
          in: query
          schema: {type: integer, minimum: 1, maximum: 100, default: 20}
        - name: starting_after
          in: query
          description: A collection ID; returns collections created before it.
          schema: {type: string, pattern: "^col_[0-9A-HJKMNP-TV-Z]{26}$"}
      responses:
        "200":
          description: A page of collections.
          headers: {X-Request-Id: {$ref: "#/components/headers/X-Request-Id"}}
          content:
            application/json:
              schema: {$ref: "#/components/schemas/CollectionList"}
        "400": {$ref: "#/components/responses/BadRequest"}
        "401": {$ref: "#/components/responses/Unauthorized"}
        "403": {$ref: "#/components/responses/Forbidden"}
        "429": {$ref: "#/components/responses/RateLimited"}

  /v1/collections/{id}:
    get:
      operationId: getCollection
      tags: [Collections]
      summary: Retrieve a collection
      parameters:
        - name: id
          in: path
          required: true
          schema: {type: string, example: col_01M3P5EQVNA1FBT259FK4XPHJR}
      responses:
        "200":
          description: The collection.
          headers: {X-Request-Id: {$ref: "#/components/headers/X-Request-Id"}}
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Collection"}
        "401": {$ref: "#/components/responses/Unauthorized"}
        "403": {$ref: "#/components/responses/Forbidden"}
        "404": {$ref: "#/components/responses/NotFound"}
        "429": {$ref: "#/components/responses/RateLimited"}

  /v1/balance:
    get:
      operationId: getBalance
      tags: [Balance]
      summary: Retrieve your balance
      description: Balances for the key's mode. `pending` becomes `available` when collections settle (T+1 by default, at 00:00 EAT).
      responses:
        "200":
          description: Balance.
          headers: {X-Request-Id: {$ref: "#/components/headers/X-Request-Id"}}
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Balance"}
        "401": {$ref: "#/components/responses/Unauthorized"}
        "403": {$ref: "#/components/responses/Forbidden"}
        "429": {$ref: "#/components/responses/RateLimited"}

  /v1/events/{id}:
    get:
      operationId: getEvent
      tags: [Events]
      summary: Retrieve an event
      description: Fetch an event by the `id` a webhook delivered, e.g. to confirm a webhook is genuine.
      parameters:
        - name: id
          in: path
          required: true
          schema: {type: string, example: evt_01M3P5FBS9V5FJ1P5R0N8Z64XX}
      responses:
        "200":
          description: The event.
          headers: {X-Request-Id: {$ref: "#/components/headers/X-Request-Id"}}
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Event"}
        "401": {$ref: "#/components/responses/Unauthorized"}
        "403": {$ref: "#/components/responses/Forbidden"}
        "404": {$ref: "#/components/responses/NotFound"}
        "429": {$ref: "#/components/responses/RateLimited"}

webhooks:
  collection.succeeded:
    post:
      operationId: webhookCollectionSucceeded
      tags: [Webhooks]
      summary: A collection was paid
      description: |
        Sent to your webhook endpoints when a collection succeeds. Verify the
        `NuruPay-Signature` header before trusting the body. Delivery is
        at-least-once and unordered: deduplicate on `id` and fetch the object
        for its current state if order matters. Respond with any 2xx within 10s;
        otherwise NuruPay retries after 1m, 5m, 30m, 2h, 6h, and 12h.
      parameters: [{$ref: "#/components/parameters/NuruPaySignature"}]
      requestBody:
        content:
          application/json:
            schema: {$ref: "#/components/schemas/CollectionEventPayload"}
      responses:
        "200": {description: Acknowledge receipt with any 2xx.}
  collection.failed:
    post:
      operationId: webhookCollectionFailed
      tags: [Webhooks]
      summary: A collection failed
      description: The customer declined, had insufficient funds, or the payment was rejected. `data.failure_code` says why.
      parameters: [{$ref: "#/components/parameters/NuruPaySignature"}]
      requestBody:
        content:
          application/json:
            schema: {$ref: "#/components/schemas/CollectionEventPayload"}
      responses:
        "200": {description: Acknowledge receipt with any 2xx.}
  collection.expired:
    post:
      operationId: webhookCollectionExpired
      tags: [Webhooks]
      summary: A collection expired unpaid
      description: The customer did not approve the prompt in time; the order was cancelled at the provider.
      parameters: [{$ref: "#/components/parameters/NuruPaySignature"}]
      requestBody:
        content:
          application/json:
            schema: {$ref: "#/components/schemas/CollectionEventPayload"}
      responses:
        "200": {description: Acknowledge receipt with any 2xx.}

components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      bearerFormat: np_(live|test)_sk_…
      description: "`Authorization: Bearer np_test_sk_…`. The key's prefix selects test or live mode."

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: |
        Unique per operation (1–255 printable ASCII characters), e.g. a UUID.
        Retrying with the same key and body returns the original response with
        `Idempotent-Replayed: true`; the same key with a different body returns
        `409 idempotency_key_reused`. Keys are kept for 24 hours.
      schema: {type: string, minLength: 1, maxLength: 255}
    NuruPaySignature:
      name: NuruPay-Signature
      in: header
      required: true
      description: '`t=<unix seconds>,v1=<hex HMAC-SHA256(signing_secret, "<t>.<raw body>")>`. Reject if the signature does not match or `t` is more than 5 minutes old.'
      schema: {type: string, example: "t=1759132800,v1=c57e6ec5e76a0cdd68ee3fd1eba420ff9abf04cd9755d174d59e1c4d6e926a54"}

  headers:
    X-Request-Id:
      description: Unique ID for this request; quote it to support.
      schema: {type: string, example: req_01M3P44HNMABSHMWA98XWDH8XP}
    Idempotent-Replayed:
      description: "`true` when this response is a replay of an earlier request with the same `Idempotency-Key`."
      schema: {type: string, enum: ["true"]}
    Retry-After:
      description: Seconds to wait before retrying.
      schema: {type: integer, minimum: 1}

  responses:
    BadRequest:
      description: Invalid request (bad field, malformed JSON, missing or invalid Idempotency-Key).
      content: {application/json: {schema: {$ref: "#/components/schemas/Error"}}}
    Unauthorized:
      description: "Missing, invalid, or revoked key (`invalid_api_key`), or an expired rolled key (`api_key_expired`)."
      content: {application/json: {schema: {$ref: "#/components/schemas/Error"}}}
    Forbidden:
      description: "`ip_not_allowed`, `merchant_suspended`, or `live_mode_not_enabled`."
      content: {application/json: {schema: {$ref: "#/components/schemas/Error"}}}
    NotFound:
      description: No such object for this key's merchant and mode.
      content: {application/json: {schema: {$ref: "#/components/schemas/Error"}}}
    Conflict:
      description: "`duplicate_reference`, `idempotency_key_reused`, or `idempotency_request_in_progress`."
      content: {application/json: {schema: {$ref: "#/components/schemas/Error"}}}
    Unprocessable:
      description: "Valid JSON the API cannot act on: `amount_too_small`, `amount_too_large`, `unsupported_channel` (number's network not detected)."
      content: {application/json: {schema: {$ref: "#/components/schemas/Error"}}}
    RateLimited:
      description: Too many requests for this key (50/s sustained, bursts of 100).
      headers: {Retry-After: {$ref: "#/components/headers/Retry-After"}}
      content: {application/json: {schema: {$ref: "#/components/schemas/Error"}}}

  schemas:
    Mode:
      type: string
      enum: [live, test]
    Channel:
      type: string
      enum: [MPESA_TZ, AIRTEL_MONEY_TZ, MIXX_BY_YAS, HALOPESA, TPESA]
      description: Mobile-money network. Detected from the phone number's prefix when omitted.
    CollectionStatus:
      type: string
      enum: [created, pending, succeeded, failed, expired]
      description: |
        `created` → `pending` (PIN prompt sent) → `succeeded`, `failed`, or `expired`.
        Terminal states never change.
    FailureCode:
      type: string
      enum: [insufficient_funds, invalid_account, account_not_registered, customer_cancelled, customer_timeout,
             limit_exceeded, duplicate_reference, provider_rejected, provider_unavailable]

    CreateCollectionRequest:
      type: object
      additionalProperties: false
      required: [amount, phone, reference]
      properties:
        amount: {type: integer, minimum: 100, maximum: 5000000, description: Amount in TZS.}
        currency: {type: string, enum: [TZS], default: TZS}
        phone: {type: string, description: "Tanzanian mobile number: `07XXXXXXXX`, `06XXXXXXXX`, `2557…`, or `+2557…`.", example: "0754123456"}
        channel: {$ref: "#/components/schemas/Channel"}
        reference: {type: string, minLength: 1, maxLength: 100, description: Your unique ID for this payment (e.g. order number).}
        description: {type: string, maxLength: 255}
        metadata: {type: object, maxProperties: 20, description: "Up to 20 keys of your own data, returned unchanged (max 4 KB)."}

    Collection:
      type: object
      required: [id, object, status, amount, fee, currency, channel, phone, reference, description, metadata,
                 failure_code, failure_message, mode, created_at, completed_at]
      properties:
        id: {type: string, pattern: "^col_[0-9A-HJKMNP-TV-Z]{26}$"}
        object: {type: string, const: collection}
        status: {$ref: "#/components/schemas/CollectionStatus"}
        amount: {type: integer}
        fee: {type: integer, description: "NuruPay fee in TZS, deducted from what you receive."}
        currency: {type: string, enum: [TZS]}
        channel: {$ref: "#/components/schemas/Channel"}
        phone: {type: string, pattern: "^255[67][0-9]{8}$", description: Normalised customer number.}
        reference: {type: string}
        description: {type: string}
        metadata: {type: object}
        failure_code:
          oneOf: [{$ref: "#/components/schemas/FailureCode"}, {type: "null"}]
        failure_message: {type: [string, "null"]}
        mode: {$ref: "#/components/schemas/Mode"}
        created_at: {type: string, format: date-time}
        completed_at: {type: [string, "null"], format: date-time}

    CollectionList:
      type: object
      required: [object, data, has_more]
      properties:
        object: {type: string, const: list}
        data: {type: array, items: {$ref: "#/components/schemas/Collection"}}
        has_more: {type: boolean}

    Balance:
      type: object
      required: [object, mode, currency, pending, available, reserved]
      properties:
        object: {type: string, const: balance}
        mode: {$ref: "#/components/schemas/Mode"}
        currency: {type: string, enum: [TZS]}
        pending: {type: integer, description: "Collected, not yet settled."}
        available: {type: integer, description: Settled and yours to withdraw.}
        reserved: {type: integer, description: Held for in-flight payouts.}

    Event:
      type: object
      required: [id, object, type, created_at, mode, data]
      properties:
        id: {type: string, pattern: "^evt_[0-9A-HJKMNP-TV-Z]{26}$"}
        object: {type: string, const: event}
        type: {type: string, enum: [collection.succeeded, collection.failed, collection.expired]}
        created_at: {type: string, format: date-time}
        mode: {$ref: "#/components/schemas/Mode"}
        data: {$ref: "#/components/schemas/Collection"}

    CollectionEventPayload:
      type: object
      required: [id, type, created_at, mode, data]
      properties:
        id: {type: string, description: Event ID; deduplicate on it.}
        type: {type: string, enum: [collection.succeeded, collection.failed, collection.expired]}
        created_at: {type: string, format: date-time}
        mode: {$ref: "#/components/schemas/Mode"}
        data: {$ref: "#/components/schemas/Collection"}

    Principal:
      type: object
      required: [object, merchant_id, mode, key_id]
      properties:
        object: {type: string, const: principal}
        merchant_id: {type: string}
        mode: {$ref: "#/components/schemas/Mode"}
        key_id: {type: string}

    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [type, code, message, request_id]
          properties:
            type:
              type: string
              enum: [invalid_request_error, authentication_error, permission_error, balance_error, rate_limit_error,
                     provider_error, api_error]
            code: {type: string, description: "Stable machine-readable code, e.g. `invalid_phone`."}
            message: {type: string, description: Human-readable; may change.}
            param: {type: string, description: "The request field at fault, when applicable."}
            request_id: {type: string}
