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

# Data Types Reference

> Shared data types, payment statuses, and error codes for Terminal Gateway APIs

## Overview

This reference documents all shared data types used across both HTTP and WebSocket Terminal Gateway APIs.

***

## PaymentRequest

The payment request object used to initiate payments.

<ParamField body="transactionId" type="string">
  Unique transaction identifier in UUIDv7 format. Use this to track and reconcile payments. Auto-generated if not provided.

  **Example:** `"01945f3d-a8c9-7000-8d45-6f8234ab9012"`
</ParamField>

<ParamField body="amount" type="string | number" required>
  Payment amount. Can be a string (recommended for precision) or number.

  **Example:** `"99.99"` or `99.99`
</ParamField>

<ParamField body="currency" type="string" required>
  ISO 4217 currency code.

  **Example:** `"USD"`, `"EUR"`, `"PHP"`
</ParamField>

<ParamField body="paymentMethod" type="string" required>
  Payment method type.

  **Values:** `CARD`, `CASH`, `MOBILE`, `OTHER`
</ParamField>

<ParamField body="products" type="Product[]">
  Array of products in the transaction.
</ParamField>

<ParamField body="customerInfo" type="CustomerInfo">
  Customer information for the transaction.
</ParamField>

<ParamField body="metadata" type="object">
  Custom key-value pairs for your use. This data is stored with the transaction and returned in responses.

  **Example:**

  ```json theme={null}
  {
    "orderId": "ORD-12345",
    "tableNumber": "T-5",
    "serverName": "John"
  }
  ```
</ParamField>

### Example

```json theme={null}
{
  "transactionId": "01945f3d-a8c9-7000-8d45-6f8234ab9012",
  "amount": "99.99",
  "currency": "USD",
  "paymentMethod": "CARD",
  "products": [
    {
      "id": "PROD-001",
      "name": "Widget",
      "price": "99.99",
      "quantity": 1
    }
  ],
  "customerInfo": {
    "customerId": "CUST-123",
    "email": "customer@example.com"
  },
  "metadata": {
    "orderId": "ORD-12345"
  }
}
```

***

## PaymentResponse

The payment response object returned when a payment completes.

<ParamField body="transactionId" type="string" required>
  Transaction identifier matching your original request.
</ParamField>

<ParamField body="status" type="string" required>
  Payment status.

  **Values:** `SUCCESS`, `FAILED`, `PENDING`, `CANCELLED`
</ParamField>

<ParamField body="amount" type="string | number" required>
  Payment amount.
</ParamField>

<ParamField body="currency" type="string" required>
  Currency code.
</ParamField>

<ParamField body="paymentMethod" type="string" required>
  Payment method used.
</ParamField>

<ParamField body="authorizationCode" type="string">
  Authorization code from payment processor. Present on successful payments.

  **Example:** `"AUTH123456"`
</ParamField>

<ParamField body="errorCode" type="string">
  Error code if status is `FAILED`.

  **Example:** `"INSUFFICIENT_FUNDS"`
</ParamField>

<ParamField body="errorMessage" type="string">
  Human-readable error message if status is `FAILED`.

  **Example:** `"Card declined due to insufficient funds"`
</ParamField>

<ParamField body="receiptData" type="string">
  Opaque receipt data from terminal. Format depends on the terminal's payment processor.
</ParamField>

<ParamField body="timestamp" type="string" required>
  ISO 8601 timestamp of when the payment was processed.
</ParamField>

<ParamField body="metadata" type="object">
  Your custom metadata returned from the original request.
</ParamField>

### Successful Payment Example

```json theme={null}
{
  "transactionId": "01945f3d-a8c9-7000-8d45-6f8234ab9012",
  "status": "SUCCESS",
  "amount": "99.99",
  "currency": "USD",
  "paymentMethod": "CARD",
  "authorizationCode": "AUTH123456",
  "receiptData": "...",
  "timestamp": "2024-01-15T10:37:30.000Z",
  "metadata": {
    "orderId": "ORD-12345"
  }
}
```

### Failed Payment Example

