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

# 取得所有交易

## 概觀

Transactions API 可讓你擷取與你的帳戶相關之所有金融交易的完整歷史。這包含購買、存款、提領、轉帳、帳單付款，以及所有其他金融活動。

**端點類型**: GraphQL Query\
**驗證**: 必要（JWT Bearer Token）\
**必要範圍**: `LIST_PAYMENT` AND `LIST_PURCHASES`\
**速率限制**: 適用標準 GraphQL 速率限制

***

## 快速開始

### 基本查詢

```graphql theme={null}
query GetTransactions {
  getTransactions {
    transactions {
      recordId
      transactionType
      amount
      status
      channel
      connectedAppId
      connectedAppName
      createdAt
    }
    totalCount
    hasNextPage
  }
}
```

<br />

***

## 查詢結構

```graphql theme={null}
getTransactions(
  filter: TransactionFilterInput
  paginate: OffsetInput
): TransactionConnection!
```

### 參數

| Parameter  | Type                     | Required | Description                 |
| ---------- | ------------------------ | -------- | --------------------------- |
| `filter`   | `TransactionFilterInput` | No       | 交易的篩選條件                     |
| `paginate` | `OffsetInput`            | No       | 分頁參數（預設：limit=20, offset=0） |

***

## 回應結構

### TransactionConnection

```graphql theme={null}
type TransactionConnection {
  transactions: [Transaction]
  totalCount: Int!
  hasNextPage: Boolean!
}
```

| Field          | Type            | Description       |
| -------------- | --------------- | ----------------- |
| `transactions` | `[Transaction]` | 交易紀錄的陣列           |
| `totalCount`   | `Int!`          | 符合篩選條件的交易總數（用於分頁） |
| `hasNextPage`  | `Boolean!`      | 是否有更多結果           |

***

## 篩選選項

### TransactionFilterInput

```graphql theme={null}
input TransactionFilterInput {
  # Record & Status
  recordId: [UUID]
  status: [TransactionStatus]
  
  # Amount Filters
  amount: Float
  amountGte: Float
  amountLte: Float
  finalAmount: Float
  finalAmountGte: Float
  finalAmountLte: Float
  
  # Cashback Filters
  cashbackAmount: Float
  cashbackAmountGte: Float
  cashbackAmountLte: Float
  cashbackPercentage: Float
  cashbackPercentageGte: Float
  cashbackPercentageLte: Float
  
  # Fee Filters
  feeAmount: Float
  feeAmountGte: Float
  feeAmountLte: Float
  
  # Date Filters
  createdGte: DateTime
  createdLte: DateTime
  updatedGte: DateTime
  updatedLte: DateTime
  
  # Merchant Filters
  merchantId: [UUID]
  merchant: [String]
  
  # Transaction Properties
  transactionType: [String]
  channel: [String!]
  category: [String]
  
  # Virtual Card Filters
  virtualCardProgram: [String]
  virtualCard: [UUID]
  
  # Other
  fundingSource: [String]
  userCashBalanceId: [UUID]
  referenceId: String
  liabilityId: UUID
}
```

### 篩選欄位詳解

#### 紀錄與狀態篩選

##### `recordId`

**Type**: `[UUID]`\
**Description**: 依特定交易紀錄 ID 篩選。

**Example**:

```graphql theme={null}
filter: {
  recordId: ["550e8400-e29b-41d4-a716-446655440000"]
}
```

##### `status`

**Type**: `[TransactionStatus]`\
**Description**: 依交易狀態篩選。

**Options**:

* `PENDING` - 交易處理中
* `SETTLED` - 交易已成功完成

**Example**:

```graphql theme={null}
filter: {
  status: [SETTLED]
}
```

***

#### 金額篩選

##### `amount`, `amountGte`, `amountLte`

**Type**: `Float`\
**Description**: 以美元計之精確金額或金額區間篩選。

