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

# 查询单笔交易

> 查询已有支付、退款或争议交易的当前状态。使用 OAuth2 Bearer Token，无需请求签名。`order_number` 与 `merchant_order_no` 至少提供一个，同时提供时必须匹配同一笔交易。第三方凭证匹配多笔时返回 code=1，请补充 BillBuddy 交易单号。

code=0 表示查询成功；支付结果以 data.status 为准。已取消的交易优先返回 result=Cancelled，同时仍返回该交易的 status。金额以主货币单位、两位小数字符串返回。时间使用 Australia/Sydney（适用夏令时）；格式见各字段。查询仅返回当前状态，不会发起或重新执行支付。未查询到交易时，请先核实订单信息和处理状态，不要直接重新扣款。

merchant_id 为可选业务筛选条件，省略或为空时查询当前认证商户的全部业务；传入时仅查询指定业务。若订单凭证在多个业务中重复，可指定 merchant_id 缩小范围，或补充 order_number 唯一定位交易。



## OpenAPI

````yaml /openapi/billbuddy-v2-openapi.yaml get /api/v2/trans/queryTrans
openapi: 3.0.3
info:
  title: BillBuddy API 接入文档
  version: 2.0.0
  description: >
    BillBuddy API
    接入文档，本文收录第三方服务端主动调用的认证、交易和订阅接口。请求与响应示例均使用完整但虚构的业务数据及离线生成的演示令牌，不能用于实际认证或交易。


    ## 接入步骤

    1. 向 BillBuddy 获取 Client ID、Client Secret、商户标识及业务标识。如启用 IP 白名单，请使用已获准的固定出口
    IP 调用。

    2. 通过 POST /oauth/token 获取 access_token。业务请求携带 Authorization: Bearer
    {access_token} 和 Accept: application/json。JSON 请求使用 Content-Type:
    application/json；获取令牌使用表单。

    3. 按需调用支付或订阅接口。客户通过 activation_url 打开托管激活页；Client Secret 仅可保存在商户服务端。


    ## 标识及金额

    商户身份由 OAuth 凭据确定，无需在请求中传 business_id。需要指定业务的接口使用 merchant_id；单笔交易查询和批次结果查询的
    merchant_id 可选，省略或为空时在当前商户全部业务范围内查询；交易列表使用可选的
    Mid（区分大小写），省略时查询当前商户的全部业务。业务标识必须属于凭据所属商户。响应中的标识请按各接口字段说明读取。

    除 TXT 批量上传文件及其 amount_cents/declared_total_amount_cents
    使用分外，金额使用主货币单位，最多两位小数，例如 10.50 表示 AUD 10.50。银行账号、卡号、月份、年份和邮编建议使用字符串，以保留前导零。


    ## 成功和失败

    业务 JSON 成功 code=0，常规失败 code=1。交易及订阅业务接口参数校验失败通常为 code=400、data={}，HTTP 状态仍为
    200。V2 业务接口认证失败为 code=1，plan/list 标识业务校验失败为 code=1。HTTP 429 表示请求超过频率限制。OAuth
    端点采用标准 OAuth 响应（HTTP 200/400/401/429）。

    code=0 表示接口处理成功，扣款结果须另行判断：批量 accepted 仅表示请求已受理，将异步处理；银行 Pending、预约 Pending 和
    3DS 待验证均不代表支付成功。交易、DDR 订阅和扣费计划各自使用不同的 status 枚举，请参阅对应字段说明。


    ## 日期及频率

    请求日期建议使用 YYYY-MM-DD。今天及明天均按服务业务时区 Australia/Sydney 计算（适用夏令时）；预约取消时间以
    Australia/Sydney 为准（适用夏令时），仅允许在处理日 08:15 之前取消，到达该时刻即不可取消。支付 complete_date
    与收银台 expires_at 使用 DD/MM/YYYY HH:mm:ss，其他时间格式见字段说明。

    RRULE 标准示例：Daily FREQ=DAILY;INTERVAL=1；Weekly
    FREQ=WEEKLY;INTERVAL=1;BYDAY=MO；Fortnightly
    FREQ=WEEKLY;INTERVAL=2;BYDAY=MO；Monthly
    FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15；Quarterly
    FREQ=MONTHLY;INTERVAL=3;BYMONTHDAY=15；Half Yearly
    FREQ=MONTHLY;INTERVAL=6;BYMONTHDAY=15；Yearly
    FREQ=YEARLY;INTERVAL=1;BYMONTH=2;BYMONTHDAY=15。星期缩写为
    MO/TU/WE/TH/FR/SA/SU。Weekly/Monthly 省略具体扣费日时按起算日确定；单一 BYDAY=SA 或 SU
    按周一处理，未指定具体日期且起算日在周末时也按周一处理。单值 BYMONTHDAY=29/30/31 在短月按月末处理；BYMONTHDAY=-1
    表示月底。所有规则须符合有效 RRULE 格式。

    非标准频率（如每 10 天）须同时传 process_type=12、custom_cycle_type=1、custom_cycle=10，且
    day_of_debit=FREQ=DAILY;INTERVAL=10。单位 1/2/3/4 对应
    DAILY/WEEKLY/MONTHLY/YEARLY，以天为单位时间隔最小为 5，其余单位最小为 1，INTERVAL 须等于
    custom_cycle。季度、半年及年度还须提供 day_of_debit_dtstart；完整日期须严格晚于同段
    start_date，并在其后一个计费周期内。createSchedule 的实际首次扣费日期由 DDR 起算日、扣费频率及最早明天的限制共同确定。


    ## 使用示例

    参数类型、可空、长度、枚举及数值范围见 Schema；条件必填、日期及业务限制见字段 description。请结合两者使用。curl 示例中的
    BASE_URL、ACCESS_TOKEN、CLIENT_ID 和 CLIENT_SECRET 需由调用方设置；实际测试或生产域名由 BillBuddy
    提供。示例中的客户、订单、卡号、账户及日期须替换为测试环境允许使用且满足日期限制的数据。


    ## 托管订阅接入

    调用 POST /api/v2/subscription/create 创建订阅，取得 activation_url 后原样用于浏览器跳转或
    iframe 的 src；也可将 activation_html 用作 iframe 的 srcdoc。客户在 BillBuddy
    提供的页面填写支付信息并完成授权和激活。请使用返回的完整链接，无需自行拼接地址或解析链接中的凭证。Client Secret 和
    access_token 仅保存在商户服务端，不得放入 iframe 地址或页面内容。


    周期订阅及 By agreement 须在 start_date 当天之前激活；纯一次性订阅须在创建后 30
    天内提交激活。页面可以打开不保证仍可提交，以激活接口结果为准。


    ## 示例数据约定

    示例中的商户、客户、订单、支付 Token、会话链接和 OAuth 凭据均为虚构，不能用于真实调用。银行卡使用标准测试卡号；银行账户为虚构账户；邮箱使用
    example.com 保留域名，电话号码使用澳大利亚保留的演示号码。请求中的 BASE_URL、ACCESS_TOKEN、CLIENT_ID 和
    CLIENT_SECRET 仍需替换为获准测试环境的实际值。示例中必要的空字符串、null、空数组、0 和 false
    表示实际接口状态，不能统一替换为非空值。

    支付响应的 sign 按各支付场景的签名规则，使用公开演示密钥 bb_docs_demo_signing_key_2030 离线计算。3DS
    待验证响应的 html 不参与签名计算。该密钥仅用于文档，不能用于实际签名或认证。


    ## TXT 批量交易

    使用 multipart/form-data 上传固定宽度 TXT 文件。文件金额及
    amount_cents、declared_total_amount_cents 均以分计，不含附加费；文件格式和示例文件见“上传 TXT
    批量交易文件”。上传成功仅表示已接收，请保存 batch_id 和 file_identifier，并使用批次结果接口查询逐笔状态。批次
    completed 不代表所有支付成功。查询结果须使用同一商户的 OAuth 凭据；merchant_id
    可省略，如传入则须与原上传请求的业务标识一致。响应字段含义以对应接口说明为准。


    ## 开发语言请求示例

    请求示例提供 cURL、Python、JavaScript、PHP、Go、Java 和 Ruby，同一语言下可切换各业务场景。各语言使用与 cURL
    对应场景相同的请求参数和类型。


    运行环境：cURL；Python 3.9+（标准库）；JavaScript 使用 Node.js 18+，保存为 .mjs 后运行；PHP 8+ 并启用
    cURL 扩展；Go 1.20+；Java 11+（示例类名为 Example，保存为 Example.java）；Ruby 3+（标准库）。


    运行前设置 BASE_URL；业务接口还需设置 ACCESS_TOKEN，获取令牌需设置 CLIENT_ID 和
    CLIENT_SECRET。BASE_URL 使用 API 根地址，不附加 /api/v2。TXT 上传示例从当前目录读取
    payments.txt。请先替换为获准测试数据，并结合响应 code 和业务状态判断结果。