```json theme={null}
{
  "transactionId": "01945f3d-b2e1-7000-9c67-8a4321cd5678",
  "status": "FAILED",
  "amount": "99.99",
  "currency": "USD",
  "paymentMethod": "CARD",
  "errorCode": "INSUFFICIENT_FUNDS",
  "errorMessage": "Card declined due to insufficient funds",
  "timestamp": "2024-01-15T10:38:00.000Z",
  "metadata": {
    "orderId": "ORD-12346"
  }
}
```

***

## Product

Product item in a payment request.

<ParamField body="id" type="string" required>
  Product identifier.

  **Example:** `"PROD-001"`
</ParamField>

<ParamField body="name" type="string" required>
  Product name.

  **Example:** `"Widget"`
</ParamField>

<ParamField body="price" type="string | number" required>
  Unit price.

  **Example:** `"29.99"`
</ParamField>

<ParamField body="quantity" type="number" required>
  Quantity purchased.

  **Example:** `2`
</ParamField>

<ParamField body="category" type="string">
  Product category.

  **Example:** `"Electronics"`
</ParamField>

<ParamField body="sku" type="string">
  Stock keeping unit.

  **Example:** `"WDG-001-BLK"`
</ParamField>

<ParamField body="brand" type="string">
  Brand name.

  **Example:** `"Acme Corp"`
</ParamField>

<ParamField body="tax" type="number">
  Tax amount for this item.

  **Example:** `2.99`
</ParamField>

<ParamField body="discount" type="number">
  Discount amount for this item.

  **Example:** `5.00`
</ParamField>

### Example

```json theme={null}
{
  "id": "PROD-001",
  "name": "Widget",
  "price": "29.99",
  "quantity": 2,
  "category": "Electronics",
  "sku": "WDG-001-BLK",
  "brand": "Acme Corp",
  "tax": 5.99,
  "discount": 0
}
```

***

## CustomerInfo

Customer information for a payment.

<ParamField body="customerId" type="string">
  Customer identifier in your system.

  **Example:** `"CUST-123"`
</ParamField>

<ParamField body="email" type="string">
  Customer email address.

  **Example:** `"customer@example.com"`
</ParamField>

<ParamField body="phone" type="string">
  Customer phone number.

  **Example:** `"+1-555-123-4567"`
</ParamField>

### Example

```json theme={null}
{
  "customerId": "CUST-123",
  "email": "customer@example.com",
  "phone": "+1-555-123-4567"
}
```

***

## TerminalInfo

Terminal information returned when listing or querying terminals.

<ParamField body="connectionId" type="string" required>
  Unique connection identifier. Changes when terminal reconnects.
</ParamField>

<ParamField body="terminalId" type="string" required>
  Primary identifier. Uses `deviceId` if available, otherwise `connectionId`.
</ParamField>

<ParamField body="deviceId" type="string">
  Stable device identifier. Configured via `X-Device-Id` header on terminal connection. Persists across reconnections.
</ParamField>

<ParamField body="connectedAt" type="string" required>
  ISO 8601 timestamp of when the terminal connected.
</ParamField>

<ParamField body="lastActivity" type="string" required>
  ISO 8601 timestamp of the terminal's last activity.
</ParamField>

<ParamField body="status" type="string" required>
  Terminal status.

  **Values:** `online`, `offline`, `reconnecting`
</ParamField>

<ParamField body="metadata" type="object">
  Custom terminal metadata.
</ParamField>

### Example

```json theme={null}
{
  "connectionId": "abc123xyz",
  "terminalId": "TERM-001",
  "deviceId": "TERM-001",
  "connectedAt": "2024-01-15T10:30:00.000Z",
  "lastActivity": "2024-01-15T10:35:00.000Z",
  "status": "online",
  "metadata": {}
}
```

***

## TransactionRecord

Transaction record returned when querying transaction status (HTTP API).

<ParamField body="transactionId" type="string" required>
  Unique transaction identifier.
</ParamField>

<ParamField body="status" type="string" required>
  Transaction status.

  **Values:** `PENDING`, `COMPLETED`, `FAILED`, `CANCELLED`, `AWAITING_RECONNECT`, `VOIDED`
</ParamField>

