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

# 交易查詢

> 查詢付款、退款或撤銷交易的最新處理狀態

當商戶發起付款、退款或撤銷後，建議透過本查詢 API 確認交易最終狀態。

此接口適用於：

* 交易處於處理中（如 1143 / 1145）
* 避免重複請求
* 對帳與補償流程
* 系統異常後的狀態確認

***

# 查詢方式

支援以下查詢條件：

* 使用 QFPay 訂單號 `syssn`
* 使用商戶訂單號 `out_trade_no`
* 使用時間區間 `start_time` + `end_time`

<Note>
  若為退款交易，回應中將包含 `origssn`，對應原始付款交易的 `syssn`。
</Note>

***

# HTTP 請求

## Endpoint

```text TEXT theme={null}
POST /trade/v1/query
```

## Headers

```http HTTP theme={null}
Content-Type: application/x-www-form-urlencoded
X-QF-APPCODE: <your-app-code>
X-QF-SIGN: <signature>
```

***

# 請求參數

完整格式請參考：

[通用 API 請求格式](/zh-hant/integration/api-reference/request-format)

以下為交易查詢主要參數：

| 參數             | 類型          | 是否必填 | 說明                          |
| -------------- | ----------- | ---- | --------------------------- |
| `mchid`        | String(16)  | 視情況  | 若商戶開通時提供 `mchid`，則必填；否則不可傳入 |
| `syssn`        | String(128) | 否    | QFPay 訂單號，可多筆，使用逗號分隔        |
| `out_trade_no` | String(128) | 否    | 商戶訂單號，可多筆，使用逗號分隔            |
| `pay_type`     | String(6)   | 否    | 支付類型，可多筆，使用逗號分隔             |
| `respcd`       | String(4)   | 否    | 指定篩選特定狀態碼                   |
| `start_time`   | String(20)  | 否    | 開始時間，格式：YYYY-MM-DD HH:mm:ss |
| `end_time`     | String(20)  | 否    | 結束時間，格式：YYYY-MM-DD HH:mm:ss |
| `page`         | Integer     | 否    | 預設 1                        |
| `page_size`    | Integer     | 否    | 預設 10，最大 100                |

***

## 查詢規則說明

<Note>
  至少需提供以下其中一種條件：

  * `syssn`
  * `out_trade_no`
  * 或完整時間區間（`start_time` + `end_time`）
</Note>

<Note>
  跨月份查詢必須提供時間區間。
</Note>

***

# 程式碼範例

<Tabs>
  <Tab title="Tab">
    ```python Python theme={null}
    import hashlib
    import requests

    environment = 'https://test-openapi-hk.qfapi.com'
    app_code = 'YOUR_APP_CODE'
    client_key = 'YOUR_CLIENT_KEY'

    def make_sign(data, key):
        ordered = sorted(data.items())
        sign_str = "&".join(f"{k}={v}" for k, v in ordered) + key
        return hashlib.md5(sign_str.encode("utf-8")).hexdigest().upper()

    payload = {
        "syssn": "20191227000200020061752831"
    }

    headers = {
        "X-QF-APPCODE": app_code,
        "X-QF-SIGN": make_sign(payload, client_key)
    }

    response = requests.post(
        environment + "/trade/v1/query",
        data=payload,
        headers=headers
    )

    print(response.json())
    ```
  </Tab>

  <Tab title="Tab">
    ```javascript JavaScript theme={null}
    const crypto = require("crypto");
    const request = require("request");

    const environment = "https://test-openapi-hk.qfapi.com";
    const app_code = "YOUR_APP_CODE";
    const client_key = "YOUR_CLIENT_KEY";

    const payload = {
      syssn: "20191231000300020063521806"
    };

    const sorted = Object.keys(payload)
      .sort()
      .map(k => `${k}=${payload[k]}`)
      .join("&");

    const sign = crypto
      .createHash("md5")
      .update(sorted + client_key)
      .digest("hex")
      .toUpperCase();

    request({
      uri: environment + "/trade/v1/query",
      method: "POST",
      headers: {
        "X-QF-APPCODE": app_code,
        "X-QF-SIGN": sign
      },
      form: payload
    }, function(error, response, body) {
      console.log(body);
    });
    ```
  </Tab>
</Tabs>

***

# 回應欄位

詳細欄位請參考：

[通用 API 回應格式](/zh-hant/integration/api-reference/response-format)

以下為交易查詢常見欄位：

| 欄位                     | 類型      | 說明                   |
| ---------------------- | ------- | -------------------- |
| `syssn`                | String  | QFPay 交易編號           |
| `out_trade_no`         | String  | 商戶交易編號               |
| `txamt`                | Integer | 金額（單位：分）             |
| `txcurrcd`             | String  | 幣別代碼                 |
| `respcd`               | String  | 交易結果代碼               |
| `errmsg`               | String  | 交易結果說明               |
| `order_type`           | String  | `payment` 或 `refund` |
| `pay_type`             | String  | 支付方式代碼               |
| `cancel`               | String  | 撤銷 / 退款標記            |
| `cash_fee`             | String  | 實際支付金額               |
| `cash_fee_type`        | String  | 支付幣別                 |
| `cash_refund_fee`      | String  | 實際退款金額               |
| `cash_refund_fee_type` | String  | 退款幣別                 |
| `exchange_rate`        | String  | 匯率（跨幣交易時）            |
| `sysdtm`               | String  | QFPay 系統時間           |
| `txdtm`                | String  | 商戶交易時間               |
| `chnlsn`               | String  | 通道交易號                |
| `origssn`              | String  | 原始交易號（僅退款時返回）        |
| `note`                 | String  | 交易備注（有值時返回）          |

***

# 回應範例

```json JSON theme={null}
{
  "respcd": "0000",
  "resperr": "Request successful",
  "data": [
    {
      "syssn": "20230423000200020088888888",
      "out_trade_no": "YOUR_ORDER_001",
      "txamt": "100",
      "txcurrcd": "HKD",
      "respcd": "0000",
      "errmsg": "success",
      "pay_type": "801107",
	  "note": "sample note for payment",
      "order_type": "payment",
      "txdtm": "2023-04-23 12:00:00",
      "sysdtm": "2023-04-23 12:00:03",
      "cancel": "0",
      "cash_fee": "100",
      "cash_fee_type": "HKD"
    }
  ]
}
```

***

# 整合建議

1. 在收到 1143 / 1145 等處理中狀態時，請使用本查詢 API 確認最終結果。
2. 避免在未知狀態下重複發送支付請求。
3. 對帳流程應以 `syssn` 作為唯一交易識別。
4. 建議實作延遲查詢機制（例如 3–5 秒後再查詢）。