servers:
  - url: https://staging-api.billbuddyhq.com
    description: Staging 测试环境
security:
  - oauth2: []
tags:
  - name: 认证
    description: OAuth2 Client Credentials。
  - name: 交易
    description: 单笔、批量与预约取消。
  - name: 订阅
    description: 订阅模板、创建订阅、创建并激活 DDR 及推送扣费计划。
paths:
  /api/v2/trans/queryTrans:
    get:
      tags:
        - 交易
      summary: 查询单笔交易
      description: >-
        查询已有支付、退款或争议交易的当前状态。使用 OAuth2 Bearer Token，无需请求签名。`order_number` 与
        `merchant_order_no` 至少提供一个，同时提供时必须匹配同一笔交易。第三方凭证匹配多笔时返回 code=1，请补充
        BillBuddy 交易单号。


        code=0 表示查询成功；支付结果以 data.status 为准。已取消的交易优先返回 result=Cancelled，同时仍返回该交易的
        status。金额以主货币单位、两位小数字符串返回。时间使用
        Australia/Sydney（适用夏令时）；格式见各字段。查询仅返回当前状态，不会发起或重新执行支付。未查询到交易时，请先核实订单信息和处理状态，不要直接重新扣款。


        merchant_id 为可选业务筛选条件，省略或为空时查询当前认证商户的全部业务；传入时仅查询指定业务。若订单凭证在多个业务中重复，可指定
        merchant_id 缩小范围，或补充 order_number 唯一定位交易。
      operationId: v2QueryTransaction
      parameters:
        - name: merchant_id
          in: query
          required: false
          description: 可选业务标识，最长20个字符；传入时必须属于当前认证商户。省略或为空时在该商户全部业务范围内定位交易。
          schema:
            type: string
            maxLength: 20
            nullable: true
          example: '48290713'
        - name: order_number
          in: query
          required: false
          description: BillBuddy 交易单号，与 merchant_order_no 至少提供一个；同时提供时必须对应同一笔交易。
          schema:
            type: string
            maxLength: 60
            nullable: true
          example: b1893452400000741
        - name: merchant_order_no
          in: query
          required: false
          description: 第三方订单凭证，与 order_number 至少提供一个；若匹配多笔交易，须补充 order_number。
          schema:
            type: string
            maxLength: 64
            nullable: true
          example: ORDER-20300101-001
      responses:
        '200':
          description: HTTP 200。code=0 表示查询成功，code=1 表示业务或认证失败，code=400 表示查询参数不符合要求。
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/TransactionQueryResponse'
                  - $ref: '#/components/schemas/PublicApiError'
              examples:
                successful:
                  summary: 支付成功
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893452400000741
                      merchant_order_no: ORDER-20300101-001
                      trans_type: 1
                      trans_type_text: Payment
                      original_order_number: null
                      status: 1
                      status_text: Successful
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 01/01/2030 10:00:00
                      complete_date: 01/01/2030 10:00:05
                      process_date: null
                      cancelled_at: null
                      expired_at: null
                      payment_method:
                        type: 2
                        type_text: Credit
                        card_brand: Visa
                        wallet_type: null
                      result: Successful
                pending:
                  summary: Pending
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893452400000741
                      merchant_order_no: ORDER-20300101-001
                      trans_type: 1
                      trans_type_text: Payment
                      original_order_number: null
                      status: 3
                      status_text: Pending
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 01/01/2030 10:00:00
                      complete_date: null
                      process_date: null
                      cancelled_at: null
                      expired_at: null
                      payment_method:
                        type: 2
                        type_text: Credit
                        card_brand: Visa
                        wallet_type: null
                      result: Pending
                failed:
                  summary: Failed
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893452400000741
                      merchant_order_no: ORDER-20300101-001
                      trans_type: 1
                      trans_type_text: Payment
                      original_order_number: null
                      status: 2
                      status_text: Failed
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 01/01/2030 10:00:00
                      complete_date: 01/01/2030 10:00:05
                      process_date: null
                      cancelled_at: null
                      expired_at: null
                      payment_method:
                        type: 2
                        type_text: Credit
                        card_brand: Visa
                        wallet_type: null
                      result: Failed
                expired:
                  summary: Expired
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893452400000741
                      merchant_order_no: ORDER-20300101-001
                      trans_type: 1
                      trans_type_text: Payment
                      original_order_number: null
                      status: 4
                      status_text: Expired
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 01/01/2030 10:00:00
                      complete_date: 01/01/2030 10:00:05
                      process_date: null
                      cancelled_at: null
                      expired_at: null
                      payment_method:
                        type: 2
                        type_text: Credit
                        card_brand: Visa
                        wallet_type: null
                      result: Expired
                cancelled:
                  summary: Cancelled
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893452400000741
                      merchant_order_no: ORDER-20300101-001
                      trans_type: 1
                      trans_type_text: Payment
                      original_order_number: null
                      status: 2
                      status_text: Failed
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 01/01/2030 10:00:00
                      complete_date: null
                      process_date: '2030-01-02'
                      cancelled_at: 01/01/2030 10:10:00
                      expired_at: null
                      payment_method:
                        type: 2
                        type_text: Credit
                        card_brand: Visa
                        wallet_type: null
                      result: Cancelled
                notFound:
                  summary: Transaction not found
                  value:
                    code: 1
                    message: Transaction not found
                    data: {}
                ambiguousReference:
                  summary: Multiple transactions found; please provide order_number
                  value:
                    code: 1
                    message: Multiple transactions found; please provide order_number
                    data: {}
                permissionDenied:
                  summary: Permission denied
                  value:
                    code: 1
                    message: Permission denied
                    data: {}
                invalidBusiness:
                  summary: Business Merchant not found
                  value:
                    code: 1
                    message: Business Merchant not found
                    data: {}
                validationError:
                  summary: >-
                    The order number field is required when merchant order no is
                    not present.
                  value:
                    code: 400
                    message: >-
                      The order number field is required when merchant order no
                      is not present.
                    data: {}
                internalError:
                  summary: Transaction query failed due to internal error
                  value:
                    code: 1
                    message: Transaction query failed due to internal error
                    data: {}
                unauthenticated:
                  summary: 认证失败
                  value:
                    code: 1
                    message: Unauthenticated, invalid or expired access token
                    data: []
                refund:
                  summary: 退款交易
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893456000000629
                      merchant_order_no: REFUND-20300101-001
                      trans_type: 2
                      trans_type_text: Refund
                      original_order_number: b1893452400000741
                      status: 1
                      status_text: Successful
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 01/01/2030 11:00:00
                      complete_date: 01/01/2030 11:00:05
                      process_date: null
                      cancelled_at: null
                      expired_at: null
                      payment_method:
                        type: 2
                        type_text: Credit
                        card_brand: Visa
                        wallet_type: null
                      result: Successful
                noPaymentMethod:
                  summary: 支付方式信息不可用
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893452400000741
                      merchant_order_no: ORDER-20300101-001
                      trans_type: 1
                      trans_type_text: Payment
                      original_order_number: null
                      status: 3
                      status_text: Pending
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 01/01/2030 10:00:00
                      complete_date: null
                      process_date: null
                      cancelled_at: null
                      expired_at: null
                      payment_method: null
                      result: Pending
                applePay:
                  summary: Apple Pay 支付
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893452400000741
                      merchant_order_no: ORDER-20300101-001
                      trans_type: 1
                      trans_type_text: Payment
                      original_order_number: null
                      status: 1
                      status_text: Successful
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 01/01/2030 10:00:00
                      complete_date: 01/01/2030 10:00:05
                      process_date: null
                      cancelled_at: null
                      expired_at: null
                      payment_method:
                        type: 2
                        type_text: Credit
                        card_brand: Visa
                        wallet_type: APPLE_PAY
                      result: Successful
                dispute:
                  summary: 争议交易
                  value:
                    code: 0
                    message: ok
                    data:
                      business_id: '7294815'
                      merchant_id: '48290713'
                      order_number: b1893538800000368
                      merchant_order_no: ''
                      trans_type: 3
                      trans_type_text: Dispute
                      original_order_number: b1893452400000741
                      status: 1
                      status_text: Successful
                      amount: '10.00'
                      currency: AUD
                      surcharge_amount: '0.50'
                      surcharge_currency: AUD
                      payment_amount: '10.50'
                      payment_currency: AUD
                      created_at: 02/01/2030 10:00:00
                      complete_date: 02/01/2030 10:00:05
                      process_date: null
                      cancelled_at: null
                      expired_at: null
                      payment_method:
                        type: 2
                        type_text: Credit
                        card_brand: Visa
                        wallet_type: null
                      result: Successful
        '429':
          description: >-
            请求超过频率限制。API 请求共享每分钟 120 次的限额，通常按请求来源 IP 计数，并非每个接口单独 120 次。请遵循
            Retry-After 指定的等待秒数。
      security:
        - oauth2: []
      x-codeSamples:
        - lang: Shell
          label: 按 BillBuddy 交易单号查询
          source: |-
            curl --get "${BASE_URL}/api/v2/trans/queryTrans" \
              -H "Authorization: Bearer ${ACCESS_TOKEN}" \
              -H "Accept: application/json" \
              --data-urlencode merchant_id=48290713 \
              --data-urlencode order_number=b1893452400000741
        - lang: Shell
          label: 按第三方订单凭证查询
          source: |-
            curl --get "${BASE_URL}/api/v2/trans/queryTrans" \
              -H "Authorization: Bearer ${ACCESS_TOKEN}" \
              -H "Accept: application/json" \
              --data-urlencode merchant_id=48290713 \
              --data-urlencode merchant_order_no=ORDER-20300101-001
        - lang: Python
          label: 按 BillBuddy 交易单号查询
          source: >
            import json

            import os

            import urllib.parse

            import urllib.request


            base_url = os.environ["BASE_URL"].rstrip("/")

            url = base_url + "/api/v2/trans/queryTrans"

            headers = {"Accept": "application/json"}

            headers["Authorization"] = "Bearer " + os.environ["ACCESS_TOKEN"]

            params = {
                "merchant_id": "48290713",
                "order_number": "b1893452400000741",
            }

            url += "?" + urllib.parse.urlencode(params)

            body = None


            request = urllib.request.Request(url, data=body, headers=headers,
            method="GET")

            with urllib.request.urlopen(request, timeout=30) as response:
                print(response.read().decode("utf-8"))
        - lang: Python
          label: 按第三方订单凭证查询
          source: >
            import json

            import os

            import urllib.parse

            import urllib.request


            base_url = os.environ["BASE_URL"].rstrip("/")

            url = base_url + "/api/v2/trans/queryTrans"

            headers = {"Accept": "application/json"}

            headers["Authorization"] = "Bearer " + os.environ["ACCESS_TOKEN"]

            params = {
                "merchant_id": "48290713",
                "merchant_order_no": "ORDER-20300101-001",
            }

            url += "?" + urllib.parse.urlencode(params)

            body = None


            request = urllib.request.Request(url, data=body, headers=headers,
            method="GET")

            with urllib.request.urlopen(request, timeout=30) as response:
                print(response.read().decode("utf-8"))
        - lang: JavaScript
          label: 按 BillBuddy 交易单号查询
          source: |
            const env = (name) => {
              const value = process.env[name];
              if (!value) throw new Error(`Missing environment variable: ${name}`);
              return value;
            };
            const baseUrl = env("BASE_URL").replace(/\/+$/, "");
            const url = new URL(baseUrl + "/api/v2/trans/queryTrans");
            const headers = { Accept: "application/json" };
            headers.Authorization = `Bearer ${env("ACCESS_TOKEN")}`;
            const params = new URLSearchParams({
              "merchant_id": "48290713",
              "order_number": "b1893452400000741",
            });
            url.search = params.toString();

            const response = await fetch(url, {
              method: "GET",
              headers,
              signal: AbortSignal.timeout(30_000),
            });
            console.log(await response.text());
        - lang: JavaScript
          label: 按第三方订单凭证查询
          source: |
            const env = (name) => {
              const value = process.env[name];
              if (!value) throw new Error(`Missing environment variable: ${name}`);
              return value;
            };
            const baseUrl = env("BASE_URL").replace(/\/+$/, "");
            const url = new URL(baseUrl + "/api/v2/trans/queryTrans");
            const headers = { Accept: "application/json" };
            headers.Authorization = `Bearer ${env("ACCESS_TOKEN")}`;
            const params = new URLSearchParams({
              "merchant_id": "48290713",
              "merchant_order_no": "ORDER-20300101-001",
            });
            url.search = params.toString();

            const response = await fetch(url, {
              method: "GET",
              headers,
              signal: AbortSignal.timeout(30_000),
            });
            console.log(await response.text());
        - lang: PHP
          label: 按 BillBuddy 交易单号查询
          source: |
            <?php
            $env = static function (string $name): string {
                $value = getenv($name);
                if ($value === false || $value === '') {
                    throw new RuntimeException("Missing environment variable: " . $name);
                }
                return $value;
            };
            $baseUrl = rtrim($env('BASE_URL'), '/');
            $url = $baseUrl . "/api/v2/trans/queryTrans";
            $headers = ['Accept: application/json'];
            $headers[] = 'Authorization: Bearer ' . $env('ACCESS_TOKEN');
            $params = [
                "merchant_id" => "48290713",
                "order_number" => "b1893452400000741",
            ];
            $url .= '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);

            $curl = curl_init($url);
            curl_setopt_array($curl, [
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
            ]);
            $response = curl_exec($curl);
            if ($response === false) {
                $error = curl_error($curl);
                curl_close($curl);
                throw new RuntimeException($error);
            }
            curl_close($curl);
            echo $response, PHP_EOL;
        - lang: PHP
          label: 按第三方订单凭证查询
          source: |
            <?php
            $env = static function (string $name): string {
                $value = getenv($name);
                if ($value === false || $value === '') {
                    throw new RuntimeException("Missing environment variable: " . $name);
                }
                return $value;
            };
            $baseUrl = rtrim($env('BASE_URL'), '/');
            $url = $baseUrl . "/api/v2/trans/queryTrans";
            $headers = ['Accept: application/json'];
            $headers[] = 'Authorization: Bearer ' . $env('ACCESS_TOKEN');
            $params = [
                "merchant_id" => "48290713",
                "merchant_order_no" => "ORDER-20300101-001",
            ];
            $url .= '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);

            $curl = curl_init($url);
            curl_setopt_array($curl, [
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
            ]);
            $response = curl_exec($curl);
            if ($response === false) {
                $error = curl_error($curl);
                curl_close($curl);
                throw new RuntimeException($error);
            }
            curl_close($curl);
            echo $response, PHP_EOL;
        - lang: Go
          label: 按 BillBuddy 交易单号查询
          source: |
            package main

            import (
                "fmt"
                "io"
                "net/http"
                "net/url"
                "os"
                "strings"
                "time"
            )

            func mustEnv(name string) string {
                value := os.Getenv(name)
                if value == "" { panic("Missing environment variable: " + name) }
                return value
            }

            func main() {
                baseURL := strings.TrimRight(mustEnv("BASE_URL"), "/")
                endpoint := baseURL + "/api/v2/trans/queryTrans"
                params := url.Values{}
                params.Set("merchant_id", "48290713")
                params.Set("order_number", "b1893452400000741")
                endpoint += "?" + params.Encode()
                req, err := http.NewRequest("GET", endpoint, nil)
                if err != nil { panic(err) }
                req.Header.Set("Accept", "application/json")
                req.Header.Set("Authorization", "Bearer " + mustEnv("ACCESS_TOKEN"))
                client := &http.Client{Timeout: 30 * time.Second}
                response, err := client.Do(req)
                if err != nil { panic(err) }
                defer response.Body.Close()
                result, err := io.ReadAll(response.Body)
                if err != nil { panic(err) }
                fmt.Println(string(result))
            }
        - lang: Go
          label: 按第三方订单凭证查询
          source: |
            package main

            import (
                "fmt"
                "io"
                "net/http"
                "net/url"
                "os"
                "strings"
                "time"
            )

            func mustEnv(name string) string {
                value := os.Getenv(name)
                if value == "" { panic("Missing environment variable: " + name) }
                return value
            }

            func main() {
                baseURL := strings.TrimRight(mustEnv("BASE_URL"), "/")
                endpoint := baseURL + "/api/v2/trans/queryTrans"
                params := url.Values{}
                params.Set("merchant_id", "48290713")
                params.Set("merchant_order_no", "ORDER-20300101-001")
                endpoint += "?" + params.Encode()
                req, err := http.NewRequest("GET", endpoint, nil)
                if err != nil { panic(err) }
                req.Header.Set("Accept", "application/json")
                req.Header.Set("Authorization", "Bearer " + mustEnv("ACCESS_TOKEN"))
                client := &http.Client{Timeout: 30 * time.Second}
                response, err := client.Do(req)
                if err != nil { panic(err) }
                defer response.Body.Close()
                result, err := io.ReadAll(response.Body)
                if err != nil { panic(err) }
                fmt.Println(string(result))
            }
        - lang: Java
          label: 按 BillBuddy 交易单号查询
          source: |
            import java.io.ByteArrayOutputStream;
            import java.net.URI;
            import java.net.URLEncoder;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpResponse;
            import java.nio.charset.StandardCharsets;
            import java.nio.file.Files;
            import java.nio.file.Path;
            import java.time.Duration;
            import java.util.LinkedHashMap;
            import java.util.Map;
            import java.util.UUID;
            import java.util.stream.Collectors;

            public class Example {
                static String requireEnv(String name) {
                    String value = System.getenv(name);
                    if (value == null || value.isEmpty()) {
                        throw new IllegalArgumentException("Missing environment variable: " + name);
                    }
                    return value;
                }

                public static void main(String[] args) throws Exception {
                    String baseUrl = requireEnv("BASE_URL").replaceAll("/+$", "");
                    String endpoint = baseUrl + "/api/v2/trans/queryTrans";
                    Map<String, String> params = new LinkedHashMap<>();
                    params.put("merchant_id", "48290713");
                    params.put("order_number", "b1893452400000741");
                    String encoded = params.entrySet().stream()
                        .map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "="
                            + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
                        .collect(Collectors.joining("&"));
                    endpoint += "?" + encoded;
                    HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(endpoint))
                        .timeout(Duration.ofSeconds(30))
                        .header("Accept", "application/json");
                    builder.header("Authorization", "Bearer " + requireEnv("ACCESS_TOKEN"));
                    HttpRequest request = builder.method("GET", HttpRequest.BodyPublishers.noBody()).build();
                    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
                    HttpResponse<String> response = client.send(request,
                        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                    System.out.println(response.body());
                }
            }
        - lang: Java
          label: 按第三方订单凭证查询
          source: |
            import java.io.ByteArrayOutputStream;
            import java.net.URI;
            import java.net.URLEncoder;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpResponse;
            import java.nio.charset.StandardCharsets;
            import java.nio.file.Files;
            import java.nio.file.Path;
            import java.time.Duration;
            import java.util.LinkedHashMap;
            import java.util.Map;
            import java.util.UUID;
            import java.util.stream.Collectors;

            public class Example {
                static String requireEnv(String name) {
                    String value = System.getenv(name);
                    if (value == null || value.isEmpty()) {
                        throw new IllegalArgumentException("Missing environment variable: " + name);
                    }
                    return value;
                }

                public static void main(String[] args) throws Exception {
                    String baseUrl = requireEnv("BASE_URL").replaceAll("/+$", "");
                    String endpoint = baseUrl + "/api/v2/trans/queryTrans";
                    Map<String, String> params = new LinkedHashMap<>();
                    params.put("merchant_id", "48290713");
                    params.put("merchant_order_no", "ORDER-20300101-001");
                    String encoded = params.entrySet().stream()
                        .map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "="
                            + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
                        .collect(Collectors.joining("&"));
                    endpoint += "?" + encoded;
                    HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(endpoint))
                        .timeout(Duration.ofSeconds(30))
                        .header("Accept", "application/json");
                    builder.header("Authorization", "Bearer " + requireEnv("ACCESS_TOKEN"));
                    HttpRequest request = builder.method("GET", HttpRequest.BodyPublishers.noBody()).build();
                    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
                    HttpResponse<String> response = client.send(request,
                        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                    System.out.println(response.body());
                }
            }
        - lang: Ruby
          label: 按 BillBuddy 交易单号查询
          source: |
            require "net/http"
            require "uri"

            base_url = ENV.fetch("BASE_URL").sub(%r{/+$}, "")
            uri = URI(base_url + "/api/v2/trans/queryTrans")
            params = {
              "merchant_id" => "48290713",
              "order_number" => "b1893452400000741",
            }
            uri.query = URI.encode_www_form(params)
            request = Net::HTTP::Get.new(uri)
            request["Accept"] = "application/json"
            request["Authorization"] = "Bearer " + ENV.fetch("ACCESS_TOKEN")
            http = Net::HTTP.new(uri.host, uri.port)
            http.use_ssl = uri.scheme == "https"
            http.open_timeout = 30
            http.read_timeout = 30
            puts http.request(request).body
        - lang: Ruby
          label: 按第三方订单凭证查询
          source: |
            require "net/http"
            require "uri"

            base_url = ENV.fetch("BASE_URL").sub(%r{/+$}, "")
            uri = URI(base_url + "/api/v2/trans/queryTrans")
            params = {
              "merchant_id" => "48290713",
              "merchant_order_no" => "ORDER-20300101-001",
            }
            uri.query = URI.encode_www_form(params)
            request = Net::HTTP::Get.new(uri)
            request["Accept"] = "application/json"
            request["Authorization"] = "Bearer " + ENV.fetch("ACCESS_TOKEN")
            http = Net::HTTP.new(uri.host, uri.port)
            http.use_ssl = uri.scheme == "https"
            http.open_timeout = 30
            http.read_timeout = 30
            puts http.request(request).body