<ParamField body="request" type="PaymentRequest" required>
  Original payment request.
</ParamField>

<ParamField body="response" type="PaymentResponse">
  Payment response (if completed).
</ParamField>

<ParamField body="createdAt" type="string" required>
  ISO 8601 timestamp of creation.
</ParamField>

<ParamField body="updatedAt" type="string" required>
  ISO 8601 timestamp of last update.
</ParamField>

<ParamField body="completedAt" type="string">
  ISO 8601 timestamp of completion (if applicable).
</ParamField>

<ParamField body="terminalDeviceId" type="string">
  Stable terminal device identifier (if available).
</ParamField>

<ParamField body="voidedAt" type="string">
  ISO 8601 timestamp when payment was voided (if applicable).
</ParamField>

<ParamField body="voidReason" type="string">
  Reason for voiding the payment (if voided).
</ParamField>

<ParamField body="timestamp" type="string" required>
  ISO 8601 timestamp of this response.
</ParamField>

### Example

```json theme={null}
{
  "transactionId": "01945f3d-a8c9-7000-8d45-6f8234ab9012",
  "status": "COMPLETED",
  "request": {
    "transactionId": "01945f3d-a8c9-7000-8d45-6f8234ab9012",
    "amount": "99.99",
    "currency": "USD",
    "paymentMethod": "CARD"
  },
  "response": {
    "transactionId": "01945f3d-a8c9-7000-8d45-6f8234ab9012",
    "status": "SUCCESS",
    "amount": "99.99",
    "currency": "USD",
    "paymentMethod": "CARD",
    "authorizationCode": "AUTH123456",
    "timestamp": "2024-01-15T10:37:30.000Z"
  },
  "createdAt": "2024-01-15T10:37:00.000Z",
  "updatedAt": "2024-01-15T10:37:30.000Z",
  "completedAt": "2024-01-15T10:37:30.000Z",
  "timestamp": "2024-01-15T10:40:00.000Z"
}
```

***

## VoidResult

The result returned when a void operation is performed.

<ParamField body="success" type="boolean" required>
  Whether the void operation succeeded.
</ParamField>

<ParamField body="transactionId" type="string" required>
  The transaction that was voided.
</ParamField>

<ParamField body="reason" type="string" required>
  Reason for the void.

  **Example:** `"Terminal reconnected after grace period"`
</ParamField>

<ParamField body="voidedAt" type="string">
  ISO 8601 timestamp of when the payment was voided.

  **Example:** `"2024-01-15T10:38:30.000Z"`
</ParamField>

<ParamField body="error" type="string">
  Error message if the void operation failed.

  **Example:** `"Transaction already voided"`
</ParamField>

### Example

```json theme={null}
{
  "success": true,
  "transactionId": "01945f3d-a8c9-7000-8d45-6f8234ab9012",
  "reason": "Terminal reconnected after grace period",
  "voidedAt": "2024-01-15T10:38:30.000Z"
}
```

***

## Metadata Field

The `metadata` field allows you to attach custom data to payments. This data is stored with the transaction and returned in responses.

### Use Cases

| Use Case              | Example                                        |
| --------------------- | ---------------------------------------------- |
| **Order tracking**    | Link payments to your order management system  |
| **Staff attribution** | Track which employee processed the transaction |
| **Custom reporting**  | Add fields needed for your business reporting  |
| **Integration IDs**   | Store references to external systems           |

```json theme={null}
{
  "metadata": {
    "orderId": "ORD-12345",
    "tableNumber": "T-5",
    "serverName": "John",
    "loyaltyPoints": 150
  }
}
```

<Note>
  The `metadata` field accepts any valid JSON object. Keys and values should be strings, numbers, or booleans for best compatibility.
</Note>

***

## Payment Status Definitions

### Transaction Status

| Status               | Description                                                                                |
| -------------------- | ------------------------------------------------------------------------------------------ |
| `PENDING`            | Transaction created, awaiting terminal response                                            |
| `COMPLETED`          | Transaction completed successfully                                                         |
| `FAILED`             | Transaction failed (see error details)                                                     |
| `CANCELLED`          | Transaction was cancelled                                                                  |
| `AWAITING_RECONNECT` | Terminal disconnected mid-payment, waiting for reconnection (60-second grace period)       |
| `VOIDED`             | Payment was voided (e.g., terminal reconnected after grace period with successful payment) |

