Return funds from the merchant to the customer after a transaction has been processed (batched)
Return all or part of a customer's payment with POST /transaction/{id}/refund after batching (grouping transactions for processing).
This reference is for developers integrating refunds with the Stax API.
Prepare your refund request
- Install Python 3 to run the standard-library example below.
- Copy your merchant API key from Stax Pay > Apps > API Keys for Bearer authentication. Keep the key out of client-side code and public repositories. Use a sandbox key for testing: sandbox and live accounts share
https://apiprod.fattlabs.com, and your API key determines which environment you access. A sandbox processes test payments without moving real money. - Copy the original transaction's
idfrom an existing transaction response. For example,"6f49149d-69a1-48e6-bec5-d63eb5816118"illustrates the documented UUID format; use an ID belonging to your merchant account, not this example value. To review the payment in the Dashboard, open Stax Pay > Payments, then select the transaction to open Payment Details. Use the API response as the source of the API transaction ID; the available documentation does not identify a Dashboard field containing that ID. - Retrieve the original transaction with
GET /transaction/{id}. Confirm thatis_refundableistrueand check the remaining refundable amount before submitting a refund.
Submit a partial refund
Send the original transaction ID in the path and total as a JSON string in dollars. Both are required and have no documented defaults. Set total to at least "0.01" and no more than the remaining refundable amount.
Run this Python 3 example. It defaults to the sandbox environment label and a $0.01 partial refund, prompts for credentials and the transaction ID, and requires confirmation before sending the request. The environment label does not switch accounts or validate your key: enter a key for the selected environment. The script does not retry automatically because another submission could create another refund.
import getpass
import json
import socket
import sys
from decimal import Decimal, InvalidOperation
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen
def main():
environment = input("API key environment (sandbox/live) [sandbox]: ").strip().lower() or "sandbox"
if environment not in ("sandbox", "live"):
sys.exit("Choose sandbox or live; no refund request was sent.")
# Both environments share this URL; the API key selects the account.
base_url = "https://apiprod.fattlabs.com"
# Copy the matching account's key from Stax Pay > Apps > API Keys.
api_key = getpass.getpass(f"Merchant {environment} API key: ").strip()
# Review the payment in Stax Pay > Payments > select transaction > Payment Details.
# Copy its API id from an existing transaction response, not a payment reference.
# Example UUID string: "6f49149d-69a1-48e6-bec5-d63eb5816118" (do not use as a default).
transaction_id = input("Original transaction ID: ").strip()
total = input("Refund amount in dollars [0.01]: ").strip() or "0.01"
if not api_key or not transaction_id:
sys.exit("Provide both an API key and a transaction ID.")
try:
amount = Decimal(total)
if not amount.is_finite() or amount < Decimal("0.01"):
sys.exit("Enter a refund amount of at least $0.01.")
if amount != amount.quantize(Decimal("0.01")):
sys.exit("Enter an amount with no more than two decimal places.")
except InvalidOperation:
sys.exit("Enter a valid dollar amount, such as 0.01.")
total = format(amount, ".2f")
print(f"Selected environment: {environment}. Your API key determines the actual account.")
if environment == "live":
print("Live refunds return real money. Verify your key and transaction before continuing.")
confirmation = input(
f"Refund ${total} on transaction {transaction_id} ({environment})? Type REFUND: "
)
if confirmation != "REFUND":
sys.exit("Cancelled; no refund request was sent.")
request = Request(
base_url + "/transaction/" + quote(transaction_id, safe="") + "/refund",
data=json.dumps({"total": total}).encode("utf-8"),
headers={
"Authorization": "Bearer " + api_key,
"Content-Type": "application/json",
"Accept": "application/json",
},
method="POST",
)
try:
with urlopen(request, timeout=30) as response:
status = response.status
transaction = json.load(response)
except HTTPError as error:
guidance = {
400: "Check the request parameters.",
401: "Check your merchant API key.",
404: "Check that the transaction ID belongs to this merchant.",
422: "Check refund eligibility and the remaining refundable amount.",
500: "Check the transaction status before submitting another refund.",
}
sys.exit(f"HTTP {error.code}: " + guidance.get(
error.code, "Check the transaction status before trying again."
))
except (URLError, TimeoutError, socket.timeout):
sys.exit("Connection failed; check the transaction before trying again.")
except (ValueError, UnicodeError):
sys.exit("Invalid JSON response; check the transaction before trying again.")
if status != 200 or not isinstance(transaction, dict):
sys.exit("Unexpected response; check the transaction before trying again.")
print(json.dumps(transaction, indent=2))
children = transaction.get("child_transactions")
refunds = [
child for child in children
if isinstance(child, dict) and child.get("type") == "refund"
] if isinstance(children, list) else []
if transaction.get("success") is False:
sys.exit("The returned transaction reports failure. Review its details.")
if not refunds:
sys.exit("No refund child transaction returned. Verify before trying again.")
print("Refund records returned. Confirm the newly added record and its outcome.")
if __name__ == "__main__":
main()Expected result: HTTP 200 returns the original transaction with an added entry in child_transactions whose type is "refund" and whose reference_id links to the original transaction. The script prints the returned JSON and, when refund records are present, this message:
Refund records returned. Confirm the newly added record and its outcome.Compare the returned records with the original transaction to identify the new refund; an older refund record alone does not confirm this request's outcome. The endpoint specification provides only an empty response example, so no complete JSON refund response is shown here.
Check refund limits and linked transactions
- Batching requirement: Refund transactions that have been batched. Batching groups transactions for processing; settlement is the completion of payment processing and transfer of funds. Use
is_refundableto check eligibility rather than assuming that batching and settlement mean the same thing. - Partial refunds: Refund any amount between $0.01 and the total remaining refundable amount.
- Child transactions: Each refund creates a linked transaction with
type = refundand areference_idpointing to the original transaction.
Optional: Refund terminal payments with Settlement Tokenization
Settlement Tokenization lets you reuse a card captured at a Stax integrated terminal without presenting the physical card again, after settlement (completion of payment processing and transfer of funds). Tokenization replaces card details with a reusable reference. Enroll in this feature before using it.
If your merchant account has this feature enabled and the transaction is not yet available for refund via API, this endpoint returns HTTP 422 with the message:
This transaction is not yet available to be refunded via API. You can still complete this transaction through the card present flow.
In this case, use POST /terminal/void-or-refund to process the refund through the terminal with the customer's physical card.
Usage Notes
Refund Eligibility: Check the transaction object's is_refundable flag before submitting a refund.
Calculating Refund Amounts: The total amount refunded across all refund transactions cannot exceed the original transaction amount.
Multiple Refunds: You can issue multiple partial refunds as long as the cumulative total does not exceed the original transaction amount.
Child Transactions: Each refund action creates a child transaction linked to the original transaction for tracking purposes.
Error Handling: Attempting to refund more than the remaining refundable amount will result in an error.
Response Structure
| Code | Response | Reason |
|---|---|---|
| 200 | Success | Returns the original transaction object with an added child transaction of type = refund. |
| 400 | Bad Request | Invalid request parameters. |
| 401 | Unauthorized | Authentication failed. |
| 404 | Not Found | Transaction ID does not exist. |
| 422 | Unprocessable Entity | The transaction cannot be refunded (e.g., amount exceeds refundable total). |
| 500 | Internal Server Error | An unexpected error occurred on the server. |
Important Considerations
Refund Timing: Refunds may take several business days to process, depending on the customer's bank.
Customer Notification (recommended): Notify the customer after you confirm that the refund has been initiated. This recommendation is separate from the endpoint's required authentication, transaction eligibility, and refund amount constraints.
Compliance responsibilities (required, not an optional recommendation): Address your applicable Payment Card Industry Data Security Standard (PCI DSS) requirements, which protect cardholder data. Stax's security features support your compliance efforts; using this refund endpoint does not guarantee compliance or replace your responsibilities. Review PCI Compliance Protocols and consult your legal and compliance teams regarding specific requirements.
Refunding Terminal Transactions: If you are refunding a transaction that was processed through a terminal, and Settlement Tokenization is not enabled or the transaction is not yet available for refund via API, you may need to process the refund directly through the terminal.
Testing Environment Notes
- In a sandbox account, transactions are not refundable until 12 am EST.
- Certain behaviors in the testing environment may differ from production; plan accordingly.
