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

# Allocate a payment address

> Allocates (or rotates) the temporary payment address for this invoice and returns:
- the address to pay,
- a quote (estimated token amount + exchange rate), and
- a short-lived websocket token for realtime payment updates (`/ws/payment`).

Choose `network` and `tokenId` from `GET /api/v1/payments/available-tokens`.




## OpenAPI

````yaml /api-reference/openapi.json post /api/v1/payments/payment-addresses
openapi: 3.0.0
info:
  title: Pepay API (SDK-scoped)
  version: 1.0.0
  description: API documentation for Pepay API
servers:
  - url: https://api-beta.pepay.io
    description: Beta server
  - url: http://localhost:3000
    description: Local development
security:
  - bearerAuth: []
tags:
  - name: Events
    description: Events API (history + debugging) for canonical notification envelopes.
  - name: Metrics
    description: Internal Prometheus metrics (restricted).
  - name: WebSockets
    description: WebSocket streams (upgrade endpoints) and message schemas.
  - name: Commerce - Devnet Simulator
    description: >
      Deterministic devnet-only endpoints for simulating Commerce V2 order state
      transitions.


      Use this when integrating as a merchant on devnet to test your backend/UI
      against realistic order lifecycle changes

      (payment confirmation, settlement gating, placement, tracking,
      cancellation, refunds) without placing real retailer

      orders or sending real on-chain refunds.


      How it works:

      - Requires a devnet `X-Commerce-Api-Key` (merchant-scoped).

      - Only operates on orders created in `networkEnvironment=devnet`.

      - Updates the order using the same reducer/persistence paths used in
      mainnet (provider snapshots are simulated).

      - After each simulation, Pepay emits the normal `commerce.order.updated`
      merchant webhook event.
  - name: Merchant Checkout
    description: >
      Merchant-scoped **three-step** checkout flow:

      1) `POST /api/commerce/merchant/checkout/estimate` — validate items
      against current eligible offers and return `validItems[]` +
      `invalidItems[]`.

      2) `POST /api/commerce/merchant/checkout/address` — attach and validate a
      shipping address for the estimate.

      3) `POST /api/commerce/merchant/checkout/invoice` — create the final
      invoice + commerce order.


      Cart behavior (when `useCart: true`):

      - The estimate call **reads** the saved cart but does **not** remove or
      modify cart items.

      - Items with no eligible offers are returned in `invalidItems[]`.

      - To remove items from the saved cart, call the Merchant Cart APIs (`PUT
      /api/commerce/merchant/carts/items/:itemId` with `quantity: 0`, or `DELETE
      /api/commerce/merchant/carts/items/:itemId`).

      - To exclude items for *this checkout attempt* without mutating the cart,
      use `itemOverrides[]` with `quantity: 0`.
  - name: Payment Sessions
    description: >
      Payor-facing APIs used by the hosted payment page and other embedded
      checkout clients.


      Canonical base path:

      - All documented endpoints are under `/api/v1/payments/*`.


      Authentication:

      - These endpoints do **not** accept merchant API keys or bearer JWTs.

      - Send `x-session-token` and `x-signature` headers on every request (both
      are returned when creating an invoice).


      Typical flow:

      1) Create an invoice (`POST /api/v1/invoices`) → receive `payment_url`,
      `session_token`, `signature`.

      2) Render/open the `payment_url` for the payor.

      3) Fetch invoice context (`GET /api/v1/payments/session-details`).

      4) List supported tokens (`GET /api/v1/payments/available-tokens`).

      5) Allocate a payment address (`POST /api/v1/payments/payment-addresses`)
      → use `ws_connection` for `/ws/payment`.

      6) Track progress via polling (`GET /api/v1/payments/payment-status`)
      and/or websocket (`/ws/payment`).


      Security notes:

      - Treat `session_token` and `signature` as sensitive values (anyone with
      them can read the invoice/payment status).

      - Do not store them in long-lived browser storage; prefer in-memory usage
      on the payment page.
  - name: Quotes
    description: Token settlement quotes and rate calculations
  - name: Webhooks
    description: >
      Webhook endpoint management and delivery history for canonical
      notifications.


      Delivery model:

      - At-least-once delivery; receivers must dedupe by `event.id` (also sent
      as `X-Pepay-Event-ID`).

      - Payloads are canonical `PepayEvent` objects and match websocket
      `event_v1` frames for the same event type.


      Security:

      - Endpoints must be HTTPS.

      - Deliveries are signed using `HMAC_SHA256("${timestamp_ms}.${raw_body}")`
      and sent in `X-Pepay-Signature`.