### Payment Response Status

| Status      | Description                                                                                            |
| ----------- | ------------------------------------------------------------------------------------------------------ |
| `SUCCESS`   | Payment was successfully processed and approved. The `authorizationCode` will be present.              |
| `FAILED`    | Payment was declined or encountered an error. Check `errorCode` and `errorMessage` for details.        |
| `PENDING`   | Payment is still being processed. This may occur with network issues or terminal communication delays. |
| `CANCELLED` | Payment was cancelled by the user or terminal operator before completion.                              |

***

## HTTP Error Reference

### Error Response Format

All HTTP API errors follow this format:

```json theme={null}
{
  "error": {
    "code": "TERMINAL_NOT_FOUND",
    "message": "Terminal not found or offline. Please check terminal status and try again.",
    "details": {}
  },
  "timestamp": "2024-01-15T10:40:00.000Z",
  "requestId": "req-abc123"
}
```

### Error Codes

| Code                        | HTTP Status | Description                                          | Recommended Action                       |
| --------------------------- | ----------- | ---------------------------------------------------- | ---------------------------------------- |
| `INVALID_REQUEST`           | 400         | Request body is malformed or missing required fields | Check request format and required fields |
| `INVALID_AMOUNT`            | 400         | Amount is invalid or doesn't match products total    | Verify amount calculation                |
| `UNAUTHORIZED`              | 401         | Missing or invalid API key                           | Check API key configuration              |
| `INVALID_SIGNATURE`         | 401         | HMAC signature verification failed                   | Verify signature computation             |
| `TIMESTAMP_EXPIRED`         | 401         | Request timestamp outside 5-minute window            | Ensure system clock is synchronized      |
| `GROUP_MISMATCH`            | 403         | Resource belongs to a different group                | Verify you're using the correct API key  |
| `TERMINAL_NOT_FOUND`        | 404         | Specified terminal does not exist                    | Refresh terminal list                    |
| `TRANSACTION_NOT_FOUND`     | 404         | Specified transaction does not exist                 | Verify transaction ID                    |
| `PAYMENT_IN_PROGRESS`       | 409         | Another payment is being processed                   | Wait for current payment to complete     |
| `RATE_LIMITED`              | 429         | Too many requests                                    | Reduce request frequency                 |
| `TERMINAL_CONNECTION_ERROR` | 502         | Failed to communicate with terminal                  | Terminal may have disconnected; retry    |
| `TERMINAL_OFFLINE`          | 503         | Terminal is offline or unresponsive                  | Check terminal connectivity              |
| `TIMEOUT`                   | 504         | Terminal did not respond within 90 seconds           | Check transaction status endpoint        |
| `INTERNAL_ERROR`            | 500         | Unexpected server error                              | Contact support if persistent            |

***

## WebSocket Error Reference

### Error Message Format

WebSocket errors follow this format:

```json theme={null}
{
  "error": "Bad Request",
  "message": "terminalId is required"
}
```

### Common Errors

| Error                 | Message                                              | Cause                     |
| --------------------- | ---------------------------------------------------- | ------------------------- |
| Bad Request           | Invalid JSON in message body                         | Malformed JSON in request |
| Bad Request           | terminalId is required                               | Missing required field    |
| Bad Request           | paymentRequest is required                           | Missing payment data      |
| Not Found             | Connection not found                                 | Invalid connection ID     |
| Not Found             | Terminal connection not found                        | Terminal not connected    |
| Forbidden             | Only desktop devices can request terminal list       | Wrong device type         |
| Forbidden             | Cannot send message to connection in different group | Group mismatch            |
| Internal Server Error | Failed to process message                            | Server-side error         |

### forceDisconnect Reasons

