Charge a Payment Method

Charge a saved payment method with POST /charge, including a runnable sandbox example, response handling, parameter requirements, and PCI guidance.

Charge a customer's saved payment method under your merchant account with POST /charge.

Audience: Developers integrating server-side payments. Set pre_auth to false to authorize the payment (approve the amount) and capture it (submit it for payment) in one transaction, creating a record with type = charge.

Send a test charge

  1. Create a sandbox account using Test Environments, then copy its secret API key from Stax Pay > Apps > API Keys. Sandbox and live accounts share the same API URL; use a sandbox key to avoid moving real money.
  2. Create a payment method using POST /payment-methods, or retrieve an existing payment method associated with your sandbox customer. Copy the payment method object's id; use a method belonging to the merchant associated with your API key.
  3. Run the Python 3 example below in a terminal. It uses only the standard library, prompts for your credentials and payment method ID, and submits a $26.00 test charge. Keep the secret API key on your server and out of public repositories.

The documented response uses UUID-shaped IDs, such as b5f8729c-93ee-4bbb-9bfe-4a71f7b0e126 for a payment method. This is example data, not a usable payment method for your account.

import getpass
import json
import sys
import uuid
import urllib.error
import urllib.request


def main():
    # Copy the sandbox secret key from Stax Pay > Apps > API Keys.
    api_key = getpass.getpass("Sandbox secret API key: ").strip()
    # Copy the payment method object's id from its creation or retrieval response.
    payment_method_id = input("Sandbox payment method ID: ").strip()
    if not api_key or not payment_method_id:
        print("Enter both an API key and a payment method ID.", file=sys.stderr)
        return 1

    # Reuse this value for retries of the same payment to avoid duplicate charges.
    idempotency_id = input("Existing idempotency ID for a retry (Enter for a new payment): ").strip()
    if not idempotency_id:
        idempotency_id = str(uuid.uuid4())
    print(f"Save this idempotency ID before continuing: {idempotency_id}", flush=True)

    payload = {
        "payment_method_id": payment_method_id,
        "total": 26.00,  # Stax expects dollars and cents, not an integer cent amount.
        "pre_auth": False,  # Capture now rather than place an authorization-only hold.
        "idempotency_id": idempotency_id,
        "meta": {},
    }
    request = urllib.request.Request(
        "https://apiprod.fattlabs.com/charge",
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            status = response.status
            body = response.read().decode("utf-8", errors="replace")
    except urllib.error.HTTPError as error:
        print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}", file=sys.stderr)
        return 1
    except (urllib.error.URLError, OSError) as error:
        print(f"Connection failed: {error}. The payment outcome is unknown; reuse the saved idempotency ID if you retry.", file=sys.stderr)
        return 1

    try:
        transaction = json.loads(body)
    except ValueError:
        print(f"HTTP {status}: Expected JSON but received an empty or invalid response. Verify the payment before retrying, and reuse the saved idempotency ID.", file=sys.stderr)
        return 1

    if not isinstance(transaction, dict) or transaction.get("success") is not True or not transaction.get("id"):
        print(f"HTTP {status}: Payment success was not confirmed.", file=sys.stderr)
        print(json.dumps(transaction, indent=2), file=sys.stderr)
        return 1

    print(json.dumps({
        "id": transaction["id"],
        "success": transaction["success"],
        "type": transaction.get("type"),
        "total": transaction.get("total"),
        "pre_auth": transaction.get("pre_auth"),
    }, indent=2))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (EOFError, KeyboardInterrupt):
        print("\nInput interrupted. If a request was already sent, verify the payment before retrying and reuse the saved idempotency ID.", file=sys.stderr)
        sys.exit(1)

A successful request returns HTTP 200 with success: true and a transaction ID. The example prints these fields from the documented response; your transaction ID will differ:

{
  "id": "ad107d1a-819b-45f8-9f46-0260a3b05d26",
  "success": true,
  "type": "charge",
  "total": 26,
  "pre_auth": false
}

For HTTP 422, inspect the field errors. For example, an invalid payment method returns:

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

Use a valid payment method belonging to the authenticated merchant before retrying. For HTTP 401, check your secret API key. For HTTP 400, review the request parameters; for HTTP 500, a connection failure, or an unconfirmed response, verify the transaction outcome before retrying and reuse the saved idempotency_id for the same payment.