paths:
  /api/v1/payments/payment-addresses:
    post:
      tags:
        - Payment Sessions
      summary: Allocate a payment address
      description: >
        Allocates (or rotates) the temporary payment address for this invoice
        and returns:

        - the address to pay,

        - a quote (estimated token amount + exchange rate), and

        - a short-lived websocket token for realtime payment updates
        (`/ws/payment`).


        Choose `network` and `tokenId` from `GET
        /api/v1/payments/available-tokens`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Postapiv1paymentspayment-addressesRequest'
            example:
              network: ethereum
              tokenId: 1
      responses:
        '200':
          description: Address allocated
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/Postapiv1paymentspayment-addressesResponse200
              example:
                temp_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'
                network: ethereum
                supported_token_id: 1
                estimated_token_amount: '100.50'
                exchange_rate: '0.9950'
                usd_amount: 100
                quote_last_updated_at: 1765540800
                quote_valid_until: 1765541100
                quote_expires_in_seconds: 300
                ws_connection:
                  token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                  endpoint: /ws/payment
                  format: event_v1
                  ws_url: /ws/payment?format=event_v1
        '400':
          description: Invalid request or unsupported token/network
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                invalid_request:
                  value:
                    error: Invalid or missing tokenId
                    code: INVALID_REQUEST_FORMAT
                wrong_network:
                  value:
                    error: Must complete payment using the same network
                    code: INVALID_PAYMENT_NETWORK
                wrong_token:
                  value:
                    error: Must complete payment using the same token
                    code: INVALID_PAYMENT_TOKEN
        '401':
          description: Missing/invalid session authentication
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: Invoice not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '410':
          description: Invoice has expired
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: Too many requests
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RateLimitError'
        '500':
          description: Failed to generate payment address
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - PaymentSessionToken: []
          PaymentSessionSignature: []
components:
  schemas:
    Postapiv1paymentspayment-addressesRequest:
      type: object
      required:
        - network
        - tokenId
      properties:
        network:
          type: string
          description: >-
            Network identifier from `/api/v1/payments/available-tokens`
            (lowercase).
        tokenId:
          type: integer
          description: Token identifier from `/api/v1/payments/available-tokens`.
    Postapiv1paymentspayment-addressesResponse200:
      type: object
      properties:
        success:
          type: boolean
          description: Always true; quote availability is communicated via `quote_status`.
        quote_status:
          type: string
          enum:
            - available
            - unavailable
            - expired
          description: Quote window status for this token selection.
        status_code:
          type: string
          enum:
            - ok
            - quote_unavailable
            - quote_expired
            - settlement_unavailable
          description: Machine-readable status.
        message:
          type: string
          nullable: true
          description: Human-readable status message.
        temp_address:
          type: string
          description: Generated payment address
        network:
          type: string
          description: Network name (lowercase)
        supported_token_id:
          type: integer
          description: Token id that was selected.
        estimated_token_amount:
          type: string
          description: Amount to pay in token (includes buffer)
        exchange_rate:
          type: string
          description: USD to token exchange rate
        usd_amount:
          type: number
          description: Invoice amount in USD
        quote_last_updated_at:
          type: integer
          nullable: true
          description: Server timestamp the current quote was persisted (epoch seconds).
        quote_valid_until:
          type: integer
          nullable: true
          description: Server timestamp when the quote expires (epoch seconds).
        quote_expires_in_seconds:
          type: integer
          nullable: true
          description: Seconds remaining until `quote_valid_until` (computed at send time).
        retryable:
          type: boolean
          nullable: true
          description: True when the backend recommends retrying to mint/refresh a quote.
        retry_after_seconds:
          type: integer
          nullable: true
          description: Suggested backoff in seconds when retryable.
        ws_connection:
          type: object
          properties:
            token:
              type: string
              description: >-
                Short-lived websocket token for `/ws/payment` (treat as
                sensitive).
            endpoint:
              type: string
              description: WebSocket endpoint path (event_v1 default).
            format:
              type: string
              enum:
                - event_v1
              description: WebSocket payload format (event_v1 only).
            ws_url:
              type: string
              description: WebSocket endpoint with format query (relative path).
    Error:
      type: object
      description: Standard error response (not used for rate limiting).
      properties:
        error:
          type: string
          description: Human-readable error message.
        code:
          type: string
          nullable: true
          description: Optional machine-readable error code.
        details:
          nullable: true
          description: >-
            Optional structured details (present in some development/debug
            scenarios).
          oneOf:
            - type: string
            - type: object
              additionalProperties: true
            - type: array
              items:
                type: object
                additionalProperties: true
      example:
        error: Failed to fetch available tokens
        code: DATABASE_ERROR
    RateLimitError:
      type: object
      description: Rate limit error response (HTTP 429).
      properties:
        error:
          type: string
        error_code:
          type: string
        source:
          type: string
      example:
        error: Too many requests. Please try again in a minute.
        error_code: PAYMENT_SESSION_RATE_LIMIT
        source: payment_session
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT token for wallet authentication
    PaymentSessionToken:
      type: apiKey
      in: header
      name: x-session-token
      description: >-
        Payment session token (opaque). Returned when creating an invoice; send
        on every request.
    PaymentSessionSignature:
      type: apiKey
      in: header
      name: x-signature
      description: >-
        Payment session signature in the format `signature_hash.timestamp_ms`
        (returned with the invoice/session).

````