| Reason                     | Description                                        |
| -------------------------- | -------------------------------------------------- |
| `api_key_used_elsewhere`   | Another device connected with the same API key     |
| `stale_connection_timeout` | Connection was inactive for too long               |
| `admin_action`             | Connection terminated by administrator             |
| `server_restarting`        | Server is restarting for maintenance or deployment |
| `other`                    | Other system-initiated disconnect                  |

***

## Currency Codes

The API uses ISO 4217 three-letter currency codes:

| Code  | Currency          |
| ----- | ----------------- |
| `USD` | US Dollar         |
| `EUR` | Euro              |
| `GBP` | British Pound     |
| `PHP` | Philippine Peso   |
| `JPY` | Japanese Yen      |
| `CAD` | Canadian Dollar   |
| `AUD` | Australian Dollar |

<Note>
  Contact [support@moduluslabs.io](mailto:support@moduluslabs.io) for the complete list of supported currencies for your integration.
</Note>

***

## System Constants

Important timeouts and limits to consider when integrating with Terminal Gateway.

| Constant                          | Value      | Description                                                              |
| --------------------------------- | ---------- | ------------------------------------------------------------------------ |
| Reconnect grace period            | 60 seconds | Time allowed for a terminal to reconnect during a mid-payment disconnect |
| Long poll timeout                 | 90 seconds | Maximum wait time for HTTP API payment requests                          |
| Transaction retention (WebSocket) | 7 days     | How long WebSocket transactions are retained                             |
| Transaction retention (HTTP)      | 30 days    | How long HTTP transactions are retained                                  |

<Note>
  If a terminal disconnects mid-payment, the system waits up to 60 seconds for reconnection. If the terminal reconnects with a successful payment after this grace period, the payment is automatically voided.
</Note>

***

## WebhookEndpoint

Configuration object for a webhook endpoint.

<ParamField body="endpointId" type="string" required>
  Unique identifier for the webhook endpoint.

  **Example:** `"wh_01HQ3K4M5N6P7R8S9T0UVWXYZ"`
</ParamField>

<ParamField body="url" type="string" required>
  The HTTPS URL where webhook payloads are delivered.

  **Example:** `"https://api.yourcompany.com/webhooks/payments"`
</ParamField>

<ParamField body="events" type="string[]" required>
  Event types this endpoint is subscribed to.

  **Values:** `payment.completed`, `payment.failed`, `payment.cancelled`, `payment.timeout`
</ParamField>

<ParamField body="description" type="string">
  Human-readable description for this endpoint.

  **Example:** `"Production payment notifications"`
</ParamField>

<ParamField body="secret" type="string">
  Webhook signing secret for verifying payloads. Only returned on endpoint creation.

  **Example:** `"whsec_abc123xyz789..."`
</ParamField>

<ParamField body="status" type="string" required>
  Endpoint status.

  **Values:** `active`, `disabled`
</ParamField>

<ParamField body="metadata" type="object">
  Custom key-value pairs associated with this endpoint.
</ParamField>

<ParamField body="createdAt" type="string" required>
  ISO 8601 timestamp of when the endpoint was created.
</ParamField>

<ParamField body="updatedAt" type="string" required>
  ISO 8601 timestamp of the last update.
</ParamField>

### Example

```json theme={null}
{
  "endpointId": "wh_01HQ3K4M5N6P7R8S9T0UVWXYZ",
  "url": "https://api.yourcompany.com/webhooks/payments",
  "events": ["payment.completed", "payment.failed", "payment.cancelled", "payment.timeout"],
  "description": "Production payment notifications",
  "status": "active",
  "metadata": {
    "environment": "production"
  },
  "createdAt": "2024-01-15T10:30:00.000Z",
  "updatedAt": "2024-01-15T10:30:00.000Z"
}
```

***

## WebhookPayload

Payload delivered to your webhook endpoint when a payment event occurs.

<ParamField body="eventType" type="string" required>
  The type of event that triggered this webhook.

  **Values:** `payment.completed`, `payment.failed`, `payment.cancelled`, `payment.timeout`
</ParamField>

<ParamField body="eventId" type="string" required>
  Unique identifier for this event. Use for idempotency checks.

  **Example:** `"evt_01HQ3K4M5N6P7R8S9T0UVWXYZ"`
</ParamField>