components:
  schemas:
    TransactionQueryResponse:
      type: object
      properties:
        code:
          type: integer
          description: 查询成功，不代表支付成功。
          enum:
            - 0
        message:
          type: string
          description: 处理结果说明，成功为 ok。
          example: ok
        data:
          $ref: '#/components/schemas/TransactionQueryItem'
      required:
        - code
        - message
        - data
      additionalProperties: false
    PublicApiError:
      type: object
      properties:
        code:
          type: integer
          description: 业务或认证失败为 1；请求参数或文件属性校验失败为 400。
          enum:
            - 1
            - 400
        message:
          type: string
          description: 错误原因，实际文案随失败原因变化。
        data:
          description: 业务及参数错误为空对象；认证失败为空数组。
          oneOf:
            - type: object
              additionalProperties: false
            - type: array
              items: {}
              maxItems: 0
      required:
        - code
        - message
        - data
      additionalProperties: false
    TransactionQueryItem:
      type: object
      properties:
        business_id:
          type: string
          description: 交易所属商户的标识，由 OAuth 凭据确定。
        merchant_id:
          type: string
          description: 交易所属业务的标识；对应查询请求中的 merchant_id，或交易列表的 Mid。
        order_number:
          type: string
          description: 当前交易的 BillBuddy 交易单号。
        merchant_order_no:
          type: string
          description: 当前交易的第三方订单凭证；无值时为空字符串。
        trans_type:
          type: integer
          description: 交易类型：1 Payment（支付）、2 Refund（退款）、3 Dispute（争议）；未知类型保留数值。
        trans_type_text:
          type: string
          description: 交易类型名称：Payment、Refund、Dispute；未知类型为 Unknown。
        original_order_number:
          type: string
          description: 退款或争议对应的原交易单号；没有可访问的原交易时为 null。
          nullable: true
        status:
          type: integer
          description: >-
            交易状态：1 Successful（成功）、2 Failed（失败）、3 Pending（处理中）、4
            Expired（过期）；未知状态保留数值。
        status_text:
          type: string
          description: 状态名称：Successful、Failed、Pending、Expired；未知状态为 Unknown。
        amount:
          type: string
          description: 交易本金，以对应币种的主货币单位表示，固定两位小数。
          pattern: ^-?\d+\.\d{2}$
        currency:
          type: string
          description: 交易本金币种。
        surcharge_amount:
          type: string
          description: 附加费金额，以对应币种的主货币单位表示，固定两位小数。
          pattern: ^-?\d+\.\d{2}$
        surcharge_currency:
          type: string
          description: 附加费币种。
        payment_amount:
          type: string
          description: 支付金额（包含附加费），不代表已经结算或到账，以对应币种的主货币单位表示，固定两位小数。
          pattern: ^-?\d+\.\d{2}$
        payment_currency:
          type: string
          description: 支付币种。
        created_at:
          type: string
          description: 交易创建时间；格式 DD/MM/YYYY HH:mm:ss，无值时为 null。
          nullable: true
        complete_date:
          type: string
          description: 交易完成时间；格式 DD/MM/YYYY HH:mm:ss，无值时为 null。
          nullable: true
        process_date:
          type: string
          description: 预约处理日期；格式 YYYY-MM-DD，无值时为 null。
          nullable: true
        cancelled_at:
          type: string
          description: >-
            取消时间；有值时 result 为 Cancelled，status 仍需独立读取；格式 DD/MM/YYYY
            HH:mm:ss，无值时为 null。
          nullable: true
        expired_at:
          type: string
          description: 到期时间；是否已经过期以交易状态为准；格式 DD/MM/YYYY HH:mm:ss，无值时为 null。
          nullable: true
        payment_method:
          type: object
          properties:
            type:
              type: integer
              description: 支付方式类型：1 Bank Account、2 Credit、3 BPAY、4 WeChat；未知类型保留数值。
            type_text:
              type: string
              description: 支付方式名称，未知类型为 Unknown。
            card_brand:
              type: string
              description: 卡品牌，如 Visa、MasterCard、American Express；非卡支付或未知品牌为 null。
              nullable: true
            wallet_type:
              type: string
              description: 钱包类型 APPLE_PAY 或 GOOGLE_PAY；不适用或无法识别时为 null。
              nullable: true
              enum:
                - APPLE_PAY
                - GOOGLE_PAY
                - null
          required:
            - type
            - type_text
            - card_brand
            - wallet_type
          additionalProperties: false
          nullable: true
          description: 本笔交易使用的支付方式摘要；无可用信息时整个对象为 null。
        result:
          type: string
          description: 结果说明；已取消时为 Cancelled，其余为交易状态名称。
          enum:
            - Successful
            - Failed
            - Pending
            - Expired
            - Cancelled
            - Unknown
      required:
        - business_id
        - merchant_id
        - order_number
        - merchant_order_no
        - trans_type
        - trans_type_text
        - original_order_number
        - status
        - status_text
        - amount
        - currency
        - surcharge_amount
        - surcharge_currency
        - payment_amount
        - payment_currency
        - created_at
        - complete_date
        - process_date
        - cancelled_at
        - expired_at
        - payment_method
        - result
      additionalProperties: false
      description: 响应数据。
  securitySchemes:
    oauth2:
      type: oauth2
      description: OAuth2 client_credentials 授权。access_token 到期后重新获取。
      flows:
        clientCredentials:
          tokenUrl: /oauth/token
          scopes: {}

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.