Usage Scenarios

E-commerce Purchases: Charging a customer's credit card for an online order.

Service Payments: Collecting payment for services rendered immediately after completion.

Subscription Setups: Charging an initial fee when a customer subscribes to a service.


Response Structure

CodeResponseReason
200SuccessA successful response returns a transaction object containing details about the processed charge, including transaction ID, type, status, amount, currency, payment method ID, customer ID, creation timestamp, and any metadata provided.
400Bad RequestThe request was invalid due to incorrect parameters.
401UnauthorizedAuthentication failed due to invalid or missing authentication tokens.
422Unprocessable EntityValidation errors occurred, such as missing required fields or invalid values.
500Internal Server ErrorAn unexpected error occurred on the server.

Detailed Parameter Descriptions

ParameterTypeRequiredDefault and constraints
payment_method_idstringYesNo default. Use an existing payment method belonging to the authenticated merchant. Copy its id from the creation or retrieval response.
totalnumber (float)YesNo default. Minimum 0.01, expressed in dollars and cents; 26.00 charges $26.00.
pre_authbooleanYesNo default; send it explicitly. Use false for an immediate charge. Use true for a pre-authorization (a hold on funds without capturing them).
idempotency_idstringNo; recommendedNo default documented. Generate a unique value for each new payment, and reuse it when retrying that payment to prevent duplicates. The example generates a UUID (Universally Unique Identifier).
metaobjectNo in the request schemaNo default documented. Include additional payment information, such as tax, poNumber, shippingAmount, custom fields, and descriptors. The example sends an empty object.

Optional: Line-item metadata. Use the case-sensitive key meta.lineItems. Its documented fields are id, quantity, price, item, and details (the item's description).


Usage Notes

Optional: Level 2 Processing (additional transaction data used to qualify eligible payments for different processing rates). Your merchant account must have this feature enabled. Include tax, poNumber, and shippingAmount in the meta object. The tax amount must be between 0.1% and 30% of the total; shippingAmount can be zero.

Idempotency: It's crucial to use idempotency_id to prevent duplicate charges. If a request with the same idempotency_id is received, the API returns the original transaction.

Error Handling: Implement robust error handling to capture and address issues promptly. Check for validation errors and provide meaningful feedback to users.

Webhooks: This endpoint triggers the create_transaction webhook. Ensure your application handles webhooks to stay synchronized with transaction statuses.


Additional Considerations

Settlement Timing: With pre_auth: false, funds are typically captured immediately, but settlement (the transfer of payment funds to the merchant's account) may vary based on banking processes.

Fraud Prevention: Utilize security measures such as AVS (Address Verification System) and CVV checks to reduce the risk of fraudulent transactions. Transaction Defense fraud scoring may also block a charge before it reaches the payment gateway if the transaction's risk score exceeds the merchant's configured threshold. When a transaction is blocked, the API returns the message: "Payment failed, please reach out to the merchant to complete the transaction."

Recurring Payments: For recurring charges, store the payment_method_id securely and comply with all applicable regulations regarding the storage of payment information.

PCI Compliance: PCI DSS (Payment Card Industry Data Security Standard, a security standard for handling payment card data) requirements are separate from the recommended fraud-prevention measures above. We recommend client-side tokenization (replacing card details with a payment method identifier) through Stax.js to support your compliance efforts; it does not replace applicable PCI DSS requirements. Consult your legal team regarding the specific requirements for your integration.

Body Params
float
required

Float is required and will be the amount a customer is charged, in dollars and cents. Min: 00.01

string
required

An existing payment_method id within Stax. The customer_id is derived from this automatically.

meta
object

Can contain any json object

boolean
required

Creates a pre authorization

string

Creates a pre authorization

string

A unique string identifier to help prevent against duplicate operations

string

A way to identify where a transaction originated (ex. "partner-mobile-application" or "partner-web-application:). Stax's UI fills this channel parameter with values that correspond to where the transaction originated from. This value lives in the API only and does not show up on the Stax Payment dashboards.

funding
object

Defines how the funds from this transaction should be paid out. This attribute is only supported with the Split Funding feature enabled

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