Payments

Use the Payments API to integrate charges, pre-authorizations, captures, and refunds into your application as a developer working with one-time payments or recurring billing.


Key Concepts and Features

Charge a Payment Method

Charge a saved payment method under the merchant's account. A charge authorizes the payment (reserves funds on the customer's card) and captures it (submits the authorized amount for processing) in a single transaction.

Send a charge request

  1. Install Python 3 to run the example without additional packages.
  2. Set the STAX_API_TOKEN environment variable to your merchant's authentication token. Keep this token out of source control.
  3. Set STAX_PAYMENT_METHOD_ID to an existing payment method's id, such as b5f8729c-93ee-4bbb-9bfe-4a71f7b0e126. Use the actual ID from the GET /payment-method response, not this example value.
  4. Set STAX_IDEMPOTENCY_ID to a new UUID (Universally Unique Identifier), such as 19abe670-825b-4866-a446-3a8f019e1b2f, for this payment. Keep the same value when retrying this payment; use a new value for a different payment.
  5. Save the following code as charge.py and run python3 charge.py.

This example sends a $26.00 charge to the production API at https://apiprod.fattlabs.com/. Run it only when you intend to submit a payment. For testing, use your sandbox environment rather than submitting test payments to production.

import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


def main():
    names = ("STAX_API_TOKEN", "STAX_PAYMENT_METHOD_ID", "STAX_IDEMPOTENCY_ID")
    missing = [name for name in names if not os.environ.get(name)]
    if missing:
        print("Set these environment variables: " + ", ".join(missing), file=sys.stderr)
        return 1

    payload = {
        "total": 26.00,  # Use dollars and cents, not an integer count of cents.
        # Use the id returned by GET /payment-method for this merchant.
        "payment_method_id": os.environ["STAX_PAYMENT_METHOD_ID"],
        "pre_auth": False,  # Submit a charge rather than reserving funds only.
        "idempotency_id": os.environ["STAX_IDEMPOTENCY_ID"],
        "meta": {},
    }
    request = Request(
        "https://apiprod.fattlabs.com/charge",
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": "Bearer " + os.environ["STAX_API_TOKEN"],
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        method="POST",
    )
    try:
        with urlopen(request, timeout=30) as response:
            raw = response.read().decode("utf-8")
    except HTTPError as error:
        print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}",
              file=sys.stderr)
        return 1
    except (URLError, TimeoutError, OSError) as error:
        print(f"Could not confirm the payment result: {error}", file=sys.stderr)
        print("Check the transaction before retrying; reuse the same idempotency ID.",
              file=sys.stderr)
        return 1

    try:
        transaction = json.loads(raw)
    except ValueError:
        print("The API returned an empty or non-JSON response. Check the transaction "
              "before retrying with the same idempotency ID.", file=sys.stderr)
        return 1

    if (isinstance(transaction, dict) and transaction.get("success") is True
            and transaction.get("id")):
        print(f"Payment succeeded. Transaction ID: {transaction['id']}")
        return 0

    print("The response did not confirm a successful payment:", file=sys.stderr)
    print(json.dumps(transaction, indent=2), file=sys.stderr)
    print("Check the transaction before retrying with the same idempotency ID.",
          file=sys.stderr)
    return 1


if __name__ == "__main__":
    sys.exit(main())

On success, you receive success: true and a transaction id. The script prints a message like:

Payment succeeded. Transaction ID: ad107d1a-819b-45f8-9f46-0260a3b05d26

For an invalid or unauthorized payment method, the API can return HTTP 422 with:

{
  "payment_method_id": [
    "Payment method is invalid or unauthorized."
  ]
}

Correct validation errors before retrying. If a network failure leaves the outcome uncertain, check the transaction before retrying and reuse the same idempotency_id to avoid a duplicate charge.

Required charge parameters and the recommended retry identifier:

ParameterTypeValue and constraints
totalnumberRequired. Amount in dollars and cents; minimum $0.01. The example uses $26.00.
payment_method_idstringRequired. Use an existing payment method ID for this merchant.
pre_authbooleanRequired. Explicitly set false for a charge or true to reserve funds for later capture; do not rely on an implicit default.
idempotency_idstringOptional in the API; recommended for retries. Generate a unique UUID for each payment and reuse it only for retries of that payment.

For additional request fields, see the Charge a Payment Method endpoint documentation.


Pre-Authorizations

Use a pre-authorization to reserve a card amount without immediately capturing the funds. This supports payments whose final amount may change, such as hotel bookings or car rentals.

  1. Create: Set pre_auth to true when charging a payment method to reserve funds.
  2. Capture: Capture the authorized amount when you know the final amount.
  3. Void if necessary: If you no longer need the pre-authorization, void it to release the held funds instead of capturing them.

