Pay an Invoice

Process payments for invoices with idempotency support, split funding capabilities, and automatic status updates through the Stax API.

Process a payment for an existing invoice and keep its payments, refunds, and voids grouped under the same invoice.

Audience: Developers using the Stax API.

Submit an invoice payment

  1. Prepare a merchant API key for bearer-token authentication. Use an invoice belonging to that merchant.
  2. Copy the invoice's id from a Get All Invoices response. Obtain the saved payment method's id from your integration; if Get an Invoice returns a non-null payment_method, its id identifies that payment method. Confirm that it is the method you intend to charge.
  3. Generate and save an idempotency ID (a unique value that lets you retry the same payment without creating a duplicate). Use Python 3's python -c 'import uuid; print(uuid.uuid4())', then keep that value with your payment record. Reuse it for retries of this payment; generate a new value only for a separate payment.
  4. Save the example below as pay_invoice.py and run python pay_invoice.py. Enter your credentials and IDs when prompted, then confirm the payment. The example uses Python's standard library, a 30-second timeout, and no automatic retries.

This example submits a payment to the production API. Confirm the invoice and payment method before typing PAY. The UUIDs shown in the prompts match the documented response format; they are examples, not values to submit unchanged.

import getpass
import json
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen

api_key = getpass.getpass("Merchant API key: ").strip()
# Copy id from an invoice in the GET /invoice response's data array.
example_invoice_id = "990117ce-b31f-4e76-b027-52e90b32e465"
invoice_id = input(f"Invoice ID (example: {example_invoice_id}): ").strip()
# If GET /invoice returns no payment method ID, use your saved method's id.
# GET /invoice for a list is distinct from retrieving one invoice by its ID.
example_method_id = "f27192f5-c170-451c-a45e-397acb870b15"
payment_method_id = input(
    f"Saved payment method ID (example: {example_method_id}): "
).strip()
# Reuse this stored value if the response is lost; a new value risks a new charge.
idempotency_id = input("Saved idempotency ID for this payment: ").strip()

if not all((api_key, invoice_id, payment_method_id, idempotency_id)):
    sys.exit("Enter the API key, invoice ID, payment method ID, and idempotency ID.")
if len(idempotency_id) > 255:
    sys.exit("The idempotency ID must be no longer than 255 characters.")

print(f"Invoice: {invoice_id}; payment method: {payment_method_id}")
if input("Type PAY to submit this payment: ").strip() != "PAY":
    sys.exit("Cancelled; no payment request was sent.")

query = urlencode({
    "payment_method_id": payment_method_id,
    "idempotency_id": idempotency_id,
})
url = (
    "https://apiprod.fattlabs.com/invoice/"
    + quote(invoice_id, safe="")
    + "/pay?"
    + query
)
request = Request(
    url,
    data=b"",
    headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
    method="POST",
)

try:
    with urlopen(request, timeout=30) as response:
        invoice = json.load(response)
    if not isinstance(invoice, dict) or not invoice.get("id"):
        sys.exit("Unexpected response. Check the invoice before retrying with the same idempotency ID.")
    print(json.dumps(invoice, indent=2))
    if invoice.get("payment_attempt_failed"):
        sys.exit(f"Payment failed: {invoice.get('payment_attempt_message') or 'Check the invoice response.'}")
    if invoice.get("status") == "PAID":
        print("Payment applied; invoice status is PAID.")
    elif invoice.get("status") == "PARTIALLY APPLIED":
        print(f"Partial payment applied; balance due: {invoice.get('balance_due')}")
    else:
        sys.exit("Review the invoice status before treating the payment as successful.")
except HTTPError as error:
    print(f"Request failed: HTTP {error.code}", file=sys.stderr)
    print(error.read().decode("utf-8", errors="replace"), file=sys.stderr)
    sys.exit("Check the invoice before retrying; reuse the same idempotency ID for this payment.")
except (URLError, TimeoutError, OSError) as error:
    sys.exit(f"Connection failed: {error}. The payment outcome may be unknown; check the invoice before retrying with the same idempotency ID.")
except (ValueError, UnicodeError) as error:
    sys.exit(f"Could not decode the response: {error}. Check the invoice before retrying with the same idempotency ID.")

A successful full payment returns HTTP 200 and an invoice with status set to PAID. The documented response includes these fields (other fields omitted):

{
  "id": "990117ce-b31f-4e76-b027-52e90b32e465",
  "status": "PAID",
  "payment_attempt_failed": false,
  "balance_due": 0,
  "total_paid": 10
}

The script then prints Payment applied; invoice status is PAID. For an authentication failure, check that the API key belongs to the invoice's merchant. For HTTP 422, inspect the returned validation messages and verify the payment method ID and parameter types.


Key Features

Direct Invoice Linking

Links payments directly to an invoice and updates the invoice status automatically.

Idempotency Support

Supports idempotency (retrying the same request without creating duplicate payments) with unique identifiers.

Split Funding

Handles advanced payment allocation with Split Funding across multiple accounts.

Immutable Records

Generates immutable payment records for transparency and consistency.


Usage Guidelines

Definition: Idempotency ensures that repeated requests with the same idempotency_id produce the same result without creating duplicate payments.

How It Works:

  • Include a unique idempotency_id string in the query string, as shown in the Python example above.
  • If the same idempotency_id is sent in a subsequent request, the API will recognize it as a duplicate and return the original payment response without processing a new transaction.

Best Practices:

  • Generate and store a unique idempotency_id before submitting a new payment. Follow the UUID-generation step above, and reuse the stored value when retrying that payment.
  • Ensure the idempotency_id is no longer than 255 characters.

Response Structure

CodeResponseReason
200SuccessPayment was successfully applied to the invoice.
400Bad RequestInvalid payment details or invoice ID.
401UnauthorizedAuthentication failed.
422Unprocessable EntitySplit funding allocation does not match the invoice.
500Internal Server ErrorUnexpected server error.

Important Considerations

Duplicate Payment Prevention

Avoid Duplicate Payments: Reuse the same idempotency_id when retrying a payment, including after a timeout or lost response. Generate a new identifier only for a separate payment, not for another attempt to submit the same payment.

Split Funding Requirements

Split Funding: Merchant accounts must be enrolled in the Split Funding feature to allocate payments across multiple accounts. Contact support if this feature is needed.

Payment Methods

Manual Payments: Use Mark an Invoice Paid in Cash or Check to record cash, check, or gift card payments received outside Stax. For example, POST /invoice/990117ce-b31f-4e76-b027-52e90b32e465/pay/cash records cash against the example invoice; replace the UUID with your invoice's id from the invoice response. The supported method values are cash, check, and giftcard.

Path Params
string
required
Query Params
float
boolean
Defaults to false
string
string
string
Responses

Language
Credentials
Bearer
JWT
LoadingLoading…
Response
Click Try It! to start a request and see the response here! Or choose an example:
application/json