* `amount` - 精確金額相符
* `amountGte` - 最低金額（大於等於）
* `amountLte` - 最高金額（小於等於）

**Example**:

```graphql theme={null}
# Transactions between $10 and $500
filter: {
  amountGte: 10.00
  amountLte: 500.00
}
```

##### `finalAmount`, `finalAmountGte`, `finalAmountLte`

**Type**: `Float`\
**Description**: 依最終金額（金額＋手續費）篩選。

**Example**:

```graphql theme={null}
filter: {
  finalAmountGte: 25.00
}
```

***

#### 現金回饋篩選

##### `cashbackAmount`, `cashbackAmountGte`, `cashbackAmountLte`

**Type**: `Float`\
**Description**: 依獲得的現金回饋金額篩選。

**Example**:

```graphql theme={null}
# Transactions that earned $5 or more in cashback
filter: {
  cashbackAmountGte: 5.00
}
```

##### `cashbackPercentage`, `cashbackPercentageGte`, `cashbackPercentageLte`

**Type**: `Float`\
**Description**: 依現金回饋百分比篩選。

**Example**:

```graphql theme={null}
# Transactions with 5% or higher cashback
filter: {
  cashbackPercentageGte: 5.0
}
```

***

#### 手續費篩選

##### `feeAmount`, `feeAmountGte`, `feeAmountLte`

**Type**: `Float`\
**Description**: 依交易手續費金額篩選。

**Example**:

```graphql theme={null}
# Transactions with fees
filter: {
  feeAmountGte: 0.01
}
```

***

#### 日期篩選

##### `createdGte`, `createdLte`

**Type**: `DateTime`\
**Format**: ISO 8601（例如 `2025-01-01T00:00:00Z`）\
**Description**: 依交易建立時間範圍篩選。

**Example**:

```graphql theme={null}
filter: {
  createdGte: "2025-01-01T00:00:00Z"
  createdLte: "2025-01-31T23:59:59Z"
}
```

##### `updatedGte`, `updatedLte`

**Type**: `DateTime`\
**Description**: 依交易最後更新時間範圍篩選。

***

#### 商家篩選

##### `merchantId`

**Type**: `[UUID]`\
**Description**: 依特定商家 ID 篩選。

**Example**:

```graphql theme={null}
filter: {
  merchantId: ["550e8400-e29b-41d4-a716-446655440000"]
}
```

##### `merchant`

**Type**: `[String]`\
**Description**: 依商家名稱篩選（比對 destination 欄位）。

**Example**:

```graphql theme={null}
filter: {
  merchant: ["Amazon", "Walmart"]
}
```

***

#### 交易屬性

##### `transactionType`

**Type**: `[String]`\
**Description**: 依特定交易類型篩選。

**Common Values**:

* `Add Money` - 存入
* `Gift Card Purchase` - 禮品卡購買
* `Transfer - In` - 轉入
* `Transfer - Out` - 轉出
* `Virtual Card Purchase` - 虛擬卡購買
* `Withdrawal`

<br />

**Example**:

```graphql theme={null}
filter: {
  transactionType: ["Gift Card Purchase", "Add Money"]
}
```

##### `channel`

**Type**: `[String!]`\
**Description**: 依平台通道篩選。

**Common Values**:

* `WEB` - 網頁瀏覽器
* `MOBILE` - 行動裝置 App
* `API` - API 請求

**Example**:

```graphql theme={null}
filter: {
  channel: ["WEB", "MOBILE"]
}
```

##### `category`

**Type**: `[String]`\
**Description**: 依交易分類篩選。

**Example**:

```graphql theme={null}
filter: {
  category: ["Shopping", "Travel"]
}
```

***

#### 虛擬卡篩選

##### `virtualCardProgram`

**Type**: `[String]`\
**Description**: 依虛擬卡方案／發卡方篩選。

**Example**:

```graphql theme={null}
filter: {
  virtualCardProgram: ["TRANSPECOS", "SUTTON"]
}
```

