> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloudpay.africa/llms.txt
> Use this file to discover all available pages before exploring further.

# Switch between live and test

> Moves the session to the paired environment without logging in again. The same phone number's
person account in the other environment is used and the current device is bound to it.
Switching to test creates the test account (no PIN) if missing. Returning to production requires
the session you switched from to still be active; otherwise 403 device_verification_required and
the client must do a normal live login. A test session from a fresh test login can never go live.
The previous token keeps working in its own environment.




## OpenAPI

````yaml /openapi.yaml post /v1/auth/switch
openapi: 3.1.0
info:
  title: CloudPay Core API
  version: 0.1.0
  summary: Wallet, ledger and payments API for CloudPay (Phase 0).
  description: >+
    cloudpay-core is the system of record for CloudPay e-money. Every shilling
    moves

    through a double-entry ledger that the database itself keeps balanced.


    ## Conventions

    - **Money** is always an integer number of **cents** (KES minor units).
    `150000` = KES 1,500.00.
      Never send decimals or floats.
    - **Phone numbers** accept `07XXXXXXXX`, `01XXXXXXXX`, `+2547XXXXXXXX` or
    `2547XXXXXXXX`
      and are returned as `2547XXXXXXXX`.
    - **Envelope**: every response is `{"status": {"ok", "code", "desc"},
    "data": ...}` on success
      and `{"status": ..., "errors": {"code", "message"}}` on failure. Branch on `errors.code`,
      which is stable; `message` is for humans.
    - **Tenancy**: unauthenticated endpoints name the tenant with `X-Tenant-ID`:
    its short slug
      (`cloudpay`) or UUID. Without the header they use the platform tenant (DEFAULT_TENANT_ID).
      Authenticated endpoints take the tenant from the token.
    - **Idempotency**: every money-moving request carries an `idempotency_key`
    (8-100 chars,
      unique per customer). Retrying with the same key and the same body returns the original
      result; the same key with a different body returns `409 idempotency_key_reused`.
    - **PIN step-up**: money leaving a wallet always needs the customer's PIN in
    the request,
      even with a valid token.

    ## Flows

    1. **Onboard**: `POST /v1/auth/otp` (purpose `register`) -> `POST
    /v1/auth/register`.

    2. **Login on a known device**: `POST /v1/auth/login` with PIN.
       **On a new device**: the first login returns `403 device_verification_required`;
       request an OTP with purpose `login`, then log in again with `otp`.
    3. **Top up from M-Pesa**: `POST /v1/topups/mpesa` sends an STK prompt and
    returns `pending`.
       The wallet is credited only after cloudpay-rails confirms. Poll `GET /v1/topups/{id}`
       until `completed`, `failed` or `review`.
    4. **Send money**: optionally `GET /v1/parties/lookup` to show the
    recipient's name, then
       `POST /v1/transfers`.

    ## Environments

    | Environment | Base URL | Money | M-Pesa | OTP |

    |---|---|---|---|---|

    | Production | `https://api.cloudpay.africa/cloudpay` | real | real
    (cloudpay-rails) | SMS |

    | Development (an `sk_test_` key or test session) |
    `https://api.cloudpay.africa/cloudpay` | real STK up to KES 100 per prompt
    and KES 1,000 per day, no payouts; carried to Production on approval |
    CloudPay platform rail | SMS never sent; `123456` accepted for any code you
    requested |

    | Local dev | `http://localhost:8080` | as above | provider sandboxes
    (cloudpay-rails) | `123456` for every tenant, plus `dev_code` in responses |


    There is one deployment: the key (`sk_test_` / `sk_live_`) and the tenant's
    mode choose the environment.


    Every response that resolves a tenant carries `X-CloudPay-Environment: live`
    or `test`, taken from the

    tenant. Check it in your client if you need to be sure which twin answered.
    Health endpoints omit it.


    **Development mode**

    - OTP `123456` is accepted for any OTP you requested, for test tenants.

    - M-Pesa prompts are real (STK to a handset you hold), collected through
    CloudPay's platform rail:
      up to KES 100 per prompt. Nothing is simulated by CloudPay. No payouts or settlements.
    - Payments are asynchronous: a new top-up, collection or disbursement is
    `initiated`, becomes
      `pending` once the provider accepts it (a Paystack checkout's `access_code` appears then), and
      ends `completed`, `failed` or `review`. Poll the GET endpoint.
    - Ready-made customers and merchants: the **Sandbox** endpoints below,
    authenticated with
      `Authorization: Bearer sk_test_...`. A live key gets 403 `live_mode_required`.

  contact:
    name: CloudPay Engineering
servers:
  - url: https://api.cloudpay.africa/cloudpay
    description: Production and Development (the key chooses)
  - url: http://localhost:8080
    description: Local dev (make dev / make up)
security:
  - bearer: []
tags:
  - name: Auth
    description: OTP, registration, login, PIN and sessions.
  - name: Wallet
    description: Profile, balance and statement.
  - name: Payments
    description: P2P transfers and M-Pesa top-ups.
  - name: Merchant pay
    description: >
      QR payments to merchants. A merchant QR encodes
      `{PUBLIC_BASE_URL}/pay/{code}`; scanning it

      opens a hosted page where the payer picks **M-Pesa** (STK prompt to any
      phone, no CloudPay

      account) or **CloudPay wallet** (sign in, confirm with PIN). Public
      endpoints resolve the

      tenant from the code; no X-Tenant-ID needed. `{code}` is a till's QR code
      (10 characters) or a

      pay-link (12 characters). A link that is disabled, expired or used up
      answers 403 `link_inactive`,

      `link_expired` or `link_used_up`.
  - name: Merchant API
    description: >
      Run a business: tills, members and roles, balances, statements, sweeps,
      API keys. Authenticate as a member

      (bearer session; the role decides) or with a merchant API key
      (`Authorization: Bearer sk_...` or `X-Api-Key`;

      its scopes decide). Permissions: read, collect, disburse, rails,
      credentials, links, transfer, settle,

      members, keys, settings.
  - name: Merchant webhooks
    description: >
      Get told when a collection or payout finishes instead of polling. Set one
      HTTPS endpoint; CloudPay POSTs a signed

      event for every final status (`collection.completed|failed|review`,
      `disbursement.completed|failed|review`) and

      retries for about 38 hours. Every attempt is kept (the trail). Also lists
      the CloudPay IPN addresses to paste

      into a provider dashboard when you use your own Paystack keys.
  - name: Merchant rails
    description: >
      Merchant & developer API for payment rails (M-Pesa, SasaPay, Paystack):
      choose rails, bring your own keys,

      collect, disburse, bulk. Authenticate with a merchant API key
      (`Authorization: Bearer sk_...`) or a member's

      session plus `X-Merchant-ID`. Permissions: `read`, `collect`, `disburse`,
      `rails`, `credentials`.
  - name: Sandbox
    description: >-
      Developer tooling for test tenants. Needs an `sk_test_` key; a live key
      gets 403 `live_mode_required`.
paths:
  /v1/auth/switch:
    post:
      tags:
        - Auth
      summary: Switch between live and test
      description: >
        Moves the session to the paired environment without logging in again.
        The same phone number's

        person account in the other environment is used and the current device
        is bound to it.

        Switching to test creates the test account (no PIN) if missing.
        Returning to production requires

        the session you switched from to still be active; otherwise 403
        device_verification_required and

        the client must do a normal live login. A test session from a fresh test
        login can never go live.

        The previous token keeps working in its own environment.
      operationId: switchEnvironment
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - mode
              additionalProperties: false
              properties:
                mode:
                  type: string
                  enum:
                    - live
                    - test
                  description: The environment to switch to.
      responses:
        '200':
          description: A session in the other environment.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Envelope'
                  - properties:
                      data:
                        type: object
                        properties:
                          access_token:
                            type: string
                          tenant_id:
                            type: string
                            format: uuid
                            description: The paired tenant the token belongs to.
                          mode:
                            type: string
                            enum:
                              - live
                              - test
        '400':
          $ref: '#/components/responses/Error'
        '401':
          $ref: '#/components/responses/Error'
        '403':
          $ref: '#/components/responses/Error'
components:
  schemas:
    Envelope:
      type: object
      required:
        - status
      properties:
        status:
          $ref: '#/components/schemas/Status'
    Status:
      type: object
      required:
        - ok
        - code
        - desc
      properties:
        ok:
          type: boolean
        code:
          type: integer
        desc:
          type: string
    ErrorEnvelope:
      type: object
      required:
        - status
        - errors
      properties:
        status:
          $ref: '#/components/schemas/Status'
        errors:
          $ref: '#/components/schemas/Error'
    Error:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: string
          description: Stable machine-readable code.
          enum:
            - invalid_body
            - invalid_msisdn
            - invalid_purpose
            - invalid_device_id
            - invalid_amount
            - invalid_idempotency_key
            - invalid_reference
            - invalid_id
            - invalid_status
            - weak_pin
            - self_transfer
            - unauthorized
            - invalid_otp
            - invalid_pin
            - invalid_credentials
            - device_verification_required
            - party_blocked
            - not_allowed_for_tier
            - risk_denied
            - tenant_not_found
            - party_not_found
            - account_not_found
            - entry_not_found
            - topup_not_found
            - party_exists
            - idempotency_key_reused
            - entry_final
            - insufficient_funds
            - account_frozen
            - account_closed
            - account_locked
            - amount_below_minimum
            - amount_above_limit
            - daily_limit_reached
            - pin_locked
            - otp_rate_limited
            - invalid_kyc_tier
            - tenant_exists
            - balance_not_supported
            - live_mode_required
            - invalid_api_key
            - api_key_not_found
            - tenant_not_found
            - unauthorized
            - bootstrap_key_required
            - staff_key_required
            - staff_exists
            - staff_not_found
            - invalid_name
            - unknown_secret
            - secret_not_found
            - empty_value
            - unknown_provider
            - invalid_credentials
            - credential_not_found
            - invalid_public_key
            - reason_required
            - backup_not_found
            - self_approval
            - not_maker
            - backup_not_pending
            - backup_expired
            - backup_not_downloadable
            - internal
        message:
          type: string
  responses:
    Error:
      description: Error envelope. Branch on `errors.code`.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
          examples:
            insufficient_funds:
              value:
                status:
                  ok: false
                  code: 422
                  desc: Unprocessable Entity
                errors:
                  code: insufficient_funds
                  message: insufficient funds
  securitySchemes:
    bearer:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >-
        `access_token` from register or login. Expires after JWT_TTL (default
        15m) or when the session ends.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.