> ## 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.

# Search Commerce

> Search products/retail inventory via the Commerce API.

## Overview

Use this endpoint to search Commerce inventory and build a product browsing experience.

## Authentication

Commerce search requires a commerce-scoped API key (see [Commerce APIs](/api-spec/commerce/api-keys)).

## Request

### SDK

```ts theme={null}
const results = await pepay.commerce.search({ q: 'wireless headphones', limit: 10 });
```

### cURL

```bash theme={null}
curl "https://api-beta.pepay.io/api/commerce/search?q=wireless%20headphones&limit=10" \
  -H "x-commerce-api-key: ck_..."
```

## Response

```json theme={null}
{
  "success": true,
  "data": {
    "products": [
      {
        "productId": "B000NPYY04",
        "title": "Wireless Headphones",
        "price": 129.99,
        "image": "https://images.example.com/product.png"
      }
    ]
  }
}
```

## Errors

* `400` invalid search parameters
* `401` missing/invalid commerce auth

## Examples

* Build “search → cart → checkout” flows using the adjacent Commerce endpoints in the sidebar.
  Next: [Create a checkout invoice](/api-spec/endpoints/commerce-checkout-invoice)


## OpenAPI

````yaml GET /api/commerce/search
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: Subscriptions
    description: Recurring subscription plans and charges (X402 Flex).
  - name: Subscriptions - Admin
    description: Admin operations for subscription infrastructure.
  - 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/commerce/search:
    get:
      tags:
        - Commerce - Products
      summary: Search for products
      description: >
        Search for products across supported retailers using our commerce
        platform.

        Results are cached for 5 minutes to improve performance.


        **Features:**

        - Full-text product search across retailers

        - Pagination support (up to 100 pages)

        - Price range filtering

        - Real-time availability and pricing

        - Delivery eligibility filtering (<=10 days)

        - Customer ratings and reviews


        **Rate Limiting:**

        - 10 searches per minute per API key

        - Results cached for 5 minutes to reduce API calls


        **Response includes:**

        - Product title, description, and images

        - Current pricing and discounts

        - Availability status

        - Customer ratings and review count

        - Delivery window information

        - Shipping information (when available)
      operationId: searchProducts
      parameters:
        - name: q
          in: query
          required: true
          schema:
            type: string
            minLength: 1
            maxLength: 200
          description: Search query (1-200 characters)
          example: wireless headphones
        - name: page
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 1
          description: Page number for pagination (1-100)
        - name: retailer
          in: query
          required: false
          schema:
            type: string
            enum:
              - amazon
              - walmart
            default: amazon
          description: Retailer to search (currently only Amazon supported)
        - name: minPrice
          in: query
          required: false
          schema:
            type: number
            format: float
            minimum: 0
          description: Minimum price filter in USD
          example: 25
        - name: maxPrice
          in: query
          required: false
          schema:
            type: number
            format: float
            minimum: 0
          description: Maximum price filter in USD
          example: 150
      responses:
        '200':
          description: Search results with pagination info
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetapicommercesearchResponse200'
        '400':
          description: Bad request - Invalid parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetapicommercesearchResponse400'
        '401':
          description: Unauthorized - Missing or invalid commerce API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetapicommercesearchResponse401'
        '403':
          description: Forbidden - API key suspended or expired
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetapicommercesearchResponse403'
        '429':
          description: Too Many Requests - Rate limit exceeded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetapicommercesearchResponse429'
        '503':
          description: Service unavailable - Commerce disabled or API error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetapicommercesearchResponse503'
      security:
        - commerceApiKey: []
        - merchantApiKey: []
components:
  schemas:
    GetapicommercesearchResponse200:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            products:
              type: array
              description: Array of product search results
              items:
                type: object
                properties:
                  productId:
                    type: string
                    description: Product identifier (e.g., ASIN for Amazon)
                    example: B000NPYY04
                  title:
                    type: string
                    description: Product title
                    example: >-
                      Nature's Bounty Fish Oil, 1200 mg Omega-3, 200 Rapid
                      Release Softgels
                  price:
                    type: number
                    format: decimal
                    description: Current price in USD (converted from cents)
                    example: 12.48
                  image:
                    type: string
                    format: uri
                    description: Primary product image URL
                    example: >-
                      https://images-na.ssl-images-amazon.com/images/I/51KGjV22PWL._AC_US218_.jpg
                  rating:
                    type: number
                    format: decimal
                    nullable: true
                    description: Average customer rating (0-5) extracted from stars string
                    example: 4.5
                  reviewCount:
                    type: integer
                    nullable: true
                    description: Number of customer reviews
                    example: 395
                  fresh:
                    type: boolean
                    description: Whether the data is fresh/recently updated
                    example: false
                  retailer:
                    type: string
                    description: Retailer name
                    example: amazon
                  url:
                    type: string
                    format: uri
                    description: Product URL on retailer site (constructed if not provided)
                    example: https://www.amazon.com/dp/B000NPYY04
            pagination:
              type: object
              properties:
                page:
                  type: integer
                  description: Current page number
                  example: 1
                totalPages:
                  type: integer
                  description: Total number of pages
                  example: 8
                totalResults:
                  type: integer
                  nullable: true
                  description: Total number of results (if available)
                  example: 150
                hasNext:
                  type: boolean
                  description: Whether there is a next page
                  example: true
            query:
              type: string
              description: Search query used
              example: wireless headphones
            retailer:
              type: string
              description: Retailer searched
              example: amazon
        meta:
          type: object
          properties:
            timestamp:
              type: integer
              example: 1738240496
            cacheStats:
              type: object
              description: Cache performance statistics
    GetapicommercesearchResponse400:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: object
          properties:
            code:
              type: string
              enum:
                - VALIDATION_ERROR
              example: VALIDATION_ERROR
            message:
              type: string
              example: Invalid request parameters
            details:
              type: array
              items:
                type: object
                properties:
                  field:
                    type: string
                    example: q
                  message:
                    type: string
                    example: Search query must be between 1 and 200 characters
    GetapicommercesearchResponse401:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: object
          properties:
            code:
              type: string
              enum:
                - COMMERCE_API_KEY_MISSING
                - INVALID_COMMERCE_API_KEY
              example: COMMERCE_API_KEY_MISSING
            message:
              type: string
              example: Commerce API key required
    GetapicommercesearchResponse403:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: object
          properties:
            code:
              type: string
              enum:
                - COMMERCE_API_KEY_SUSPENDED
                - COMMERCE_API_KEY_EXPIRED
              example: COMMERCE_API_KEY_SUSPENDED
            message:
              type: string
              example: Commerce API key suspended
    GetapicommercesearchResponse429:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: object
          properties:
            code:
              type: string
              enum:
                - RATE_LIMIT_EXCEEDED
              example: RATE_LIMIT_EXCEEDED
            message:
              type: string
              example: Too many search requests. Please wait before trying again.
            retryAfter:
              type: integer
              description: Seconds to wait before retrying
              example: 60
    GetapicommercesearchResponse503:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: object
          properties:
            code:
              type: string
              enum:
                - COMMERCE_DISABLED
                - COMMERCE_API_ERROR
            message:
              type: string
              example: Commerce features are currently disabled
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT token for wallet authentication
    commerceApiKey:
      type: apiKey
      in: header
      name: x-commerce-api-key
      description: >-
        Legacy alias for commerce-scoped API keys. Prefer `x-api-key` with
        scope=commerce.
    merchantApiKey:
      type: apiKey
      in: header
      name: x-api-key
      description: API key for server-to-server operations (scope=merchant or commerce)

````