##### `virtualCard`

**Type**: `[UUID]`\
**Description**: 依特定虛擬卡 ID 篩選。

**Example**:

```graphql theme={null}
filter: {
  virtualCard: ["vc-1", "vc-2"]
}
```

***

#### 其他篩選

##### `fundingSource`

**Type**: `[String]`\
**Description**: 搜尋資金來源名稱（在來源或目的地做部分比對）。

**Example**:

```graphql theme={null}
filter: {
  fundingSource: ["Visa"]
}
```

##### `referenceId`

**Type**: `String`\
**Description**: 依外部參考 ID 篩選（例如購買顯示 ID）。

**Example**:

```graphql theme={null}
filter: {
  referenceId: "1000123"
}
```

##### `liabilityId`

**Type**: `UUID`\
**Description**: 依負債 ID 篩選（用於帳單付款）。

***

## 分頁

### OffsetInput

```graphql theme={null}
input OffsetInput {
  limit: Int = 20
  offset: Int = 0
}
```

| Field    | Type | Default | Max | Description |
| -------- | ---- | ------- | --- | ----------- |
| `limit`  | Int  | 20      | 20  | 每頁要回傳的交易數量  |
| `offset` | Int  | 0       | -   | 要略過的交易數量    |

**範例 - 第 1 頁**:

```graphql theme={null}
paginate: {
  limit: 20
  offset: 0
}
```

**範例 - 第 2 頁**:

```graphql theme={null}
paginate: {
  limit: 20
  offset: 20
}
```

**範例 - 檢查是否有更多頁**:

```graphql theme={null}
query GetTransactions {
  getTransactions(paginate: { limit: 20, offset: 0 }) {
    transactions { record_id }
    hasNextPage  # Use this to determine if there are more results
    totalCount   # Total matching records
  }
}
```

***

## Transaction Type

```graphql theme={null}
type Transaction {
  record_id: UUID
  user: String!
  account_id: UUID!
  user_id: UUID
  transaction_type: String
  amount: Float!
  destination: String
  source: String
  external_funding_source_activity: Float
  fluz_balance_activity: Float
  fee: Float
  cashback: Float
  
  # Ending balances after transaction
  gift_card_prepayment_balance_available_balance: Float
  gift_card_prepayment_balance_total_balance: Float
  cash_balance_available_balance: Float
  cash_balance_total_balance: Float
  seat_balance_available_balance: Float
  seat_balance_total_balance: Float
  reserve_balance_available_balance: Float
  reserve_balance_total_balance: Float
  other_cash_balance_available_balance: Float
  other_cash_balance_total_balance: Float
  
  status: TransactionStatus
  reference_id: String
  description: String
  note: String
  category: String
  card_last_four: String
  card_display_name: String
  original_currency_amount: Float
  original_currency_code: String
  conversion_rate: Float
  merchant_id: UUID
  descriptor_id: UUID
  virtual_card_program: String
  cashback_rate: Float
  bonus_cashback_rate: Float
  channel: String
  source_type: String
  logo_url: String
  platformInstitutionLogo: String
  challengeLogoUrl: String
  invitedAccountId: UUID
  expectedClearedDate: DateTime
  liability_id: UUID
  is_gift_card_balance_affected: Boolean
  is_cash_balance_affected: Boolean
  is_seat_balance_affected: Boolean
  is_reserve_balance_affected: Boolean
  transfer_id: UUID
  used_user_cash_balance_id: UUID
  connectedAppId: UUID
  connectedAppName: String
  
  memo: String
  transactionCategory: String
  attachmentUrl: String

  created_at: DateTime
  updated_at: DateTime
}
```

### 欄位說明

#### 核心交易欄位