<ParamField body="timestamp" type="string" required>
  ISO 8601 timestamp of when the event occurred.
</ParamField>

<ParamField body="data" type="object" required>
  Event-specific payload data containing the payment result.

  <Expandable title="Data fields">
    <ParamField body="transactionId" type="string" required>
      Transaction identifier from the original payment request.
    </ParamField>

    <ParamField body="status" type="string" required>
      Payment status: `SUCCESS`, `FAILED`, `CANCELLED`, or `TIMEOUT`.
    </ParamField>

    <ParamField body="amount" type="string" required>
      Payment amount.
    </ParamField>

    <ParamField body="currency" type="string" required>
      ISO 4217 currency code.
    </ParamField>

    <ParamField body="paymentMethod" type="string" required>
      Payment method used.
    </ParamField>

    <ParamField body="authorizationCode" type="string">
      Authorization code from payment processor (success only).
    </ParamField>

    <ParamField body="errorCode" type="string">
      Error code if payment failed.
    </ParamField>

    <ParamField body="errorMessage" type="string">
      Human-readable error message if payment failed.
    </ParamField>

    <ParamField body="receiptData" type="string">
      Opaque receipt data from terminal.
    </ParamField>

    <ParamField body="terminalId" type="string" required>
      Terminal that processed the payment.
    </ParamField>

    <ParamField body="metadata" type="object">
      Custom metadata from the original payment request.
    </ParamField>
  </Expandable>
</ParamField>

### Example

```json theme={null}
{
  "eventType": "payment.completed",
  "eventId": "evt_01HQ3K4M5N6P7R8S9T0UVWXYZ",
  "timestamp": "2024-01-15T10:37:30.000Z",
  "data": {
    "transactionId": "TXN-20240115-001",
    "status": "SUCCESS",
    "amount": "99.99",
    "currency": "USD",
    "paymentMethod": "CARD",
    "authorizationCode": "AUTH123456",
    "receiptData": "...",
    "terminalId": "TERM-001",
    "metadata": {
      "orderId": "ORD-12345"
    }
  }
}
```

***

## WebhookEventType

Event types that can trigger webhook notifications.

| Event Type          | Description               | Trigger                             |
| ------------------- | ------------------------- | ----------------------------------- |
| `payment.completed` | Payment succeeded         | Terminal returns `SUCCESS` status   |
| `payment.failed`    | Payment declined or error | Terminal returns `FAILED` status    |
| `payment.cancelled` | User cancelled payment    | Terminal returns `CANCELLED` status |
| `payment.timeout`   | Terminal didn't respond   | 90-second timeout reached           |

***

## Payment Methods

Supported payment method values:

| Method   | Description                                  |
| -------- | -------------------------------------------- |
| `CARD`   | Credit or debit card payment                 |
| `CASH`   | Cash payment                                 |
| `MOBILE` | Mobile payment (e.g., Apple Pay, Google Pay) |
| `OTHER`  | Other payment method                         |

***

## Timestamps

All timestamps in the API use ISO 8601 format with UTC timezone:

```text theme={null}
2024-01-15T10:30:00.000Z
```

### Parsing Timestamps

<CodeGroup>
  ```javascript Node.js theme={null}
  const timestamp = message.timestamp;
  const date = new Date(timestamp);

  console.log(date.toLocaleDateString()); // Local date
  console.log(date.toLocaleTimeString()); // Local time
  ```

  ```python Python theme={null}
  from datetime import datetime

  timestamp = message['timestamp']
  date = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))

  print(date.strftime('%Y-%m-%d %H:%M:%S'))  # Formatted date/time
  ```
</CodeGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Authentication" icon="key" href="./authentication">
    Learn about API authentication methods
  </Card>

  <Card title="Core Concepts" icon="lightbulb" href="./concepts">
    Understand device enforcement and reconnection resilience
  </Card>

  <Card title="HTTP Endpoints" icon="server" href="./http/endpoints">
    Complete HTTP endpoint reference
  </Card>

  <Card title="WebSocket Actions" icon="paper-plane" href="./websocket/actions">
    WebSocket commands reference
  </Card>
</CardGroup>
