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

# Obtain an OAuth access token

> Obtains an access token using OAuth2 client_credentials. Client credentials must be approved, enabled, not revoked and not expired. If an IP allowlist is configured, business requests must originate from an approved IP. Use the Client Secret and access_token only on the merchant server. Request a new token when it expires; no refresh_token is provided. Token requests are limited to 60 per minute; exceeding the limit returns HTTP 429.



## OpenAPI

````yaml /openapi/billbuddy-v2-openapi.en.yaml post /oauth/token
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:
  /oauth/token:
    post:
      tags:
        - Authentication
      summary: Obtain an OAuth access token
      description: >-
        Obtains an access token using OAuth2 client_credentials. Client
        credentials must be approved, enabled, not revoked and not expired. If
        an IP allowlist is configured, business requests must originate from an
        approved IP. Use the Client Secret and access_token only on the merchant
        server. Request a new token when it expires; no refresh_token is
        provided. Token requests are limited to 60 per minute; exceeding the
        limit returns HTTP 429.
      operationId: oauthClientCredentialsToken
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/OAuthTokenRequest'
            example:
              grant_type: client_credentials
              client_id: 8a6bf2d9-47c1-4e85-92b3-6d1a7c084f52
              client_secret: d9K7wR2mN8vT4xQ6aH3cF5jL1sB0eG9pY7uV2zC4
      responses:
        '200':
          description: Token issued successfully.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OAuthTokenResponse'
              example:
                token_type: Bearer
                expires_in: 7200
                access_token: >-
                  eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI4YTZiZjJkOS00N2MxLTRlODUtOTJiMy02ZDFhN2MwODRmNTIiLCJqdGkiOiJhZGRiNDgzNDkxMGM2MThjZmJiNGRhMTJhZDMwNWEwNGU3ZmZiNWUzMTE3YjI3YmQwNTVlMjk5ZTgzOTU1ZTkyIiwiaWF0IjoxODkzNDUyNDAwLCJuYmYiOjE4OTM0NTI0MDAsImV4cCI6MTg5MzQ1OTYwMCwic3ViIjoiOGE2YmYyZDktNDdjMS00ZTg1LTkyYjMtNmQxYTdjMDg0ZjUyIiwic2NvcGVzIjpbXX0.dLrN3edou1KGfN5a2kbfDRtGA-iM4meEfwlMTPc1UHv1wGrv70ue8Mb3UU0TYxbZHxK-kHHUVH9aWwItbsyYBkou3Sgr5NAwejvuxSOmQZHk4dT-Uw982pelDqBrBmJV5qZ5qY7qeGDc0Fz_0ymre50BLOd2d3MsLj-INdwjNNIF4fr2AG9M6mDK8pEqGMNMqT20GGVEQ1YJZGwpy-XiPp-6sVS3qOjyineqTK_hN3N0QXykoEM4iFGK_wQdc681B8tfXJRpcQksNt4A1pM2G5nUdnBC-ahByGYUaij4JAkxR_LpnXoR1xQbd-j4wj8cG78WAPdJTzZcIFPRU0Gmjw
        '400':
          description: Missing parameters, invalid grant type or invalid scope.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OAuthError'
              example:
                error: invalid_request
                error_description: >-
                  The request is missing a required parameter, includes an
                  invalid parameter value, includes a parameter more than once,
                  or is otherwise malformed.
                hint: Check the `grant_type` parameter
        '401':
          description: >-
            Client authentication failed or the client is unavailable for
            business requests.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OAuthError'
              example:
                error: invalid_client
                error_description: Client authentication failed
        '429':
          description: >-
            Token request rate limit exceeded: at most 60 requests per minute.
            Wait as directed by Retry-After before retrying.
          headers:
            Retry-After:
              description: Seconds to wait before retrying.
              schema:
                type: integer
          content:
            application/json:
              schema:
                type: object
                description: Rate limit response.
                properties:
                  message:
                    type: string
                    description: Rate limit message.
              example:
                message: Too Many Attempts.
      security: []
      x-codeSamples:
        - lang: Shell
          label: Client credentials
          source: |-
            curl -X POST "${BASE_URL}/oauth/token" \
              -H "Accept: application/json" \
              -H "Content-Type: application/x-www-form-urlencoded" \
              --data-urlencode "grant_type=client_credentials" \
              --data-urlencode "client_id=${CLIENT_ID}" \
              --data-urlencode "client_secret=${CLIENT_SECRET}"
        - lang: Python
          label: Client credentials
          source: >
            import json

            import os

            import urllib.parse

            import urllib.request


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

            url = base_url + "/oauth/token"

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

            params = {
                "grant_type": "client_credentials",
                "client_id": os.environ["CLIENT_ID"],
                "client_secret": os.environ["CLIENT_SECRET"],
            }

            body = urllib.parse.urlencode(params).encode("utf-8")

            headers["Content-Type"] = "application/x-www-form-urlencoded"


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

            with urllib.request.urlopen(request, timeout=30) as response:
                print(response.read().decode("utf-8"))
        - lang: JavaScript
          label: Client credentials
          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 + "/oauth/token");
            const headers = { Accept: "application/json" };
            const params = new URLSearchParams({
              "grant_type": "client_credentials",
              "client_id": env("CLIENT_ID"),
              "client_secret": env("CLIENT_SECRET"),
            });
            const body = params;
            headers["Content-Type"] = "application/x-www-form-urlencoded";

            const response = await fetch(url, {
              method: "POST",
              headers,
              body,
              signal: AbortSignal.timeout(30_000),
            });
            console.log(await response.text());
        - lang: PHP
          label: Client credentials
          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 . "/oauth/token";
            $headers = ['Accept: application/json'];
            $params = [
                "grant_type" => "client_credentials",
                "client_id" => $env("CLIENT_ID"),
                "client_secret" => $env("CLIENT_SECRET"),
            ];
            $body = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
            $headers[] = 'Content-Type: application/x-www-form-urlencoded';

            $curl = curl_init($url);
            curl_setopt_array($curl, [
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_POSTFIELDS => $body,
            ]);
            $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: Client credentials
          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 + "/oauth/token"
                params := url.Values{}
                params.Set("grant_type", "client_credentials")
                params.Set("client_id", mustEnv("CLIENT_ID"))
                params.Set("client_secret", mustEnv("CLIENT_SECRET"))
                body := strings.NewReader(params.Encode())
                req, err := http.NewRequest("POST", endpoint, body)
                if err != nil { panic(err) }
                req.Header.Set("Accept", "application/json")
                req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
                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: Client credentials
          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 + "/oauth/token";
                    Map<String, String> params = new LinkedHashMap<>();
                    params.put("grant_type", "client_credentials");
                    params.put("client_id", requireEnv("CLIENT_ID"));
                    params.put("client_secret", requireEnv("CLIENT_SECRET"));
                    String encoded = params.entrySet().stream()
                        .map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "="
                            + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
                        .collect(Collectors.joining("&"));
                    HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(endpoint))
                        .timeout(Duration.ofSeconds(30))
                        .header("Accept", "application/json");
                    builder.header("Content-Type", "application/x-www-form-urlencoded");
                    HttpRequest request = builder.method("POST", HttpRequest.BodyPublishers.ofString(encoded, StandardCharsets.UTF_8)).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: Client credentials
          source: |
            require "net/http"
            require "uri"

            base_url = ENV.fetch("BASE_URL").sub(%r{/+$}, "")
            uri = URI(base_url + "/oauth/token")
            params = {
              "grant_type" => "client_credentials",
              "client_id" => ENV.fetch("CLIENT_ID"),
              "client_secret" => ENV.fetch("CLIENT_SECRET"),
            }
            request = Net::HTTP::Post.new(uri)
            request["Accept"] = "application/json"
            request.set_form_data(params)
            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:
    OAuthTokenRequest:
      type: object
      description: OAuth form.
      properties:
        grant_type:
          type: string
          description: Grant type. Always client_credentials.
          enum:
            - client_credentials
          minLength: 1
        client_id:
          type: string
          description: OAuth Client ID assigned by BillBuddy. Submit as a string.
          minLength: 1
        client_secret:
          type: string
          description: OAuth Client Secret. Store only on the merchant server.
          minLength: 1
        scope:
          type: string
          description: Optional space-separated scopes. Usually omitted or an empty string.
          default: ''
      required:
        - grant_type
        - client_id
        - client_secret
    OAuthTokenResponse:
      type: object
      description: >-
        Standard OAuth success response. Does not contain code/message/data and
        does not return refresh_token.
      properties:
        token_type:
          type: string
          description: Always Bearer.
          enum:
            - Bearer
        expires_in:
          type: integer
          description: >-
            Token lifetime in seconds. Use the actual response; the example is
            7200 seconds.
        access_token:
          type: string
          description: >-
            OAuth access_token. Include it in the Authorization: Bearer header
            on subsequent requests.
      required:
        - token_type
        - expires_in
        - access_token
    OAuthError:
      type: object
      description: Standard OAuth error without the business response envelope.
      properties:
        error:
          type: string
          description: OAuth error code.
        error_description:
          type: string
          description: Error description.
        hint:
          type: string
          description: Optional troubleshooting hint.
        message:
          type: string
          description: Optional error message.
      required:
        - error
        - error_description
  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.