| Field              | Type              | Description                       |
| ------------------ | ----------------- | --------------------------------- |
| `record_id`        | UUID              | 此交易紀錄的唯一識別碼                       |
| `user`             | String            | 與交易關聯的使用者顯示名稱                     |
| `account_id`       | UUID              | 擁有此交易的帳戶                          |
| `user_id`          | UUID              | 發起此交易的使用者                         |
| `transaction_type` | String            | 交易類型（PURCHASE、DEPOSIT 等）          |
| `amount`           | Float             | 主要交易金額（美元）                        |
| `source`           | String            | 資金來源（例如 "Bank Card \*\*\*\*1234"） |
| `destination`      | String            | 資金去向（例如商家名稱）                      |
| `status`           | TransactionStatus | 目前狀態（PENDING 或 SETTLED）           |

#### 金融明細

| Field                              | Type  | Description        |
| ---------------------------------- | ----- | ------------------ |
| `external_funding_source_activity` | Float | 對外部資金來源（銀行卡／帳戶）的變動 |
| `fluz_balance_activity`            | Float | 對 Fluz 內部餘額的變動     |
| `fee`                              | Float | 此交易收取的手續費          |
| `cashback`                         | Float | 此交易獲得的現金回饋         |
| `cashback_rate`                    | Float | 現金回饋百分比            |
| `bonus_cashback_rate`              | Float | 額外加成的現金回饋比例        |

#### 餘額快照

**重要**: 所有餘額欄位皆顯示在此交易「套用後」的餘額。

| Field                                            | Description |
| ------------------------------------------------ | ----------- |
| `cash_balance_available_balance`                 | 交易後可用現金餘額   |
| `cash_balance_total_balance`                     | 交易後現金總餘額    |
| `seat_balance_available_balance`                 | 交易後可用獎勵餘額   |
| `seat_balance_total_balance`                     | 交易後獎勵總餘額    |
| `gift_card_prepayment_balance_available_balance` | 交易後可用預付款餘額  |
| `gift_card_prepayment_balance_total_balance`     | 交易後預付款總餘額   |
| `reserve_balance_available_balance`              | 交易後可用保留餘額   |
| `reserve_balance_total_balance`                  | 交易後保留總餘額    |
| `other_cash_balance_available_balance`           | 交易後其他現金可用餘額 |
| `other_cash_balance_total_balance`               | 交易後其他現金總餘額  |

#### 交易明細

| Field                 | Type   | Description                                                                                                                          |
| :-------------------- | :----- | :----------------------------------------------------------------------------------------------------------------------------------- |
| `reference_id`        | String | 外部參考（例如購買顯示 ID）                                                                                                                      |
| `description`         | String | 人類可讀的描述                                                                                                                              |
| `note`                | String | 其他備註                                                                                                                                 |
| `category`            | String | 交易分類                                                                                                                                 |
| `card_last_four`      | String | 使用卡片的後四碼（若適用）                                                                                                                        |
| `card_display_name`   | String | 付款方式的顯示名稱                                                                                                                            |
| `memo`                | String | 附加在此交易上的自由文字備忘。可透過在 [`updateTransactionMetadata`](/features/add-expense-details) 設定，或於存款、購買與轉帳時設定。                                   |
| `transactionCategory` | String | 附加在此交易上的分類標籤。可透過在 [`updateTransactionMetadata`](/features/add-expense-details) 設定，或於存款、購買與轉帳時設定。                                     |
| `attachmentUrl`       | String | 附加在此交易之檔案的簽名 URL。可透過在 [`updateTransactionMetadata`](/features/add-expense-details) 設定，或於交易當下設定。**此 URL 會過期 — 請勿儲存。** 需要存取檔案時請重新擷取交易。 |

#### 商家資訊

| Field           | Type   | Description      |
| --------------- | ------ | ---------------- |
| `merchant_id`   | UUID   | 商家識別碼            |
| `descriptor_id` | UUID   | 交易敘述 ID          |
| `logo_url`      | String | 商家／來源 Logo 的 URL |

#### 虛擬卡資訊

| Field                  | Type   | Description             |
| ---------------------- | ------ | ----------------------- |
| `virtual_card_program` | String | 虛擬卡計畫（LITHIC、MARQETA 等） |