For more information, see the Pre-Authorizations and the Capture a Pre-Authorization endpoints.


Idempotency

Idempotency means that repeating an operation has the same effect as performing it once. Use it to prevent duplicate charges when network issues or retries cause your application to submit the same request again.

  • Idempotency ID: Generate a unique UUID for each payment and send it as idempotency_id. You generate this value in your application; you do not retrieve it from the Dashboard.
  • Duplicate requests: When the API receives another request with the same idempotency_id, it returns the original transaction instead of creating a new one.
  • Retries: Keep the original ID for retries of the same payment. Generate a new ID for each different payment.

For details on implementing idempotency, refer to the Idempotency Section.


Custom Fees (Partners Only)

Note for Partners: If you are a partner with Custom Fees enabled, you can specify custom fees for transactions. Please refer to the Custom Fees section in the Partner API documentation for detailed instructions.


Settlement Tokenization

Advanced feature: Enroll in Settlement Tokenization before using it.

Settlement (the completion of payment processing and transfer of funds) usually occurs the next business day. Tokenization replaces card details with a reusable reference, so your application can reference the card for later payments. With Settlement Tokenization, you can reuse a card from a Stax integrated terminal for card-not-present transactions (payments without the physical card at a terminal) after settlement completes.

Use this feature for:

Card-Not-Present Refunds: Issue refunds or voids without needing the original terminal.

Scheduled/Recurring Payments: Capture a card in-person and create scheduled payments afterward.

Future charges: Use the original transaction's payment_method_id for future charges once the payment method becomes available.

Important notes:

  • Availability: Stax tokenizes the card after settlement (completion of payment processing and transfer of funds). Wait until the payment method becomes available before reusing it.
  • Eligibility check: Poll the API to check the transaction's is_cnp_refundable value or whether a payment method exists.
  • Refund handling: Proceed with a card-not-present refund only when the transaction qualifies. If it does not qualify, do not submit the refund through this flow.

Level 2 Processing

Feature requirement: Enable Level 2 Processing on your merchant account before using it.

Level 2 Processing can help you qualify for lower interchange rates (card-processing fees paid to the card issuer) when you supply additional transaction details.

Provide these fields for Level 2 Processing:

FieldTypeConstraint
meta.taxnumberSupply a tax amount in dollars between 0.1% and 30% of the transaction total.
meta.poNumberstringSupply the customer code or purchase order number.
meta.shippingAmountnumberSupply the shipping amount; zero is valid.

These names identify request fields, not placeholder IDs.

To check if your merchant account is eligible for Level 2 Processing, please contact support.


Account Updater

The Account Updater service automatically updates stored payment methods when they become outdated or invalid. Use it to reduce interruptions to recurring payments and subscriptions, and handle payment method errors when updates are unavailable.

Common error messages related to Account Updater:

  • "The Payment Method has been redacted."
  • "The Payment Method has been deleted."
  • "Payment method is invalid or unauthorized."

Handle these errors:

  1. Obtain updated payment method details from the customer.
  2. Update the payment method information in your system.
  3. Retry the transaction with the new payment method.

Split Funding

Advanced feature: Enroll in Split Funding before using it.

Use Split Funding to distribute funds from a single transaction into multiple bank accounts when you need to allocate a payment to different parties or accounts.

Key points:

Funding Allocations: Specify the funding accounts and amounts at the time of the transaction.

Total Amounts: The sum of all funding amounts must exactly equal the transaction total.

Default behavior: If you omit the funding fields, Stax deposits the funds into the primary account.


Best Practices and Important Notes

Authentication: Use a valid authentication token and confirm that your team has active and enabled status before processing payments.

Webhooks: Implement webhook handlers (endpoints that receive event notifications) for events such as create_transaction to keep your system synchronized with transaction statuses.

Compliance: Use payment features to support your compliance efforts, not as a guarantee of compliance. Consult your legal team regarding requirements that apply to your integration. Feature-enrollment requirements on this page describe product access, not legal obligations.

Testing: Use your sandbox environment to test your integration before going live. The charge example above targets production; do not use it for sandbox testing without the correct sandbox configuration.

Error handling: Check both the HTTP status and the transaction's success value. Correct HTTP 400 or 422 request errors, check authentication for HTTP 401, and contact support for HTTP 500. If a response leaves the payment outcome uncertain, check the transaction before retrying with the original idempotency_id.


Response Status Codes:

CodeResponse
200OK: Success.
400Bad Request: Invalid request; check error messages.
401Unauthorized: Authentication required or failed.
422Unprocessable Entity: Validation errors; check provided data.
500Internal Server Error: Server-side issue; contact support.