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

# Query a transaction

> Look up the current status of an existing payment, refund or dispute. Use an OAuth2 Bearer token; no request signature is required. Supply at least one of order_number and merchant_order_no. If both are provided, they must identify the same transaction. If a third-party reference matches multiple transactions, code=1 is returned; provide the BillBuddy transaction number.

code=0 means the lookup succeeded; use data.status to assess the payment outcome. For a cancelled transaction, result is Cancelled while status is still returned separately. Amounts are two-decimal strings in major currency units. Times use Australia/Sydney, including daylight saving; field descriptions specify formats. This lookup does not initiate or repeat a payment. If no transaction is found, verify the order and processing status before considering another payment.

merchant_id is an optional business filter. Omit it or leave it empty to search all businesses of the authenticated merchant; supply it to restrict the lookup to that business. If a reference is reused across businesses, use merchant_id to narrow the search or provide order_number to identify the transaction uniquely.



## OpenAPI

````yaml /openapi/billbuddy-v2-openapi.en.yaml get /api/v2/trans/queryTrans
openapi: 3.0.3
info:
  title: BillBuddy API Integration Guide
  version: 2.0.0
  description: >
    BillBuddy API integration guide. It covers authentication, transaction and
    subscription endpoints called by third-party servers. Request and response
    examples contain complete fictional business data and tokens generated
    offline; they cannot authenticate or initiate real transactions.


    ## Getting started

    1. Obtain your Client ID, Client Secret, merchant identifier and business
    identifier from BillBuddy. If an IP allowlist applies, send requests from an
    approved fixed outbound IP address.

    2. Obtain an access_token through POST /oauth/token. Business requests
    require Authorization: Bearer {access_token} and Accept: application/json.
    Use Content-Type: application/json for JSON requests and form encoding for
    token requests.

    3. Call the payment or subscription endpoints as needed. Customers open the
    hosted activation page through activation_url. Store the Client Secret only
    on your server.


    ## Identifiers and amounts

    OAuth credentials identify the merchant; business_id is not a request
    parameter. Endpoints that require a business use merchant_id. For
    single-transaction and batch-result lookups, merchant_id is optional; omit
    it or leave it empty to search all businesses of the authenticated merchant.
    The transaction list uses optional, case-sensitive Mid; omit it to query all
    businesses belonging to the authenticated merchant. A requested business
    must belong to that merchant. Read response identifiers according to each
    endpoint's field definitions.

    TXT file amounts, amount_cents and declared_total_amount_cents use cents.
    Other amounts use major currency units with at most two decimal places:
    10.50 means AUD 10.50. Use strings for bank account numbers, card numbers,
    months, years and postcodes to preserve leading zeros.


    ## Success and failure

    Business JSON responses use code=0 for success and code=1 for ordinary
    failures. Transaction and subscription validation failures usually return
    code=400 and data={} with HTTP 200. V2 business endpoint authentication
    failures use code=1. A missing, malformed or inaccessible business
    merchant_id for plan/list return code=1. HTTP 429 indicates a rate limit.
    The OAuth endpoint uses standard OAuth responses with HTTP 200/400/401/429.

    code=0 means the API request was processed successfully; assess the payment
    outcome separately. Batch accepted means the request was accepted for
    asynchronous processing. Bank Pending, scheduled Pending and outstanding 3DS
    authentication do not indicate payment success. Transactions, DDR
    subscriptions and payment schedules use different status enumerations; refer
    to their field definitions.


    ## Dates and frequencies

    Use YYYY-MM-DD for request dates. Today and tomorrow are evaluated in
    Australia/Sydney, including daylight saving time. Scheduled cancellations
    also use Australia/Sydney: cancellation must occur strictly before 08:15 on
    the processing date; it is no longer permitted at that time. Payment
    complete_date and checkout expires_at use DD/MM/YYYY HH:mm:ss. Refer to
    individual fields for other formats.

    Standard RRULE examples: 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. Weekday abbreviations are
    MO/TU/WE/TH/FR/SA/SU. Weekly/Monthly rules without a specific debit day
    derive it from the start date. A single BYDAY=SA or SU is treated as Monday;
    a weekend start date without an explicit debit day is also treated as
    Monday. A single BYMONTHDAY=29/30/31 falls on the last day of shorter
    months; BYMONTHDAY=-1 means the last day of the month. All rules must be
    valid RRULE expressions.

    For a nonstandard frequency such as every 10 days, provide process_type=12,
    custom_cycle_type=1, custom_cycle=10 and
    day_of_debit=FREQ=DAILY;INTERVAL=10. Units 1/2/3/4 correspond to
    DAILY/WEEKLY/MONTHLY/YEARLY. The minimum interval is 5 for days and 1 for
    other units. INTERVAL must equal custom_cycle. Quarterly, half-yearly and
    yearly schedules also require day_of_debit_dtstart. Its complete date must
    be strictly after the start_date of the same schedule segment and within one
    billing cycle after it. The first actual debit date for createSchedule
    depends on the DDR start date, debit frequency and the requirement that it
    be no earlier than tomorrow.


    ## Using examples

    Schemas define types, nullability, lengths, enumerations and numeric ranges.
    Field descriptions define conditional requirements, dates and business
    restrictions. Use both together. Set BASE_URL, ACCESS_TOKEN, CLIENT_ID and
    CLIENT_SECRET before running curl examples. BillBuddy provides the actual
    test and production domains. Replace example customers, orders, cards,
    accounts and dates with values permitted in your test environment and
    satisfying the date restrictions.


    ## Hosted subscription integration

    Call POST /api/v2/subscription/create, then use the complete activation_url
    unchanged for a browser redirect or an iframe src. Alternatively, use
    activation_html as the iframe srcdoc. Customers enter payment information,
    authorize debits and activate the subscription on the BillBuddy-hosted page.
    Use the full returned URL; do not construct it yourself or parse its
    credentials. Keep the Client Secret and access_token on your server; never
    include them in iframe URLs or page contents.


    Recurring and By agreement subscriptions must be activated before
    start_date. One-off-only subscriptions must be submitted for activation
    within 30 days of creation. An accessible page does not guarantee submission
    is still permitted; the activation response is authoritative.


    ## Example data conventions

    Example merchants, customers, orders, payment tokens, session links and
    OAuth credentials are fictional and cannot be used for real requests. Card
    numbers are standard test card numbers; bank accounts are fictional. Email
    addresses use the reserved example.com domain, and phone numbers use
    Australian numbers reserved for examples. Replace BASE_URL, ACCESS_TOKEN,
    CLIENT_ID and CLIENT_SECRET with actual values from your approved test
    environment. Empty strings, null, empty arrays, 0 and false represent
    meaningful API states in some examples and must not be replaced
    indiscriminately.

    Payment response signatures are calculated offline according to the signing
    rules for each payment scenario, using the public demo key
    bb_docs_demo_signing_key_2030. The html field is excluded for responses
    awaiting 3DS authentication. This key is for documentation only and cannot
    sign or authenticate real requests.


    ## TXT batch transactions

    Upload fixed-width TXT files using multipart/form-data. File amounts,
    amount_cents and declared_total_amount_cents use cents, excluding
    surcharges; see “Upload a TXT transaction file” for the format and example
    file. Upload success only confirms acceptance. Retain batch_id and
    file_identifier and use the batch result endpoint to check individual
    outcomes. Batch completed does not mean every payment succeeded. Use OAuth
    credentials for the same merchant to query results. merchant_id is optional;
    when supplied, it must match the business identifier in the original upload.
    Response identifiers follow the definitions for each endpoint.


    ## Request examples by programming language

    Examples are provided in cURL, Python, JavaScript, PHP, Go, Java and Ruby,
    with the same business scenarios available in each language. Each example
    preserves the parameters and types from its corresponding cURL scenario.


    Requirements: cURL; Python 3.9+ (standard library); JavaScript with Node.js
    18+, saved as an .mjs file; PHP 8+ with the cURL extension; Go 1.20+; Java
    11+ (save the Example class as Example.java); Ruby 3+ (standard library).


    Set BASE_URL before running examples. Business endpoints also require
    ACCESS_TOKEN; token requests require CLIENT_ID and CLIENT_SECRET. BASE_URL
    is the API root without /api/v2. TXT upload examples read payments.txt from
    the current directory. Replace fictional values with approved test data and
    assess the response code and business status separately.