#### 貨幣換算

| Field                      | Type   | Description      |
| -------------------------- | ------ | ---------------- |
| `original_currency_amount` | Float  | 原始貨幣金額（跨境交易）     |
| `original_currency_code`   | String | 原始貨幣代碼（例如 "EUR"） |
| `conversion_rate`          | Float  | 套用的匯率            |

#### 中繼資料

| Field                           | Type     | Description          |
| ------------------------------- | -------- | -------------------- |
| `channel`                       | String   | 平台通道（WEB、MOBILE、API） |
| `source_type`                   | String   | 資金來源類型               |
| `liability_id`                  | UUID     | 關聯的負債（用於帳單付款）        |
| `transfer_id`                   | UUID     | 關聯的轉帳（P2P）           |
| `used_user_cash_balance_id`     | UUID     | 使用的特定現金餘額            |
| `is_gift_card_balance_affected` | Boolean  | 是否影響禮品卡餘額            |
| `is_cash_balance_affected`      | Boolean  | 是否影響現金餘額             |
| `is_seat_balance_affected`      | Boolean  | 是否影響獎勵餘額             |
| `is_reserve_balance_affected`   | Boolean  | 是否影響保留餘額             |
| `connectedAppId`                | UUID     | 關聯的應用程式 ID           |
| `connectedAppName`              | String   | 關聯的應用程式名稱            |
| `created_at`                    | DateTime | 交易建立時間               |
| `updated_at`                    | DateTime | 交易最後更新時間             |

***

## 範例

### 範例 1：基本交易清單

**Query**:

```graphql theme={null}
query GetRecentTransactions {
  getTransactions(
    paginate: { limit: 10, offset: 0 }
  ) {
    transactions {
      record_id
      transaction_type
      amount
      description
      status
      cashback
      created_at
    }
    totalCount
    hasNextPage
  }
}
```

**Response**:

```json theme={null}
{
  "data": {
    "getTransactions": {
      "transactions": [
        {
          "record_id": "550e8400-e29b-41d4-a716-446655440000",
          "transaction_type": "GIFT_CARD_PURCHASE",
          "amount": 50.00,
          "description": "Gift card purchase at Amazon",
          "status": "SETTLED",
          "cashback": 2.50,
          "created_at": "2025-01-15T14:30:00Z"
        },
        {
          "record_id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
          "transaction_type": "DEPOSIT",
          "amount": 100.00,
          "description": "Cash Balance Deposit",
          "status": "SETTLED",
          "cashback": 0.00,
          "created_at": "2025-01-14T10:15:00Z"
        }
      ],
      "totalCount": 2,
      "hasNextPage": false
    }
  }
}
```

***

### 範例 2：依日期範圍篩選

**Query**:

```graphql theme={null}
query GetJanuaryTransactions {
  getTransactions(
    filter: {
      createdGte: "2025-01-01T00:00:00Z"
      createdLte: "2025-01-31T23:59:59Z"
    }
    paginate: { limit: 20, offset: 0 }
  ) {
    transactions {
      record_id
      transaction_type
      amount
      description
      status
      created_at
    }
    totalCount
    hasNextPage
  }
}
```

***

### 範例 3：僅購買交易且包含餘額

**Query**:

```graphql theme={null}
query GetPurchaseHistory {
  getTransactions(
    filter: {
      transactionType: ["GIFT_CARD_PURCHASE"]
      status: [SETTLED]
    }
    paginate: { limit: 20, offset: 0 }
  ) {
    transactions {
      record_id
      reference_id
      amount
      description
      source
      destination
      cashback
      cashback_rate
      cash_balance_available_balance
      seat_balance_available_balance
      created_at
    }
    totalCount
    hasNextPage
  }
}
```

**Response**:

