Testing Workflows in your Sandbox
Map test card and ACH payloads to expected outcomes in the Stax sandbox — including tokenization, successful payments, declines, pending/timeout states, disputes, and ACH rejections.
Verify your payment integration by mapping test requests to expected results in the Stax sandbox.
This guide is for developers using sandbox accounts configured with test gateways (services that simulate payment processing) for credit cards and ACH (Automated Clearing House, a network for bank-account payments). Use mock payment data only. Sandbox transactions do not pass through a real Merchant ID (MID, the identifier for a merchant's payment-processing account). The test gateway selects its response from the payment method and total amount you send.
These results apply only to sandbox accounts, not live merchant accounts used for testing. Sandbox testing supports your compliance efforts; it does not establish PCI DSS (Payment Card Industry Data Security Standard) compliance or replace production checks. Consult your legal team regarding specific requirements.
1. Prepare your sandbox test
- Required: Create a sandbox account using Test Environments and 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. Keep the key on your server and out of public repositories.
- Required: Store a payment method using the test credentials below and the Storing Payment Methods instructions. Tokenization replaces payment details with a reusable identifier so you can charge a saved payment method. Copy the payment method object's
idfrom the API response, not the card number or customer ID. - Required for the example: Install Python 3. Save the following code as
sandbox_charge.pyand runpython3 sandbox_charge.py.
The card and bank-account numbers in this guide are test inputs, not Dashboard IDs. Obtain the payment method ID from its creation or retrieval API response; no Dashboard location for this ID is documented here. The example prompts for actual values rather than embedding dummy IDs.
2. Send a baseline test charge
Use the Visa test card 4111 1111 1111 1111 when storing the payment method for this example. The example submits a $26.00 charge, with pre_auth set explicitly to false to submit the payment rather than reserve funds for later processing. It makes one request and does not retry automatically.
import getpass
import json
import sys
import uuid
import urllib.error
import urllib.request
def main():
# Copy the sandbox 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 API 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
if input("Confirm your key is for a sandbox (type SANDBOX): ").strip() != "SANDBOX":
print("No request sent.")
return 0
# Keep this identifier for retries of the same payment to prevent duplicates.
idempotency_id = str(uuid.uuid4())
print(f"Save this idempotency ID: {idempotency_id}", flush=True)
payload = {
"payment_method_id": payment_method_id,
"total": 26.00, # Stax uses dollars and cents, not an integer cent amount.
"pre_auth": False,
"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=45) as response:
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)
print("Review the error and verify the transaction before retrying.", file=sys.stderr)
return 1
except (urllib.error.URLError, OSError) as error:
print(f"Payment outcome unknown: {error}. Verify it before retrying.", file=sys.stderr)
return 1
try:
transaction = json.loads(body)
except ValueError:
print("Empty or invalid JSON; verify the transaction before retrying.", 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("Payment success was not confirmed:", file=sys.stderr)
print(json.dumps(transaction, indent=2), file=sys.stderr)
print("For a pending or unknown outcome, verify the final state before retrying.",
file=sys.stderr)
return 1
if __name__ == "__main__":
try:
sys.exit(main())
except (EOFError, KeyboardInterrupt):
print("\nInterrupted. If a request was sent, verify its outcome before retrying.",
file=sys.stderr)
sys.exit(1)A successful request returns HTTP 200, success: true, and a transaction id. The script prints a message like this; your transaction ID will differ:
Payment succeeded. Transaction ID: ad107d1a-819b-45f8-9f46-0260a3b05d26For HTTP 401, check your sandbox secret API key. For HTTP 422, inspect the field errors and confirm that the saved payment method belongs to the merchant associated with your key. For a connection error, HTTP 500, invalid response, or pending result, verify the transaction before retrying; use the saved idempotency_id for a retry of the same payment rather than rerunning this script, which generates a new ID.
The example uses these required parameters and recommended retry protection. No implicit defaults are assumed:
| Parameter | Type | Requirement and example value |
|---|---|---|
payment_method_id | string | Required. Use a saved payment method belonging to your sandbox merchant. |
total | number | Required. Amount in dollars and cents; minimum $0.01. The example uses $26.00. |
pre_auth | boolean | Required. Explicitly set false to submit a charge rather than reserve funds only. |
idempotency_id | string | Recommended. A unique identifier that prevents retries from creating duplicate payments. Generate one per payment and reuse it only for retries of that payment. |
3. Verify the remaining scenarios
Use the tables below to select each payment method and amount, then compare your integration's result with the documented outcome. For charge request details, see Charge a Payment Method.
Successful Tokenization (Storing Payment Methods)
You can test the tokenization and storage of payment methods (cards/ACH) on file independently of an immediate payment transaction.
Any combination of mock credit card or ACH data that passes basic validation will succeed in tokenizing the payment method. For cards, this includes the Luhn check (a calculation that checks whether a card number has a valid digit pattern).
| Target Intent | Payment Method / Test Asset String | Expected API Status | Engineering Action Item / Notes |
|---|---|---|---|
| Tokenize Card | Use any valid standard test card number | Payment Method created | Verifies tokenization only. No payment is applied. |
| Tokenize ACH | Use valid test routing/account numbers | Payment Method created | Verifies tokenization only. No payment is applied. |
Successful Payment Scenarios
Use these test scenarios to verify successful credit card and ACH payments. For cards, authorization is the approval of a payment amount. Use future card expiration dates and a valid CVV (Card Verification Value, the card's security code) length to pass front-end checks.
Use $26.00 for your baseline test. Other amounts can succeed, but the amounts in the failure and pending tables trigger specific outcomes. Other combinations of card numbers and routing/account numbers may also trigger successful payment tests.
Credit Card Specifics (AVS, CVV, and Stored Credentials)
- AVS (Address Verification Service) / CVV (Card Verification Value) Verification: Sandbox accounts do not validate AVS or CVV, so it is not possible to trigger AVS or CVV failures in the test environment (aside from basic CVV length checks). In production, however, payments may fail if this data is missing or invalid.
- Stored credentials describe how you use a saved payment method and who initiates the payment. Recommended in sandbox: Include these fields even though the sandbox does not validate them. Required in production: Include the applicable stored-credential fields to avoid card-brand payment failures. See Storing Payment Methods for the required fields and Best Practices for guidance on payments that repeat on a schedule.
Credit Card Success Credentials
| Card Brand | Card Number |
|---|---|
| Visa Credit | 4111 1111 1111 1111 |
| Mastercard Credit | 5105 1051 0510 5118 |
| Discover Credit | 6011 1111 1111 1117 |
| Amex Credit | 3782 822463 10005 |
For each card, you can use any dollar amount. The API message will be empty with a success status.
Debit Card Success Credentials
This card test verifies the processing path used for debit cards. Required for integrations that add a surcharge (an extra fee for paying by card): Test debit card handling.
| Card Brand | Card Number |
|---|---|
| Mastercard Debit | 2223 0031 2200 3222 |
For each card, you can use any dollar amount. The API message will be empty with a success status.
ACH Success Credentials
| Payment Method | Test Credentials |
|---|---|
| Standard ACH | Routing: 021000021 Account: 9876543210 |
For each card, you can use any dollar amount. The API message will be empty with a success status.
Payment Failure Testing
Immediate Payment Failure Scenarios
These scenarios trigger immediate gateway-level failures. Because payments can fail for various reasons, do not rely on specific error messages for business logic. Instead, surface the specific error provided in the API response's message field to the user.
These ACH cases cover only immediate gateway declines. ACH payments can also fail after the initial response; handle these later rejections using the lifecycle scenarios below.
| Card Issue | Card Number | Total Amount |
|---|---|---|
| Payment Decline (Credit Card) | 4111 1111 1111 1129 | $201.00 |
| Payment Decline (ACH) | Routing 021000021 / Account 9876543210 | $201.00 |
| General Payment Error (Credit Card) | 6011 0009 9013 9424 | $0.11 |
| General Payment Error (ACH) | Routing 021000021 / Account 9876543210 | $0.11 |
For a declined card issue, the API status will be Fail with the API message, "gateway response: Declined".
For general payment errors, the API status will be Fail with the API message, "gateway response: Error".
For either message, display the error message and prompt the user to re-enter a valid payment method.
Connectivity Issues & Pending Statuses
These scenarios simulate network connectivity issues where the initial transaction status is unknown. To determine the final state, use API polling or listen for the update_transaction webhook event.
For PENDING transactions, do not treat the event as a hard failure, as the status may resolve. Because reattempts can lead to duplicate charges, we recommend displaying the following messaging to your customers:
Payment Pending: Please do not retry the transaction as it may cause duplicate charges. Your payment will update automatically. If it remains pending for more than 24 hours, please contact customer support.
While Stax monitors for final states, transactions should rarely remain PENDING. If a transaction remains in this state indefinitely, please contact support.
Use any valid success credit card or ACH method.
| Scenario | Total Amount | API Status |
|---|---|---|
| Self-Resolving Network Delay | $763.67 | PENDING (eventually resolves to SUCCESS) |
| Gateway Request Timeout | $68.00 | PENDING |
Both scenarios will respond with the message, "Gateway Unreachable".
Use webhooks (update_transaction) or poll the API to detect state transition.
For the self-resolving scenario, the transaction initiates in PENDING status and resolves to SUCCESS.
For the gateway request timeout scenario, the gateway connection hangs for 30 seconds. This scenario is intentionally designed to mimic a rare edge case where the payment remains PENDING. Status is unknown; however, do not treat it as a hard failure. Use webhooks or poll the API to detect the final state.
In live production accounts, if PENDING persists for more than 24 hours, contact Stax support.
Test settlement and later payment events
Settlement is the process of finalizing a payment for transfer of funds. These test cases initially return SUCCESS and retain that status while adding properties that describe later payment events.
Required to trigger these events: After creating the initial payment, open Stax Pay > Deposit Report > Simulate Settlement or Stax Connect > Deposit Report > Simulate Settlement.
- Credit card disputes (cases where a cardholder challenges a payment): Monitor via API polling or the
create_disputeandupdate_disputewebhooks.- NOTE: Some live merchant accounts do not support this dispute functionality.
- ACH Rejections: Monitor via API polling or the
update_transaction_settledandcreate_transactionwebhooks to detect auto-voided child transactions and their funding.
| Event Type | Total Amount | API Status |
|---|---|---|
| Credit Card Dispute | $8888.88 | Success |
| Asynchronous ACH Rejection /Failure /Clawback | $730.14 | Success |
Handle a credit card chargeback (a reversal of funds associated with a disputed card payment): Keep the original API success status and check for associated Dispute records. Block refunds while a dispute is active to avoid returning the funds twice. Update your internal transaction status to 'Disputed' until resolution.
Handle an ACH rejection (a bank's refusal or return of a bank-account payment): The original status remains 'Success'; check for a child_transaction with type: void (a linked transaction that cancels the payment). Stax automatically voids the transaction upon rejection, which can occur days or months later.
Block refunds to avoid returning the funds twice. Update your internal transaction status, invoices, and receivables (amounts customers owe you) to 'Failed', 'Voided', or 'Unpaid' to match the void event.
ACHAn ACH success status does not confirm that you will retain the funds. A payment may fund (credit money to your account) before the bank finishes processing it; if processing fails, the bank may take the funds back (a clawback). A rejection before funding produces no deposit record. If funds are taken back later, account for that event during reconciliation (matching your payment records to deposits and withdrawals).
Digital Wallets
Digital Wallet testing requires a live gateway configuration. You must add valid credit or debit cards to your Apple or Google Wallet before testing.
Success Scenarios
Complete the transaction using your device's digital wallet at checkout.
Failure Scenarios
To simulate declines, test with an invalid card or a gift card with a $0 balance.
If your account is set up for Digital Wallets, you can learn more in Accepting Apple or Google Pay. A successful wallet test completes the checkout transaction; confirm the payment result before treating the order as paid.
Legacy Sandbox Accounts
If any of the card numbers listed in this article are not working as documented, you may be using a legacy sandbox account. Please reach out to support to request to be upgraded to the new sandbox account for full testing functionality.
Live Account Required for TestingIn addition to digital wallets, the following features require a live account for testing:
- Paypal testing
- Card-present payments (payments accepted with the customer's card or device physically present) using Dejavoo terminals
- Card-present mobile transactions
- Card-present tap-to-phone transactions
Contact Stax for guidance before testing these live-account scenarios.
Updated 4 days ago