servers:
  - url: https://staging-api.billbuddyhq.com
    description: Staging environment
security:
  - oauth2: []
tags:
  - name: Authentication
    description: OAuth2 Client Credentials。
  - name: Transactions
    description: Single payments, batch payments and scheduled payment cancellations.
  - name: Subscriptions
    description: >-
      Subscription templates, hosted subscription creation, DDR creation and
      activation, and payment schedule submission.
paths:
  /api/v2/trans/queryTrans:
    get:
      tags:
        - Transactions
      summary: Query a transaction
      description: >-
        Look up the current status of an existing payment, refund or dispute.
        Use an OAuth2 Bearer token; no request signature is required. Supply at
        least one of order_number and merchant_order_no. If both are provided,
        they must identify the same transaction. If a third-party reference
        matches multiple transactions, code=1 is returned; provide the BillBuddy
        transaction number.


        code=0 means the lookup succeeded; use data.status to assess the payment
        outcome. For a cancelled transaction, result is Cancelled while status
        is still returned separately. Amounts are two-decimal strings in major
        currency units. Times use Australia/Sydney, including daylight saving;
        field descriptions specify formats. This lookup does not initiate or
        repeat a payment. If no transaction is found, verify the order and
        processing status before considering another payment.


        merchant_id is an optional business filter. Omit it or leave it empty to
        search all businesses of the authenticated merchant; supply it to
        restrict the lookup to that business. If a reference is reused across
        businesses, use merchant_id to narrow the search or provide order_number
        to identify the transaction uniquely.
      operationId: v2QueryTransaction
      parameters:
        - name: merchant_id
          in: query
          required: false
          description: >-
            Optional business identifier, up to 20 characters. When supplied, it
            must belong to the authenticated merchant. Omit it or leave it empty
            to locate a transaction across all businesses of that merchant.
          schema:
            type: string
            maxLength: 20
            nullable: true
          example: '48290713'
        - name: order_number
          in: query
          required: false
          description: >-
            BillBuddy transaction number; supply this or merchant_order_no. Both
            must match the same transaction when supplied together.
          schema:
            type: string
            maxLength: 60
            nullable: true
          example: b1893452400000741
        - name: merchant_order_no
          in: query
          required: false
          description: >-
            Third-party order reference; supply this or order_number. If
            multiple transactions match, provide order_number.
          schema:
            type: string
            maxLength: 64
            nullable: true
          example: ORDER-20300101-001
      responses:
        '200':
          description: >-
            HTTP 200. code=0 means the lookup succeeded; code=1 indicates a
            business or authentication error; code=400 indicates invalid query
            parameters.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/TransactionQueryResponse'
                  - $ref: '#/components/schemas/PublicApiError'
              examples:
                successful:
                  summary: Successful payment
                  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: Payment 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: Payment 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: Transaction 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: Transaction 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: Reference matches multiple transactions
                  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 not found
                  value:
                    code: 1
                    message: Business Merchant not found
                    data: {}
                validationError:
                  summary: Invalid query parameters
                  value:
                    code: 400
                    message: >-
                      The order number field is required when merchant order no
                      is not present.
                    data: {}
                internalError:
                  summary: Query unavailable
                  value:
                    code: 1
                    message: Transaction query failed due to internal error
                    data: {}
                unauthenticated:
                  summary: Authentication failed
                  value:
                    code: 1
                    message: Unauthenticated, invalid or expired access token
                    data: []
                refund:
                  summary: Refund transaction
                  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: Payment method information unavailable
                  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 payment
                  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: Dispute transaction
                  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: >-
            Rate limit exceeded. API requests share a limit of 120 requests per
            minute, normally counted by source IP; this is not a separate
            allowance for each endpoint. Wait for the seconds specified by
            Retry-After.
      security:
        - oauth2: []
      x-codeSamples:
        - lang: Shell
          label: Look up by BillBuddy transaction number
          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: Look up by third-party order reference
          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: Look up by BillBuddy transaction number
          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: Look up by third-party order reference
          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: Look up by BillBuddy transaction number
          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: Look up by third-party order reference
          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: Look up by BillBuddy transaction number
          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: Look up by third-party order reference
          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: Look up by BillBuddy transaction number
          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: Look up by third-party order reference
          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: Look up by BillBuddy transaction number
          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: Look up by third-party order reference
          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: Look up by BillBuddy transaction number
          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: Look up by third-party order reference
          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: Lookup succeeded; this does not confirm payment success.
          enum:
            - 0
        message:
          type: string
          description: Result message; ok on success.
          example: ok
        data:
          $ref: '#/components/schemas/TransactionQueryItem'
      required:
        - code
        - message
        - data
      additionalProperties: false
    PublicApiError:
      type: object
      properties:
        code:
          type: integer
          description: >-
            1 for business or authentication errors; 400 for parameter or file
            property validation errors.
          enum:
            - 1
            - 400
        message:
          type: string
          description: Error reason; exact wording depends on the failure.
        data:
          description: >-
            Empty object for business or validation errors; empty array for
            authentication failures.
          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: >-
            Identifier of the transaction merchant, identified by the OAuth
            credentials.
        merchant_id:
          type: string
          description: >-
            Identifier of the transaction business; corresponds to merchant_id
            on single-transaction lookup or Mid on the transaction list.
        order_number:
          type: string
          description: BillBuddy transaction number for this transaction.
        merchant_order_no:
          type: string
          description: Third-party order reference for this transaction; empty when absent.
        trans_type:
          type: integer
          description: >-
            Transaction type: 1 Payment, 2 Refund, 3 Dispute; unrecognized
            numeric values may be returned.
        trans_type_text:
          type: string
          description: 'Transaction type label: Payment, Refund, Dispute, or Unknown.'
        original_order_number:
          type: string
          description: >-
            Original transaction number for a refund or dispute; null when no
            original transaction is available.
          nullable: true
        status:
          type: integer
          description: >-
            Transaction status: 1 Successful, 2 Failed, 3 Pending, 4 Expired;
            unrecognized numeric values may be returned.
        status_text:
          type: string
          description: 'Status label: Successful, Failed, Pending, Expired, or Unknown.'
        amount:
          type: string
          description: >-
            Base transaction amount in major units of the corresponding
            currency, with exactly two decimal places.
          pattern: ^-?\d+\.\d{2}$
        currency:
          type: string
          description: Base transaction currency.
        surcharge_amount:
          type: string
          description: >-
            Surcharge amount in major units of the corresponding currency, with
            exactly two decimal places.
          pattern: ^-?\d+\.\d{2}$
        surcharge_currency:
          type: string
          description: Surcharge currency.
        payment_amount:
          type: string
          description: >-
            Payment amount including surcharge; this does not confirm settlement
            or payout in major units of the corresponding currency, with exactly
            two decimal places.
          pattern: ^-?\d+\.\d{2}$
        payment_currency:
          type: string
          description: Payment currency.
        created_at:
          type: string
          description: >-
            Transaction creation time; format DD/MM/YYYY HH:mm:ss; null when
            absent.
          nullable: true
        complete_date:
          type: string
          description: >-
            Transaction completion time; format DD/MM/YYYY HH:mm:ss; null when
            absent.
          nullable: true
        process_date:
          type: string
          description: Scheduled processing date; format YYYY-MM-DD; null when absent.
          nullable: true
        cancelled_at:
          type: string
          description: >-
            Cancellation time; when present, result is Cancelled and status must
            still be read separately; format DD/MM/YYYY HH:mm:ss; null when
            absent.
          nullable: true
        expired_at:
          type: string
          description: >-
            Expiry time; use transaction status to determine whether it has
            expired; format DD/MM/YYYY HH:mm:ss; null when absent.
          nullable: true
        payment_method:
          type: object
          properties:
            type:
              type: integer
              description: >-
                Payment method: 1 Bank Account, 2 Credit, 3 BPAY, 4 WeChat;
                unrecognized numeric values may be returned.
            type_text:
              type: string
              description: Payment method label, or Unknown.
            card_brand:
              type: string
              description: >-
                Card brand, such as Visa, MasterCard or American Express; null
                for non-card methods or unknown brands.
              nullable: true
            wallet_type:
              type: string
              description: >-
                APPLE_PAY or GOOGLE_PAY; null when not applicable or
                unrecognized.
              nullable: true
              enum:
                - APPLE_PAY
                - GOOGLE_PAY
                - null
          required:
            - type
            - type_text
            - card_brand
            - wallet_type
          additionalProperties: false
          nullable: true
          description: >-
            Payment method summary for this transaction; the entire object is
            null when unavailable.
        result:
          type: string
          description: >-
            Result label; Cancelled takes precedence for cancelled transactions,
            otherwise the transaction status label.
          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: Response data.
  securitySchemes:
    oauth2:
      type: oauth2
      description: >-
        OAuth2 client_credentials authorization. Obtain a new access_token when
        it expires.
      flows:
        clientCredentials:
          tokenUrl: /oauth/token
          scopes: {}

````

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