```json theme={null}
{
  "data": {
    "getTransactions": {
      "transactions": [
        {
          "record_id": "550e8400-e29b-41d4-a716-446655440000",
          "reference_id": "1000123",
          "amount": 50.00,
          "description": "Gift card purchase at Amazon",
          "source": "Visa ****1234",
          "destination": "Amazon",
          "cashback": 2.50,
          "cashback_rate": 5.0,
          "cash_balance_available_balance": 102.50,
          "seat_balance_available_balance": 25.00,
          "created_at": "2025-01-15T14:30:00Z"
        }
      ],
      "totalCount": 1,
      "hasNextPage": false
    }
  }
}
```

***

### 範例 4：高現金回饋交易

**Query**:

```graphql theme={null}
query GetHighCashbackTransactions {
  getTransactions(
    filter: {
      cashbackPercentageGte: 5.0
      status: [SETTLED]
    }
    paginate: { limit: 10, offset: 0 }
  ) {
    transactions {
      record_id
      transaction_type
      amount
      description
      cashback
      cashback_rate
      status
      created_at
    }
    totalCount
  }
}
```

***

### 範例 5：金額區間篩選

**Query**:

```graphql theme={null}
query GetMediumTransactions {
  getTransactions(
    filter: {
      amountGte: 50.00
      amountLte: 200.00
      status: [SETTLED]
    }
    paginate: { limit: 20, offset: 0 }
  ) {
    transactions {
      record_id
      amount
      transaction_type
      description
      created_at
    }
    totalCount
    hasNextPage
  }
}
```

***

### 範例 6：虛擬卡交易

**Query**:

```graphql theme={null}
query GetVirtualCardTransactions {
  getTransactions(
    filter: {
      virtualCardProgram: ["LITHIC", "MARQETA"]
    }
    paginate: { limit: 20, offset: 0 }
  ) {
    transactions {
      record_id
      amount
      description
      virtual_card_program
      merchant_id
      status
      created_at
    }
    totalCount
  }
}
```

***

### 範例 7：分頁示例

**Query - 取得第一頁並檢查是否有更多**:

```graphql theme={null}
query GetFirstPage {
  getTransactions(paginate: { limit: 20, offset: 0 }) {
    transactions {
      record_id
      amount
      transaction_type
    }
    totalCount
    hasNextPage
  }
}
```

**Response 顯示 hasNextPage=true**:

```json theme={null}
{
  "data": {
    "getTransactions": {
      "transactions": [...],
      "totalCount": 150,
      "hasNextPage": true
    }
  }
}
```

**Query - 取得第二頁**:

```graphql theme={null}
query GetSecondPage {
  getTransactions(paginate: { limit: 20, offset: 20 }) {
    transactions {
      record_id
      amount
      transaction_type
    }
    totalCount
    hasNextPage
  }
}
```

***

## 錯誤處理

### 常見錯誤

#### 缺少或無效的權杖

```json theme={null}
{
  "errors": [
    {
      "message": "Authentication required",
      "extensions": {
        "code": "UNAUTHENTICATED"
      }
    }
  ]
}
```

**HTTP 狀態**: 401 Unauthorized

***

#### 權限不足

```json theme={null}
{
  "errors": [
    {
      "message": "Insufficient permissions: LIST_PAYMENT and LIST_PURCHASES scopes required",
      "extensions": {
        "code": "FORBIDDEN",
        "requiredScopes": ["LIST_PAYMENT", "LIST_PURCHASES"]
      }
    }
  ]
}
```

**HTTP 狀態**: 403 Forbidden

***

#### 無效的篩選參數

```json theme={null}
{
  "errors": [
    {
      "message": "Invalid date format for createdGte",
      "extensions": {
        "code": "BAD_USER_INPUT"
      }
    }
  ]
}
```

**HTTP 狀態**: 400 Bad Request

***

#### 超出速率限制

```json theme={null}
{
  "errors": [
    {
      "message": "Rate limit exceeded. Please try again later.",
      "extensions": {
        "code": "RATE_LIMITED",
        "retryAfter": 60
      }
    }
  ]
}
```

**HTTP 狀態**: 429 Too Many Requests

***

## 最佳實務

### 1. 有效使用分頁

務必檢查 `hasNextPage` 以判斷是否有更多結果：

```javascript theme={null}
async function fetchAllTransactions() {
  const allTransactions = [];
  let offset = 0;
  const limit = 20;
  
  while (true) {
    const result = await getTransactions({ 
      paginate: { limit, offset } 
    });
    
    allTransactions.push(...result.transactions);
    
    if (!result.hasNextPage) break;
    offset += limit;
  }
  
  return allTransactions;
}
```

### 2. 僅請求所需欄位

只指定你需要的欄位以減少回應大小：

```graphql theme={null}
# Good - minimal fields
getTransactions {
  transactions {
    record_id
    amount
    transaction_type
    created_at
  }
  totalCount
  hasNextPage
}

# Less efficient - requesting all 40+ fields
getTransactions {
  transactions {
    record_id
    transaction_type
    amount
    ... (all fields)
  }
}
```

### 3. 歷史查詢使用日期篩選

當查詢較早的交易時，務必使用日期篩選：

```graphql theme={null}
# Good
filter: {
  createdGte: "2024-01-01T00:00:00Z"
  createdLte: "2024-12-31T23:59:59Z"
}
```

### 4. 快取已結清交易

`status: SETTLED` 的交易是不可變的，可以進行快取：

```javascript theme={null}
// Example caching strategy
const cacheKey = `transactions:${accountId}:${createdGte}:${createdLte}`;
let result = cache.get(cacheKey);

if (!result) {
  result = await getTransactions({
    filter: { status: ['SETTLED'], createdGte, createdLte }
  });
  cache.set(cacheKey, result, '1 hour');
}
```

### 5. 有效組合篩選

先使用範圍條件縮小結果，再套用其他篩選：

```graphql theme={null}
# Efficient - date range first
filter: {
  createdGte: "2025-01-01T00:00:00Z"
  createdLte: "2025-01-31T23:59:59Z"
  transactionType: ["GIFT_CARD_PURCHASE"]
  amountGte: 50.00
}
```

***

## 速率限制

| Resource   | Limit | Window   |
| ---------- | ----- | -------- |
| 每位使用者的查詢數  | 100   | 1 minute |
| 每個 IP 的查詢數 | 300   | 1 minute |

**標頭**:

* `X-RateLimit-Limit` - 允許的最大請求數
* `X-RateLimit-Remaining` - 目前視窗剩餘請求數
* `X-RateLimit-Reset` - 速率限制重置時間（Unix 時間戳）

***

## 程式碼範例

### JavaScript/TypeScript

```typescript theme={null}
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://api.fluz.app/graphql',
  cache: new InMemoryCache(),
  headers: {
    authorization: `Bearer ${accessToken}`,
  },
});

const GET_TRANSACTIONS = gql`
  query GetTransactions($filter: TransactionFilterInput, $paginate: OffsetInput) {
    getTransactions(filter: $filter, paginate: $paginate) {
      transactions {
        record_id
        transaction_type
        amount
        description
        status
        cashback
        created_at
      }
      totalCount
      hasNextPage
    }
  }
`;

async function fetchTransactions() {
  const { data } = await client.query({
    query: GET_TRANSACTIONS,
    variables: {
      filter: {
        status: ['SETTLED'],
        createdGte: '2025-01-01T00:00:00Z',
      },
      paginate: {
        limit: 20,
        offset: 0,
      },
    },
  });
  
  return data.getTransactions;
}
```

***

### Python

```python theme={null}
import requests

def get_transactions(access_token, created_gte=None, created_lte=None, limit=20, offset=0):
    url = "https://api.fluz.app/graphql"
    
    query = """
        query GetTransactions($filter: TransactionFilterInput, $paginate: OffsetInput) {
            getTransactions(filter: $filter, paginate: $paginate) {
                transactions {
                    record_id
                    transaction_type
                    amount
                    description
                    status
                    cashback
                    created_at
                }
                totalCount
                hasNextPage
            }
        }
    """
    
    variables = {
        "filter": {},
        "paginate": {
            "limit": limit,
            "offset": offset
        }
    }
    
    if created_gte:
        variables["filter"]["createdGte"] = created_gte
    if created_lte:
        variables["filter"]["createdLte"] = created_lte
    
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }
    
    response = requests.post(
        url,
        json={"query": query, "variables": variables},
        headers=headers
    )
    
    return response.json()["data"]["getTransactions"]

# Usage
result = get_transactions(
    access_token="your_token_here",
    created_gte="2025-01-01T00:00:00Z",
    limit=20
)

print(f"Found {result['totalCount']} transactions")
print(f"Has more pages: {result['hasNextPage']}")
```

***

### cURL

```bash theme={null}
curl -X POST https://api.fluz.app/graphql \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query GetTransactions($filter: TransactionFilterInput, $paginate: OffsetInput) { getTransactions(filter: $filter, paginate: $paginate) { transactions { record_id transaction_type amount description status cashback created_at } totalCount hasNextPage } }",
    "variables": {
      "filter": {
        "status": ["SETTLED"],
        "createdGte": "2025-01-01T00:00:00Z"
      },
      "paginate": {
        "limit": 20,
        "offset": 0
      }
    }
  }'
```

***

## 常見問題

### 問：一次請求最多可以擷取多少筆交易？

答：每次請求的上限是 20 筆交易。請使用 `hasNextPage` 欄位實作分頁。

### 問：交易歷史可以回溯多久？

答：自帳戶建立以來的所有交易都可無限期取得。

### 問：會包含處理中的交易嗎？

答：會，預設包含處理中的交易。若要排除，請以 `status: [SETTLED]` 進行篩選。

### 問：時間戳的時區是什麼？

答：所有時間戳皆為 UTC（ISO 8601 格式）。

### 問：我需要哪些範圍（scopes）？

答：你需要同時具備 `LIST_PAYMENT` 和 `LIST_PURCHASES` 兩個範圍。

### 問：我可以在我的帳戶內依使用者 ID 篩選嗎？

答：不行。API 一律回傳你帳戶的所有交易，沒有使用者層級的篩選。

### 問：`amount` 與 `finalAmount` 的差異是什麼？

答：

* `amount` 會以基礎交易金額篩選
* `finalAmount` 會以金額＋手續費（向使用者實際收取的總額）篩選

### 問：如何依日期範圍篩選？

答：請使用 `createdGte` 與 `createdLte` 來限定建立日期：

```graphql theme={null}
filter: {
  createdGte: "2025-01-01T00:00:00Z"
  createdLte: "2025-01-31T23:59:59Z"
}
```

***

## 技術支援

* API 狀態: [https://status.fluz.app](https://status.fluz.app)
* 開發者入口: [https://developers.fluz.app](https://developers.fluz.app)
* 支援信箱: [api-support@fluz.app](mailto:api-support@fluz.app)
* Slack 社群: [https://fluz-dev.slack.com](https://fluz-dev.slack.com)

***

## 更新日誌

### v1.0.0（分支：13-fluz-15659-add-transactions-query-and-webhook-to-api）

* 初版釋出 Transactions Query API
* 支援全面性的篩選（15+ 種篩選類型）
* 以 `TransactionConnection` 回應類型提供分頁
* 交易紀錄中包含餘額快照
* 需要 `LIST_PAYMENT` 與 `LIST_PURCHASES` 範圍
* 只提供帳戶層級的交易存取

***

需要協助嗎？請聯絡我們的開發者支援團隊 [api-support@fluz.app](mailto:api-support@fluz.app) 或造訪我們的 [Developer Portal](https://developers.fluz.app)。
