Errors
A batch payment reports problems at three points: when you submit it, while Xtrm processes its items in the background, and when you check status (see How batch payments work). Errors at submission come back in the response to BatchTransfer. Failures during processing are recorded on each item and, if webhooks are set up for your account, sent to you as events. The other endpoints report their outcome in an OperationStatus object, covered at the end of this page in Other endpoints. To build, submit and track a batch step by step, see Create a batch payment.
A 202 means received, not paid
A 202 response means Xtrm checked the request and accepted the items listed in Accepted. Its Status is Accepted, CompletedWithFailures (some items rejected) or Failed (nothing stored). No money moves at submission: the payments run afterwards, and an accepted item can still fail. Check the outcome of each item with the batch status endpoints or with webhooks. See Batch and payment statuses.
#Where a batch payment reports errors
| When | What you get | Where to read more |
|---|---|---|
| You submit a batch and the request as a whole is refused | A 4xx HTTP status, and nothing is stored | The whole request is refused |
| You submit a batch and Xtrm hits an unexpected error | A 500: you can't tell what was stored, so wait and resend the identical request | A safe retry pattern |
| You submit a batch and some items fail the submission checks | 202 with Status CompletedWithFailures, and those items listed in Rejected. If no item passes, 422 or 409. | Items rejected at submission |
You send a CustomerBatchId and CustomerTransactionId that are already stored | CONFLICT_DUPLICATE_ITEM in Rejected, or 409 CONFLICT_PROCESSING for the whole request | Duplicate IDs |
| An item fails while Xtrm processes it | Item Status Failed, an ErrorCode on the attempt, and a Batch.Item.Failed webhook. If the delivery from the recipient's wallet to the destination fails, the item stays RetainedInWallet instead, with a Failed attempt, and the webhook is Batch.Item.Completed with DeliveryType Wallet: the money has left your wallet, and the fee isn't refunded (see When a payment stays RetainedInWallet). | Errors during processing |
| You resubmit an item to retry it | A new attempt if the item is Failed; otherwise CONFLICT_DUPLICATE_ITEM or 409 CONFLICT_PROCESSING | Resubmit failed items |
| A request for the status of a batch or an item fails | A 4xx HTTP status, or 500 | Errors when you check status |
#Errors when you submit a batch payment
Before it responds, Xtrm runs a synchronous check of the request: format, authentication, the source wallet, the IDs, and the fields each send method needs. Checks that look up the recipient and its destination, such as whether the recipient exists or whether the bank account or card SKU is valid, run later, while the item is processed. An item can therefore pass submission and still fail with a code such as RECIPIENT_NOT_FOUND (see Errors during processing).
#The whole request is refused
When the request as a whole fails a check, Xtrm refuses it and stores none of its items. The 415 and token 401 responses have a body of the form {"error": …, "error_message": …}. Every other refusal is a BatchTransferResponse with Status Failed, the code below in Key, the HTTP status as a number in ErrorCode, and a Message; some messages start with a space. Accepted is empty or null, and so is Rejected unless every item was rejected. CustomerBatchId and ItemsCount can also be null.
| HTTP status | Code | Cause |
|---|---|---|
400 | BAD_REQUEST | The body is empty or isn't valid JSON. |
401 | invalid_authorization, invalid_authentication_type, invalid_credentials or invalid_token, in error | The token is missing, empty, unrecognized, revoked or expired, doesn't use the Bearer scheme, or comes from an IP address your company doesn't allow. See Authentication errors. |
401 | Unauthorized | The token isn't allowed to act for IssuerAccountNumber. |
403 | FORBIDDEN | SourceWalletId isn't an active wallet owned by IssuerAccountNumber itself, in an active currency, or that account isn't active. A wallet that another company shares with you fails too. This is the only 403 a batch payment returns. |
409 | CONFLICT_PROCESSING | The CustomerBatchId is already in use, in any Xtrm account, and none of its items is Failed. See Duplicate IDs. |
409 or 422 | None at the top level | No item passes: every item is listed in Rejected with its own code, and Status is Failed. The HTTP status is 409 if any of them is CONFLICT_DUPLICATE_ITEM, otherwise 422. |
413 | PAYLOAD_TOO_LARGE | The request's Content-Length is over Xtrm's request-size limit, which is the same for every account. |
415 | invalid_media_type, in error | Content-Type is missing or isn't one of the supported media types. Send application/json (a charset parameter is fine). |
422 | INVALID_FIELD | IssuerAccountNumber is missing, longer than 20 characters or doesn't start with SPN; Items is empty or missing; CustomerBatchId is missing or breaks the ID rules; or SourceWalletId is missing, 0, negative or not a number. |
422 | LIMIT_EXCEEDED | Items holds more items than your account's limit. Message ends with MaxAllowed: N, where N is your limit. |
500 | TEMPORARY_ERROR | Xtrm hit an unexpected error, and you can't tell what it stored, so treat it like a timeout. |
A 202 can also report a failure. Status Failed with Key TEMPORARY_ERROR means that the items passed the checks but Xtrm couldn't store any of them: that call stored nothing, and Accepted and Rejected are empty. The call may have collided with an earlier request for the same batch that is still running. Wait, then confirm with the batch status endpoint and, for any item that seems missing, with the item status endpoint, repeating the check a few times, at least a minute apart. Then resend the identical request (see A safe retry pattern). A 400 whose body has no BatchTransferResponse, such as one whose Message is Sequence contains no elements, comes from an unexpected error during the checks. You can't tell what it stored, so treat it like a timeout: wait, then resend the identical request.
To send more items than your limit, or a body larger than the size limit, we recommend splitting them across several batches, each with a new CustomerBatchId. For every refused request, we recommend logging the HTTP status and the raw body, reading Key, Message and Rejected whenever the body contains them, and not assuming that the body is JSON.
#Items rejected at submission
If at least one item passes the checks, Xtrm accepts the request and answers 202. The items that passed are queued for processing and listed in Accepted, in no particular order. The items that failed are listed in Rejected and not stored. Status is then CompletedWithFailures, and ItemsCount.Rejected is ItemsCount.Total minus ItemsCount.Accepted.
A successful submission is always 202, never 200. We recommend reading Status, ItemsCount and Rejected in every 202, and confirming the accepted items with the status endpoints, because a 202 doesn't prove that every listed item was stored.
Each entry in Rejected has these fields:
| Field | Example | Meaning |
|---|---|---|
CustomerTransactionId | The identifier of the rejected item, as Xtrm stored it. | |
Key | INVALID_FIELD | The rejection code (see the table below). |
ErrorCode | 422 | The HTTP-style code that goes with Key, as an integer: 422, 409 for CONFLICT_DUPLICATE_ITEM or 500 for TEMPORARY_ERROR. |
Field | Items[0].Destination.SKU | The path of the field that failed, as Items[i].<path>. For CURRENCY_MISMATCH, Field is "". |
Message | A human-readable explanation of why the item was rejected. |
Match rejected items by CustomerTransactionId, not by the index in Field: the index skips items that were removed as conflicts, some errors name a related field, and one item can appear more than once. An item in Rejected wasn't stored by this request. With CONFLICT_DUPLICATE_ITEM, it had already been stored by an earlier request.
These are the rejection codes:
| Code | ErrorCode | Cause |
|---|---|---|
INVALID_FIELD | 422 | An item field fails a rule: RecipientId is missing, longer than 20 characters, your own IssuerAccountNumber, or the wrong account type for XTR94502 (PAT…) or XTR94504 (SPN…); SendMethodId isn't one of the seven values, in upper case; Amount is missing, not greater than 0, or above 9999999999999999.99; Destination is missing, lacks a field that the send method requires, or has a field that is too long or malformed, such as Email; Destination.WalletId equals SourceWalletId; Description is longer than 1,024 characters after Xtrm HTML-encodes it (each &, for example, counts as 5 characters); or CustomerTransactionId breaks the ID rules. |
DUPLICATE_ITEM_IN_REQUEST | 422 | The same CustomerTransactionId appears more than once in the request. Xtrm rejects every copy, the first included, and processes none of them. |
CONFLICT_DUPLICATE_ITEM | 409 | The item is already stored in this batch with a status other than Failed. See Duplicate IDs. |
CURRENCY_MISMATCH | 422 | A check item (XTR94507) sent from a source wallet that isn't in USD. Field is "". |
TEMPORARY_ERROR | 500 | Xtrm couldn't store the item. Confirm that it isn't in the batch before you send it again. |
Destination is required on every item, whatever the send method: for a wallet item without a WalletId, send {}. Which Destination fields each send method requires is listed in the BatchTransfer reference and in Payment methods & destinations.
To fix an item rejected with INVALID_FIELD, correct the field named in Field; for CURRENCY_MISMATCH, send the check from a USD wallet. Then send the item again. It was never stored, so it has no attempt and can keep its CustomerTransactionId. You can send it under the same CustomerBatchId only if nothing of that batch was stored or the batch has a Failed item; otherwise send it in a new batch with a new CustomerBatchId. The other codes need different handling:
CONFLICT_DUPLICATE_ITEM: an earlier request already stored the item. Don't resend it; follow the existing item with the status endpoints.DUPLICATE_ITEM_IN_REQUEST: send each payment once, with its ownCustomerTransactionId.TEMPORARY_ERROR: Xtrm couldn't store the item, for example because another request running at the same time stored it first. Wait, then confirm with the item status endpoint that it isn't stored, repeating the check a few times, at least a minute apart, before you send it again. See A safe retry pattern.
#ID rules
A CustomerBatchId that breaks the ID rules refuses the whole request with INVALID_FIELD, and a CustomerTransactionId that breaks them rejects that item with INVALID_FIELD. The rules (length, characters, reserved prefixes, sanitizing and case) are in Batch and payment identifiers.
#Duplicate IDs
Xtrm stores each pair of CustomerBatchId and CustomerTransactionId at most once, so resending the same pair never stores a second item. What each kind of duplicate does is in Duplicate IDs on the Retries & idempotency page. These are the error responses a duplicate can produce:
DUPLICATE_ITEM_IN_REQUESTinRejected: the sameCustomerTransactionIdappears twice in one request. Xtrm rejects every copy.CONFLICT_DUPLICATE_ITEMinRejected: the item is already stored in this batch with a status other thanFailed, and nothing about it changed.409withCONFLICT_PROCESSINGin the top-levelKey: the whole request was refused and nothing was stored, because theCustomerBatchIdis already in use and none of its items isFailed. On a resend after a timeout, it means your first request stored payments of the batch, not that it stored all of them: the first request can have rejected some items, and Xtrm stores a batch of more than 500 payments in groups of 500. Check each payment as described in A safe retry pattern. On the very first send of a batch, it means theCustomerBatchIdis already in use, possibly by another account, becauseCustomerBatchIdvalues are shared across all Xtrm accounts. If the batch status endpoint then answers401for thatCustomerBatchId, another account used it: send your items under a newCustomerBatchId.409withStatusFailedand every item inRejected: no item was accepted, and at least one isCONFLICT_DUPLICATE_ITEM.
Log the full body of every 409, so you can tell the two forms apart.
#Submit a batch payment and handle the response
This sample submits a two-item batch and handles each outcome: no usable response, a refused request, a 409 Conflict, a 202 that stored nothing, and items rejected inside an accepted batch.
CustomerBatchId values are shared across all Xtrm accounts. Replace the sample IDs with your own unique values, for example ones that include your account number or a UUID, before you run this in the sandbox.
response=$(curl -sS --max-time 60 -w '\n%{http_code}' -X POST "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer" \
-H "Authorization: Bearer $XTRM_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-ERRORS-0001",
"Items": [
{
"CustomerTransactionId": "TXN-ERRORS-0001",
"RecipientId": "SPN8888777",
"Amount": 100,
"SendMethodId": "XTR94500",
"Destination": {
"BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995",
"BeneficiaryBankPaymentMethod": "ACH"
}
},
{
"CustomerTransactionId": "TXN-ERRORS-0002",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001"
}
}
]
}')
http_status=$(printf '%s\n' "$response" | tail -n 1)
body=$(printf '%s\n' "$response" | sed '$d')
case "$http_status" in
2??)
# Xtrm answers 202. Status is Accepted, CompletedWithFailures or Failed.
status=$(printf '%s' "$body" | grep -o '"Status"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([^"]*\)"$/\1/')
if [ "$status" = "Failed" ]; then
# TEMPORARY_ERROR: this call stored nothing. Wait, confirm, then resend the identical request.
echo "Xtrm stored nothing: $body" >&2
else
# Items in Rejected weren't stored by this request. CONFLICT_DUPLICATE_ITEM means an earlier request stored them.
rejected=$(printf '%s' "$body" | grep -o '"Rejected"[[:space:]]*:[[:space:]]*[0-9][0-9]*' | head -n 1 | grep -o '[0-9]*$')
echo "Batch received ($status). Rejected items: ${rejected:-unknown}"
echo "$body"
fi
;;
409)
# CONFLICT_PROCESSING: this CustomerBatchId is already in use, and nothing was stored.
# CONFLICT_DUPLICATE_ITEM in Rejected: those items are already stored in this batch. Follow the batch.
echo "Conflict: $body" >&2
;;
000)
# No HTTP response arrived, so the batch may or may not have been stored.
echo "No response from Xtrm. Wait, then send the same request again, with the same IDs." >&2
;;
5??)
# A server error leaves the outcome unknown, like a timeout.
echo "HTTP $http_status from Xtrm. Wait, then send the same request again, with the same IDs." >&2
;;
400)
if printf '%s' "$body" | grep -q '"BatchTransferResponse"'; then
# Refused as a whole, or every item rejected: read Key, Message and Rejected.
echo "Batch refused with HTTP 400: $body" >&2
else
# A 400 without a BatchTransferResponse body comes from an unexpected error, so the outcome is unknown.
echo "HTTP 400 from Xtrm. Wait, then send the same request again, with the same IDs." >&2
fi
;;
*)
# Refused as a whole, or every item rejected: read Key, Message and Rejected. Don't assume the body is JSON.
echo "Batch refused with HTTP $http_status: $body" >&2
;;
esaclet response;
try {
response = await fetch('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.XTRM_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
IssuerAccountNumber: 'SPN1111222',
SourceWalletId: 122181,
CustomerBatchId: 'BATCH-ERRORS-0001',
Items: [
{
CustomerTransactionId: 'TXN-ERRORS-0001',
RecipientId: 'SPN8888777',
Amount: 100,
SendMethodId: 'XTR94500',
Destination: {
BeneficiaryBankID: '41953ec32f3e4765a35a902c82bdd995',
BeneficiaryBankPaymentMethod: 'ACH',
},
},
{
CustomerTransactionId: 'TXN-ERRORS-0002',
RecipientId: 'PAT9999888',
Amount: 50,
SendMethodId: 'XTR94503',
Destination: {
Email: '[email protected]',
SKU: 'PREP9001',
},
},
],
}),
signal: AbortSignal.timeout(60_000),
});
} catch (error) {
// No HTTP response arrived (a timeout or a dropped connection), so the batch may or may not have been stored.
throw new Error(`No response from Xtrm. Wait, then send the same request again, with the same IDs. (${error.message})`);
}
const text = await response.text();
if (response.status >= 500 || (response.status === 400 && !text.includes('"BatchTransferResponse"'))) {
// A server error, or a 400 without a BatchTransferResponse body, leaves the outcome unknown, like a timeout.
throw new Error(`HTTP ${response.status} from Xtrm. Wait, then send the same request again, with the same IDs.`);
}
if (response.status === 409) {
// CONFLICT_PROCESSING: this CustomerBatchId is already in use, and nothing was stored.
// CONFLICT_DUPLICATE_ITEM in Rejected: those items are already stored in this batch. Follow the batch.
throw new Error(`Conflict: ${text}`);
}
if (!response.ok) {
// Refused as a whole, or every item rejected: read Key, Message and Rejected. Don't assume the body is JSON.
throw new Error(`Batch refused with HTTP ${response.status}: ${text}`);
}
// Xtrm answers 202. Status is Accepted, CompletedWithFailures or Failed.
const batch = JSON.parse(text).BatchTransferResponse;
if (batch.Status === 'Failed') {
// TEMPORARY_ERROR: this call stored nothing. Wait, confirm, then resend the identical request.
throw new Error(`Xtrm stored nothing: ${batch.Key} ${batch.Message}`);
}
console.log(`Batch ${batch.CustomerBatchId} (${batch.Status}): ${batch.ItemsCount.Accepted} accepted, ${batch.ItemsCount.Rejected} rejected`);
for (const item of batch.Rejected ?? []) {
// Not stored by this request. CONFLICT_DUPLICATE_ITEM means an earlier request stored it; otherwise fix the field named in Field.
console.log(`${item.CustomerTransactionId}: ${item.Key} (${item.ErrorCode}) on ${item.Field}: ${item.Message}`);
}import os
import requests
try:
response = requests.post(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer",
headers={"Authorization": f"Bearer {os.environ['XTRM_ACCESS_TOKEN']}"},
json={
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-ERRORS-0001",
"Items": [
{
"CustomerTransactionId": "TXN-ERRORS-0001",
"RecipientId": "SPN8888777",
"Amount": 100,
"SendMethodId": "XTR94500",
"Destination": {
"BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995",
"BeneficiaryBankPaymentMethod": "ACH",
},
},
{
"CustomerTransactionId": "TXN-ERRORS-0002",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001",
},
},
],
},
timeout=60,
)
except requests.exceptions.RequestException as error:
# No HTTP response arrived (a timeout or a dropped connection), so the batch may or may not have been stored.
raise RuntimeError(f"No response from Xtrm. Wait, then send the same request again, with the same IDs. ({error})") from error
if response.status_code >= 500 or (response.status_code == 400 and '"BatchTransferResponse"' not in response.text):
# A server error, or a 400 without a BatchTransferResponse body, leaves the outcome unknown, like a timeout.
raise RuntimeError(f"HTTP {response.status_code} from Xtrm. Wait, then send the same request again, with the same IDs.")
if response.status_code == 409:
# CONFLICT_PROCESSING: this CustomerBatchId is already in use, and nothing was stored.
# CONFLICT_DUPLICATE_ITEM in Rejected: those items are already stored in this batch. Follow the batch.
raise RuntimeError(f"Conflict: {response.text}")
if not 200 <= response.status_code < 300:
# Refused as a whole, or every item rejected: read Key, Message and Rejected. Don't assume the body is JSON.
raise RuntimeError(f"Batch refused with HTTP {response.status_code}: {response.text}")
# Xtrm answers 202. Status is Accepted, CompletedWithFailures or Failed.
batch = response.json()["BatchTransferResponse"]
if batch["Status"] == "Failed":
# TEMPORARY_ERROR: this call stored nothing. Wait, confirm, then resend the identical request.
raise RuntimeError(f"Xtrm stored nothing: {batch.get('Key')} {batch.get('Message')}")
counts = batch["ItemsCount"]
print(f"Batch {batch['CustomerBatchId']} ({batch['Status']}): {counts['Accepted']} accepted, {counts['Rejected']} rejected")
for item in batch.get("Rejected") or []:
# Not stored by this request. CONFLICT_DUPLICATE_ITEM means an earlier request stored it; otherwise fix the field named in Field.
print(
f"{item.get('CustomerTransactionId')}: {item.get('Key')} ({item.get('ErrorCode')}) "
f"on {item.get('Field')}: {item.get('Message')}"
)using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("XTRM_ACCESS_TOKEN"));
var json = """
{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-ERRORS-0001",
"Items": [
{
"CustomerTransactionId": "TXN-ERRORS-0001",
"RecipientId": "SPN8888777",
"Amount": 100,
"SendMethodId": "XTR94500",
"Destination": {
"BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995",
"BeneficiaryBankPaymentMethod": "ACH"
}
},
{
"CustomerTransactionId": "TXN-ERRORS-0002",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001"
}
}
]
}
""";
HttpResponseMessage response;
try
{
response = await client.PostAsync(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer",
new StringContent(json, Encoding.UTF8, "application/json"));
}
catch (Exception error) when (error is HttpRequestException or TaskCanceledException)
{
// No HTTP response arrived (a timeout or a dropped connection), so the batch may or may not have been stored.
throw new Exception($"No response from Xtrm. Wait, then send the same request again, with the same IDs. ({error.Message})", error);
}
var body = await response.Content.ReadAsStringAsync();
if ((int)response.StatusCode >= 500
|| (response.StatusCode == HttpStatusCode.BadRequest && !body.Contains("\"BatchTransferResponse\"")))
{
// A server error, or a 400 without a BatchTransferResponse body, leaves the outcome unknown, like a timeout.
throw new Exception($"HTTP {(int)response.StatusCode} from Xtrm. Wait, then send the same request again, with the same IDs.");
}
if (response.StatusCode == HttpStatusCode.Conflict)
{
// CONFLICT_PROCESSING: this CustomerBatchId is already in use, and nothing was stored.
// CONFLICT_DUPLICATE_ITEM in Rejected: those items are already stored in this batch. Follow the batch.
throw new Exception($"Conflict: {body}");
}
if (!response.IsSuccessStatusCode)
{
// Refused as a whole, or every item rejected: read Key, Message and Rejected. Don't assume the body is JSON.
throw new Exception($"Batch refused with HTTP {(int)response.StatusCode}: {body}");
}
// Xtrm answers 202. Status is Accepted, CompletedWithFailures or Failed.
using var document = JsonDocument.Parse(body);
var batch = document.RootElement.GetProperty("BatchTransferResponse");
if (Text(batch, "Status") == "Failed")
{
// TEMPORARY_ERROR: this call stored nothing. Wait, confirm, then resend the identical request.
throw new Exception($"Xtrm stored nothing: {Text(batch, "Key")} {Text(batch, "Message")}");
}
var counts = batch.GetProperty("ItemsCount");
Console.WriteLine($"Batch {Text(batch, "CustomerBatchId")} ({Text(batch, "Status")}): {Text(counts, "Accepted")} accepted, {Text(counts, "Rejected")} rejected");
if (batch.TryGetProperty("Rejected", out var rejected) && rejected.ValueKind == JsonValueKind.Array)
{
foreach (var item in rejected.EnumerateArray())
{
// Not stored by this request. CONFLICT_DUPLICATE_ITEM means an earlier request stored it; otherwise fix the field named in Field.
Console.WriteLine($"{Text(item, "CustomerTransactionId")}: {Text(item, "Key")} ({Text(item, "ErrorCode")}) on {Text(item, "Field")}: {Text(item, "Message")}");
}
}
// Reads a property as text, whether it arrives as a string or a number.
static string Text(JsonElement element, string name) =>
element.TryGetProperty(name, out var value)
? (value.ValueKind == JsonValueKind.String ? value.GetString() ?? "" : value.GetRawText())
: "";// Reads the response with Jackson (com.fasterxml.jackson.core:jackson-databind).
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
String json = """
{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-ERRORS-0001",
"Items": [
{
"CustomerTransactionId": "TXN-ERRORS-0001",
"RecipientId": "SPN8888777",
"Amount": 100,
"SendMethodId": "XTR94500",
"Destination": {
"BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995",
"BeneficiaryBankPaymentMethod": "ACH"
}
},
{
"CustomerTransactionId": "TXN-ERRORS-0002",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001"
}
}
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer"))
.timeout(Duration.ofSeconds(60))
.header("Authorization", "Bearer " + System.getenv("XTRM_ACCESS_TOKEN"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response;
try {
response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException error) {
// No HTTP response arrived (a timeout or a dropped connection), so the batch may or may not have been stored.
throw new RuntimeException("No response from Xtrm. Wait, then send the same request again, with the same IDs. ("
+ error.getMessage() + ")", error);
}
if (response.statusCode() >= 500
|| (response.statusCode() == 400 && !response.body().contains("\"BatchTransferResponse\""))) {
// A server error, or a 400 without a BatchTransferResponse body, leaves the outcome unknown, like a timeout.
throw new RuntimeException("HTTP " + response.statusCode() + " from Xtrm. Wait, then send the same request again, with the same IDs.");
}
if (response.statusCode() == 409) {
// CONFLICT_PROCESSING: this CustomerBatchId is already in use, and nothing was stored.
// CONFLICT_DUPLICATE_ITEM in Rejected: those items are already stored in this batch. Follow the batch.
throw new RuntimeException("Conflict: " + response.body());
}
if (response.statusCode() < 200 || response.statusCode() >= 300) {
// Refused as a whole, or every item rejected: read Key, Message and Rejected. Don't assume the body is JSON.
throw new RuntimeException("Batch refused with HTTP " + response.statusCode() + ": " + response.body());
}
// Xtrm answers 202. Status is Accepted, CompletedWithFailures or Failed.
JsonNode batch = new ObjectMapper().readTree(response.body()).path("BatchTransferResponse");
if (batch.path("Status").asText().equals("Failed")) {
// TEMPORARY_ERROR: this call stored nothing. Wait, confirm, then resend the identical request.
throw new RuntimeException("Xtrm stored nothing: " + batch.path("Key").asText() + " " + batch.path("Message").asText());
}
System.out.println("Batch " + batch.path("CustomerBatchId").asText() + " (" + batch.path("Status").asText() + "): "
+ batch.path("ItemsCount").path("Accepted").asText() + " accepted, "
+ batch.path("ItemsCount").path("Rejected").asText() + " rejected");
for (JsonNode item : batch.path("Rejected")) {
// Not stored by this request. CONFLICT_DUPLICATE_ITEM means an earlier request stored it; otherwise fix the field named in Field.
System.out.println(item.path("CustomerTransactionId").asText() + ": " + item.path("Key").asText()
+ " (" + item.path("ErrorCode").asText() + ") on " + item.path("Field").asText()
+ ": " + item.path("Message").asText());
}<?php
$ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
'IssuerAccountNumber' => 'SPN1111222',
'SourceWalletId' => 122181,
'CustomerBatchId' => 'BATCH-ERRORS-0001',
'Items' => [
[
'CustomerTransactionId' => 'TXN-ERRORS-0001',
'RecipientId' => 'SPN8888777',
'Amount' => 100,
'SendMethodId' => 'XTR94500',
'Destination' => [
'BeneficiaryBankID' => '41953ec32f3e4765a35a902c82bdd995',
'BeneficiaryBankPaymentMethod' => 'ACH',
],
],
[
'CustomerTransactionId' => 'TXN-ERRORS-0002',
'RecipientId' => 'PAT9999888',
'Amount' => 50,
'SendMethodId' => 'XTR94503',
'Destination' => [
'Email' => '[email protected]',
'SKU' => 'PREP9001',
],
],
],
]),
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'),
'Content-Type: application/json',
],
]);
$body = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false) {
// No HTTP response arrived (a timeout or a dropped connection), so the batch may or may not have been stored.
throw new RuntimeException('No response from Xtrm. Wait, then send the same request again, with the same IDs. (' . curl_error($ch) . ')');
}
if ($httpStatus >= 500 || ($httpStatus === 400 && !str_contains($body, '"BatchTransferResponse"'))) {
// A server error, or a 400 without a BatchTransferResponse body, leaves the outcome unknown, like a timeout.
throw new RuntimeException("HTTP $httpStatus from Xtrm. Wait, then send the same request again, with the same IDs.");
}
if ($httpStatus === 409) {
// CONFLICT_PROCESSING: this CustomerBatchId is already in use, and nothing was stored.
// CONFLICT_DUPLICATE_ITEM in Rejected: those items are already stored in this batch. Follow the batch.
throw new RuntimeException("Conflict: $body");
}
if ($httpStatus < 200 || $httpStatus >= 300) {
// Refused as a whole, or every item rejected: read Key, Message and Rejected. Don't assume the body is JSON.
throw new RuntimeException("Batch refused with HTTP $httpStatus: $body");
}
// Xtrm answers 202. Status is Accepted, CompletedWithFailures or Failed.
$batch = json_decode($body, true)['BatchTransferResponse'];
if (($batch['Status'] ?? '') === 'Failed') {
// TEMPORARY_ERROR: this call stored nothing. Wait, confirm, then resend the identical request.
throw new RuntimeException('Xtrm stored nothing: ' . ($batch['Key'] ?? '') . ' ' . ($batch['Message'] ?? ''));
}
printf(
"Batch %s (%s): %s accepted, %s rejected\n",
$batch['CustomerBatchId'],
$batch['Status'],
$batch['ItemsCount']['Accepted'],
$batch['ItemsCount']['Rejected']
);
foreach ($batch['Rejected'] ?? [] as $item) {
// Not stored by this request. CONFLICT_DUPLICATE_ITEM means an earlier request stored it; otherwise fix the field named in Field.
printf(
"%s: %s (%s) on %s: %s\n",
$item['CustomerTransactionId'] ?? '',
$item['Key'] ?? '',
$item['ErrorCode'] ?? '',
$item['Field'] ?? '',
$item['Message'] ?? ''
);
}#Errors during processing
Xtrm processes accepted items asynchronously, in stages: it validates each item, debits your source wallet and credits the recipient's wallet, and then, for every send method other than a wallet, delivers the money from the recipient's wallet to the destination (wallet-first delivery). Each attempt with an outcome is recorded in the item's Attempts array, with a Result (Success or Failed) and an ErrorCode (SUCCESS when the attempt succeeds). The item's Status gives its current state. You can read these in three places:
- Batch status: every item in the batch, page by page. Set
historytotrueto get each item's attempts; otherwiseAttemptsis empty. - Item status: one item. Set
historytotrueto get its attempts. - Webhooks:
Batch.Item.Failedcarries theErrorCodeof an item that failed validation or the wallet credit. A failed delivery sendsBatch.Item.CompletedwithDeliveryTypeWalletinstead. A webhook's status doesn't always match the item's status, so confirm final statuses with the status endpoints.
A failed delivery isn't a Failed item. Your source wallet is debited Amount plus the fee when the recipient's wallet is credited, before the delivery to the destination. A bank, card, check, gift card or prepaid payment then shows RetainedInWallet while Xtrm delivers it, usually only briefly, and moves on to Success when the delivery goes through. If the delivery fails, the item stays RetainedInWallet, with a Failed attempt: the money is in the recipient's Xtrm wallet, so you can't retry or resubmit the item, and the fee isn't refunded. Don't act on RetainedInWallet while the batch is still Processing: the item has stuck only once the batch status is final. We recommend handling a stuck RetainedInWallet item separately from both Success and Failed; see When a payment stays RetainedInWallet.
Decide with the item's Status, not with an attempt's ErrorCode. An error code describes one attempt. For example, when attempt 1 fails with INSUFFICIENT_BALANCE and attempt 2, resubmitted after you fund the source wallet, succeeds, the item's Status is Success. To find the newest attempt, take the one with the highest AttemptNo: the batch status endpoint lists attempts newest first, and the item status endpoint oldest first.
#Run-time error codes
Each failed attempt carries an ErrorCode. What it means for the item depends on the stage where it failed:
- Validation, before any money moves: the item becomes
Failed, and Xtrm sendsBatch.Item.Failed. You can resubmit it after you fix the cause. - Wallet credit, when Xtrm debits your source wallet and credits the recipient's wallet: the item becomes
Failed, and Xtrm sendsBatch.Item.Failed. Your source wallet isn't debited, except that afterTEMPORARY_ERRORthe money may already have moved. - Delivery from the recipient's wallet: the attempt is
Failed, and the item staysRetainedInWallet, which you can't resubmit. Xtrm sendsBatch.Item.CompletedwithDeliveryTypeWallet, notBatch.Item.Failed.
Common codes are INSUFFICIENT_BALANCE, RECIPIENT_NOT_FOUND, BANKID_INVALID and SKU_NOT_FOUND. For every code and what to do, see Error codes on attempts.
#Resubmit failed items
To retry a Failed item, fix the cause, then resubmit it under the same CustomerBatchId and CustomerTransactionId, with every field. For example, fund the source wallet after INSUFFICIENT_BALANCE, or correct Destination.BeneficiaryBankID after BANKID_INVALID. Its next attempt gets the next AttemptNo. Any other item you include comes back in Rejected as CONFLICT_DUPLICATE_ITEM and nothing about it changes, and a request with no Failed item in its batch gets 409 CONFLICT_PROCESSING. An item that stays RetainedInWallet can't be resubmitted (see When a payment stays RetainedInWallet), and before you retry an item whose newest attempt is TEMPORARY_ERROR, check with Xtrm support: the money may already have moved.
Retry a batch payment covers what a resubmission does for each status and which fields you can change, and A safe retry pattern covers resending after a timeout.
#Errors when you check status
The batch status and item status endpoints return the status object at the root of the body, with no OperationStatus. When a request fails, the body has the form {"StatusCode": …, "Message": …}, with an ErrorKey added for 400, 413 and 422. Token errors have the {"error": …, "error_message": …} body described in Authentication errors. These are their error responses:
| HTTP status | ErrorKey | Endpoint | Cause |
|---|---|---|---|
400 | INVALID_PAGINATION | Batch status | recordsToSkip is negative, recordsToTake is 0 or negative, or history isn't true or false. |
400 | INVALID_PARAMETER | Item status | history isn't true or false (History value is malformed.). |
401 | None | Both | The batch was created under an IssuerAccountNumber your token can't act for. Because CustomerBatchId values are shared across all Xtrm accounts, this also tells you that another account used the ID. |
401 | None (error instead) | Both | The token is missing, empty, unrecognized, revoked or expired, doesn't use the Bearer scheme, or comes from an IP address your company doesn't allow. See Authentication errors. |
404 | None | Both | No account has a batch with this CustomerBatchId (Unknown CustomerBatchId.), or, for item status, the batch has no stored item with this CustomerTransactionId (CustomerTransactionId not found within the specified batch.). A failed database read while Xtrm looks up the batch or the item returns the same 404, so it can be temporary. |
413 | LIMIT_EXCEEDED | Both | The response would be larger than your account's response-size limit. For batch status, lower recordsToTake; for either endpoint, leave out history. |
422 | LIMIT_EXCEEDED | Batch status | recordsToTake is over your account's maximum, which Message states. |
500 | None | Both | There has been a temporary error. Please try again later. The error is temporary: repeat the check. |
A 404 from either endpoint doesn't prove that a batch or a payment is missing. Besides a failed database read, there's timing: right after a submit call times out, the item endpoint can return 404 while the original request is still storing the batch. Repeat the check a few times, at least a minute apart, before you conclude that a payment wasn't stored, and then follow A safe retry pattern to submit it.
This sample reads TXN-ERRORS-0001, the bank transfer item from the batch above, with its attempt history. It finds the latest attempt and reports the item's outcome. A 404 or 5xx gets a reminder to repeat the check. For a RetainedInWallet item, it also reads the batch status: while the batch is Processing, the delivery is still under way. Once the batch status is final, the sample reads the item again, because the delivery can finish between the two reads: an item that is still RetainedInWallet has stuck.
response=$(curl -sS -w '\n%{http_code}' -X GET "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001?history=true" \
-H "Authorization: Bearer $XTRM_ACCESS_TOKEN")
http_status=$(printf '%s\n' "$response" | tail -n 1)
body=$(printf '%s\n' "$response" | sed '$d')
if [ "$http_status" = "404" ] || [ "$http_status" -ge 500 ]; then
# Can be temporary: repeat the check a few times, at least a minute apart, before you treat the item as missing.
echo "HTTP $http_status: $body (can be temporary: repeat the check a few times, at least a minute apart)" >&2
elif [ "$http_status" -lt 200 ] || [ "$http_status" -ge 300 ]; then
echo "HTTP $http_status: $body" >&2
else
# The item's Status is the only "Status" key in this response; attempts use "Result".
status=$(printf '%s' "$body" | grep -o '"Status"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([^"]*\)"$/\1/')
echo "Item status: $status"
# Each attempt has its own ErrorCode. Use a JSON tool such as jq to pick the highest AttemptNo.
echo "Attempt error codes:"
printf '%s' "$body" | grep -o '"ErrorCode"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"\([^"]*\)"$/ \1/' || true
if [ "$status" = "RetainedInWallet" ]; then
# RetainedInWallet passes through on the way to the destination: read the batch status to tell.
batch=$(curl -sS -f "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001?recordsToSkip=0&recordsToTake=1" \
-H "Authorization: Bearer $XTRM_ACCESS_TOKEN")
# In the batch response, the first Status is the batch's.
batch_status=$(printf '%s' "$batch" | grep -o '"Status"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([^"]*\)"$/\1/')
case "$batch_status" in
Processing)
echo "RetainedInWallet while the batch is Processing: the delivery is still under way. Check again later." ;;
Completed | CompletedWithFailures | Failed)
# The delivery can finish between the two reads, so read the item again.
again=$(curl -sS -f "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001" \
-H "Authorization: Bearer $XTRM_ACCESS_TOKEN")
again_status=$(printf '%s' "$again" | grep -o '"Status"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([^"]*\)"$/\1/')
if [ "$again_status" = "RetainedInWallet" ]; then
echo "RetainedInWallet after the batch finished: the delivery didn't go through. The money is in the recipient's Xtrm wallet."
elif [ -n "$again_status" ]; then
echo "The delivery finished in the meantime: the item is now $again_status."
else
echo "Couldn't read the item again. Check it again later." >&2
fi ;;
*)
echo "Couldn't read the batch status. Check it again later." >&2 ;;
esac
fi
ficonst headers = {
Authorization: `Bearer ${process.env.XTRM_ACCESS_TOKEN}`,
};
const response = await fetch('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001?history=true', {
method: 'GET',
headers,
});
const text = await response.text();
if (response.status === 404 || response.status >= 500) {
// Can be temporary: repeat the check a few times, at least a minute apart, before you treat the item as missing.
throw new Error(`HTTP ${response.status}: ${text} (can be temporary: repeat the check a few times, at least a minute apart)`);
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${text}`);
}
const item = JSON.parse(text);
// Attempts are not always listed in the same order: take the highest AttemptNo.
const latest = (item.Attempts ?? []).reduce((best, a) => (!best || a.AttemptNo > best.AttemptNo ? a : best), null);
console.log(`${item.CustomerTransactionId}: ${item.Status}`);
if (latest) {
console.log(`Attempt ${latest.AttemptNo}: ${latest.Result} (${latest.ErrorCode})`);
}
if (item.Status === 'Failed') {
// React to the latest ErrorCode, for example fund the source wallet after INSUFFICIENT_BALANCE.
console.log(`The item failed with ${latest ? latest.ErrorCode : 'no error code'}.`);
} else if (item.Status === 'RetainedInWallet') {
// RetainedInWallet passes through on the way to the destination: read the batch status to tell.
const batchResponse = await fetch('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001?recordsToSkip=0&recordsToTake=1', {
method: 'GET',
headers,
});
if (!batchResponse.ok) {
throw new Error(`HTTP ${batchResponse.status}: ${await batchResponse.text()}`);
}
const batch = await batchResponse.json();
if (batch.Status === 'Processing') {
console.log('RetainedInWallet while the batch is Processing: the delivery is still under way. Check again later.');
} else {
// The delivery can finish between the two reads, so read the item again.
const againResponse = await fetch('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001', {
method: 'GET',
headers,
});
if (!againResponse.ok) {
throw new Error(`HTTP ${againResponse.status}: ${await againResponse.text()}`);
}
const again = await againResponse.json();
if (again.Status === 'RetainedInWallet') {
console.log("RetainedInWallet after the batch finished: the delivery didn't go through. The money is in the recipient's Xtrm wallet.");
} else {
console.log(`The delivery finished in the meantime: the item is now ${again.Status}.`);
}
}
}import os
import requests
headers = {"Authorization": f"Bearer {os.environ['XTRM_ACCESS_TOKEN']}"}
response = requests.get(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001?history=true",
headers=headers,
)
if response.status_code == 404 or response.status_code >= 500:
# Can be temporary: repeat the check a few times, at least a minute apart, before you treat the item as missing.
raise RuntimeError(
f"HTTP {response.status_code}: {response.text} "
"(can be temporary: repeat the check a few times, at least a minute apart)"
)
if not 200 <= response.status_code < 300:
raise RuntimeError(f"HTTP {response.status_code}: {response.text}")
item = response.json()
# Attempts are not always listed in the same order: take the highest AttemptNo.
attempts = item.get("Attempts") or []
latest = max(attempts, key=lambda a: a["AttemptNo"]) if attempts else None
print(f"{item['CustomerTransactionId']}: {item['Status']}")
if latest:
print(f"Attempt {latest['AttemptNo']}: {latest['Result']} ({latest['ErrorCode']})")
if item["Status"] == "Failed":
# React to the latest ErrorCode, for example fund the source wallet after INSUFFICIENT_BALANCE.
print(f"The item failed with {latest['ErrorCode'] if latest else 'no error code'}.")
elif item["Status"] == "RetainedInWallet":
# RetainedInWallet passes through on the way to the destination: read the batch status to tell.
batch_response = requests.get(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001?recordsToSkip=0&recordsToTake=1",
headers=headers,
)
if not 200 <= batch_response.status_code < 300:
raise RuntimeError(f"HTTP {batch_response.status_code}: {batch_response.text}")
if batch_response.json()["Status"] == "Processing":
print("RetainedInWallet while the batch is Processing: the delivery is still under way. Check again later.")
else:
# The delivery can finish between the two reads, so read the item again.
again_response = requests.get(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001",
headers=headers,
)
if not 200 <= again_response.status_code < 300:
raise RuntimeError(f"HTTP {again_response.status_code}: {again_response.text}")
again_status = again_response.json()["Status"]
if again_status == "RetainedInWallet":
print("RetainedInWallet after the batch finished: the delivery didn't go through. The money is in the recipient's Xtrm wallet.")
else:
print(f"The delivery finished in the meantime: the item is now {again_status}.")using System.Net.Http.Headers;
using System.Text.Json;
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("XTRM_ACCESS_TOKEN"));
var response = await client.GetAsync("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001?history=true");
var body = await response.Content.ReadAsStringAsync();
if ((int)response.StatusCode == 404 || (int)response.StatusCode >= 500)
{
// Can be temporary: repeat the check a few times, at least a minute apart, before you treat the item as missing.
throw new Exception($"HTTP {(int)response.StatusCode}: {body} " +
"(can be temporary: repeat the check a few times, at least a minute apart)");
}
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTTP {(int)response.StatusCode}: {body}");
}
using var document = JsonDocument.Parse(body);
var item = document.RootElement;
var status = item.GetProperty("Status").GetString();
// Attempts are not always listed in the same order: take the highest AttemptNo.
JsonElement? latest = null;
if (item.TryGetProperty("Attempts", out var attempts) && attempts.ValueKind == JsonValueKind.Array)
{
foreach (var attempt in attempts.EnumerateArray())
{
if (latest is not JsonElement current
|| attempt.GetProperty("AttemptNo").GetInt32() > current.GetProperty("AttemptNo").GetInt32())
{
latest = attempt;
}
}
}
Console.WriteLine($"{item.GetProperty("CustomerTransactionId").GetString()}: {status}");
if (latest is JsonElement last)
{
Console.WriteLine($"Attempt {last.GetProperty("AttemptNo").GetInt32()}: {last.GetProperty("Result").GetString()} ({last.GetProperty("ErrorCode").GetString()})");
}
if (status == "Failed")
{
// React to the latest ErrorCode, for example fund the source wallet after INSUFFICIENT_BALANCE.
Console.WriteLine($"The item failed with {(latest is JsonElement l ? l.GetProperty("ErrorCode").GetString() : "no error code")}.");
}
else if (status == "RetainedInWallet")
{
// RetainedInWallet passes through on the way to the destination: read the batch status to tell.
var batchResponse = await client.GetAsync("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001?recordsToSkip=0&recordsToTake=1");
var batchBody = await batchResponse.Content.ReadAsStringAsync();
if (!batchResponse.IsSuccessStatusCode)
{
throw new Exception($"HTTP {(int)batchResponse.StatusCode}: {batchBody}");
}
using var batchDocument = JsonDocument.Parse(batchBody);
if (batchDocument.RootElement.GetProperty("Status").GetString() == "Processing")
{
Console.WriteLine("RetainedInWallet while the batch is Processing: the delivery is still under way. Check again later.");
}
else
{
// The delivery can finish between the two reads, so read the item again.
var againResponse = await client.GetAsync("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001");
var againBody = await againResponse.Content.ReadAsStringAsync();
if (!againResponse.IsSuccessStatusCode)
{
throw new Exception($"HTTP {(int)againResponse.StatusCode}: {againBody}");
}
using var againDocument = JsonDocument.Parse(againBody);
var againStatus = againDocument.RootElement.GetProperty("Status").GetString();
if (againStatus == "RetainedInWallet")
{
Console.WriteLine("RetainedInWallet after the batch finished: the delivery didn't go through. The money is in the recipient's Xtrm wallet.");
}
else
{
Console.WriteLine($"The delivery finished in the meantime: the item is now {againStatus}.");
}
}
}// Reads the response with Jackson (com.fasterxml.jackson.core:jackson-databind).
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001?history=true"))
.header("Authorization", "Bearer " + System.getenv("XTRM_ACCESS_TOKEN"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 404 || response.statusCode() >= 500) {
// Can be temporary: repeat the check a few times, at least a minute apart, before you treat the item as missing.
throw new RuntimeException("HTTP " + response.statusCode() + ": " + response.body()
+ " (can be temporary: repeat the check a few times, at least a minute apart)");
}
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new RuntimeException("HTTP " + response.statusCode() + ": " + response.body());
}
JsonNode item = new ObjectMapper().readTree(response.body());
String status = item.path("Status").asText();
// Attempts are not always listed in the same order: take the highest AttemptNo.
JsonNode latest = null;
for (JsonNode attempt : item.path("Attempts")) {
if (latest == null || attempt.path("AttemptNo").asInt() > latest.path("AttemptNo").asInt()) {
latest = attempt;
}
}
System.out.println(item.path("CustomerTransactionId").asText() + ": " + status);
if (latest != null) {
System.out.println("Attempt " + latest.path("AttemptNo").asInt() + ": "
+ latest.path("Result").asText() + " (" + latest.path("ErrorCode").asText() + ")");
}
if (status.equals("Failed")) {
// React to the latest ErrorCode, for example fund the source wallet after INSUFFICIENT_BALANCE.
System.out.println("The item failed with "
+ (latest != null ? latest.path("ErrorCode").asText() : "no error code") + ".");
} else if (status.equals("RetainedInWallet")) {
// RetainedInWallet passes through on the way to the destination: read the batch status to tell.
HttpRequest batchRequest = HttpRequest.newBuilder()
.uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001?recordsToSkip=0&recordsToTake=1"))
.header("Authorization", "Bearer " + System.getenv("XTRM_ACCESS_TOKEN"))
.GET()
.build();
HttpResponse<String> batchResponse = client.send(batchRequest, HttpResponse.BodyHandlers.ofString());
if (batchResponse.statusCode() < 200 || batchResponse.statusCode() >= 300) {
throw new RuntimeException("HTTP " + batchResponse.statusCode() + ": " + batchResponse.body());
}
if (new ObjectMapper().readTree(batchResponse.body()).path("Status").asText().equals("Processing")) {
System.out.println("RetainedInWallet while the batch is Processing: the delivery is still under way. Check again later.");
} else {
// The delivery can finish between the two reads, so read the item again.
HttpRequest againRequest = HttpRequest.newBuilder()
.uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001"))
.header("Authorization", "Bearer " + System.getenv("XTRM_ACCESS_TOKEN"))
.GET()
.build();
HttpResponse<String> againResponse = client.send(againRequest, HttpResponse.BodyHandlers.ofString());
if (againResponse.statusCode() < 200 || againResponse.statusCode() >= 300) {
throw new RuntimeException("HTTP " + againResponse.statusCode() + ": " + againResponse.body());
}
String againStatus = new ObjectMapper().readTree(againResponse.body()).path("Status").asText();
if (againStatus.equals("RetainedInWallet")) {
System.out.println("RetainedInWallet after the batch finished: the delivery didn't go through. The money is in the recipient's Xtrm wallet.");
} else {
System.out.println("The delivery finished in the meantime: the item is now " + againStatus + ".");
}
}
}<?php
$ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001?history=true');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'),
],
]);
$body = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body !== false && ($httpStatus === 404 || $httpStatus >= 500)) {
// Can be temporary: repeat the check a few times, at least a minute apart, before you treat the item as missing.
throw new RuntimeException("HTTP $httpStatus: $body (can be temporary: repeat the check a few times, at least a minute apart)");
}
if ($body === false || $httpStatus < 200 || $httpStatus >= 300) {
throw new RuntimeException("HTTP $httpStatus: " . ($body === false ? curl_error($ch) : $body));
}
$item = json_decode($body, true);
// Attempts are not always listed in the same order: take the highest AttemptNo.
$latest = null;
foreach ($item['Attempts'] ?? [] as $attempt) {
if ($latest === null || $attempt['AttemptNo'] > $latest['AttemptNo']) {
$latest = $attempt;
}
}
echo "{$item['CustomerTransactionId']}: {$item['Status']}\n";
if ($latest !== null) {
echo "Attempt {$latest['AttemptNo']}: {$latest['Result']} ({$latest['ErrorCode']})\n";
}
if ($item['Status'] === 'Failed') {
// React to the latest ErrorCode, for example fund the source wallet after INSUFFICIENT_BALANCE.
echo 'The item failed with ' . ($latest['ErrorCode'] ?? 'no error code') . ".\n";
} elseif ($item['Status'] === 'RetainedInWallet') {
// RetainedInWallet passes through on the way to the destination: read the batch status to tell.
$ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001?recordsToSkip=0&recordsToTake=1');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'),
],
]);
$batchBody = curl_exec($ch);
$batchStatus = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($batchBody === false || $batchStatus < 200 || $batchStatus >= 300) {
throw new RuntimeException("HTTP $batchStatus: " . ($batchBody === false ? curl_error($ch) : $batchBody));
}
if (json_decode($batchBody, true)['Status'] === 'Processing') {
echo "RetainedInWallet while the batch is Processing: the delivery is still under way. Check again later.\n";
} else {
// The delivery can finish between the two reads, so read the item again.
$ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-ERRORS-0001/Items/TXN-ERRORS-0001');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'),
],
]);
$againBody = curl_exec($ch);
$againHttpStatus = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($againBody === false || $againHttpStatus < 200 || $againHttpStatus >= 300) {
throw new RuntimeException("HTTP $againHttpStatus: " . ($againBody === false ? curl_error($ch) : $againBody));
}
$againStatus = json_decode($againBody, true)['Status'];
if ($againStatus === 'RetainedInWallet') {
echo "RetainedInWallet after the batch finished: the delivery didn't go through. The money is in the recipient's Xtrm wallet.\n";
} else {
echo "The delivery finished in the meantime: the item is now $againStatus.\n";
}
}
}#Authentication errors
Batch payment endpoints. Every batch payment call needs a valid bearer token. When the token check fails, Xtrm answers 401 with a body of the form {"error": …, "error_message": …}:
| Case | error | error_message |
|---|---|---|
No Authorization header | invalid_authorization | Authorization is missing |
The scheme isn't Bearer | invalid_authentication_type | The authentication type should be bearer |
| Empty token | invalid_credentials | Missing credentials |
| Unrecognized or revoked token, or a call from an IP address that your company doesn't allow | invalid_authorization | Not authorized to view/access this resource |
| Expired token | invalid_token | The Token has expired |
A valid token must also be allowed to act for the account concerned. On a submission, a token that can't act for IssuerAccountNumber gets 401 with Key Unauthorized. On a status request, a batch created under an IssuerAccountNumber your token can't act for gets 401 with no key. The batch payment endpoints never answer 403 for a token or scope problem: their only 403 is FORBIDDEN, from the source-wallet check, which also fails when the account in IssuerAccountNumber isn't active. Xtrm checks the token before it stores anything, so after a 401 you can get a new token and submit the same batch again.
Other endpoints. Every call with a bearer token goes through the same token check, so the endpoints outside batch payments answer a missing, unrecognized or expired token, or a call from an IP address your company doesn't allow, with the same 401 responses. The token endpoint answers a failed token request with HTTP 400 and a body of the form {"error": …, "error_description": …}: for example invalid_credentials (Credentials are invalid.) when the client credentials aren't valid, invalid_grant for a refresh_token that Xtrm doesn't accept, and unsupported_grant_type for a grant_type that Xtrm doesn't support.
Token lifetime. Access and refresh tokens expire; Token lifetime and expiry says when, and how to renew them. When a refresh_token grant returns 400 with invalid_grant, get a new token with grant_type=password.
When a call fails and your token may have expired, we recommend getting a new token and trying once more. If a fresh token still fails, check that your server's IP address is allowlisted and that you use the credentials for the right environment (the sandbox is completely separate from production), then contact [email protected]. See Authentication and Sandbox & environments.
#Other endpoints: the OperationStatus envelope
The endpoints outside batch payments, such as wallets, recipients, bank accounts, recipient transfers and funding, wrap their payload in a response object and a result object, and put an OperationStatus object inside the result. A successful call returns HTTP 200 with Success set to true. Validation and business failures return HTTP 400 with the same envelope and Success set to false. There are two exceptions. The one-time password steps of a recipient transfer return HTTP 200, even when the password is wrong. The first call of a mobile-number change on UpdateUser returns HTTP 400 with Success set to true, because Xtrm has texted a one-time password to the new number. So check both the HTTP status and OperationStatus.Success on every call.
HTTP 200 does not mean the call succeeded
A wrong or expired one-time password on UserWithdrawFund or BeneficiaryCompanyWithdrawFund comes back with HTTP 200 and OperationStatus.Success set to false. Check Success on every response before you act on it, not only the HTTP status. On these two endpoints, Success: true doesn't prove a transfer either: the first request, which only sends the code, returns it too. The transfer is made only when the response has PaymentStatus Completed and a PaymentTransactionId.
#The OperationStatus object
This is the response to a successful CreateUser call:
{
"CreateUserResponse": {
"CreateUserResult": {
"UserID": "PAT9999888",
"AccountIdentityLevel": "Standard",
"OperationStatus": {
"Success": true,
"Errors": null
}
}
}
}| Field | Type | What it tells you |
|---|---|---|
Success | boolean | Whether the operation succeeded (true) or failed (false). We recommend deciding success or failure with this field. |
Errors | varies | Validation or execution error details when the call fails. On success it's empty, but the empty value varies by endpoint (see below). |
Two things vary between endpoints, so don't hard-code them:
- Wrapper names. They often differ from the operation name, sometimes with typos. For example,
GetUserWalletBalancereturnsUserWalletBalnceResponse>UserWalletBalanceResult. FindOperationStatusby searching for the key rather than by a fixed path. See Requests & responses. - Key order.
Successcomes beforeErrorson some endpoints and after it on others.
#Errors on a successful call
On success, Errors is empty, but endpoints express "empty" in three different ways:
Errors on success | Endpoints |
|---|---|
null | Most endpoints, for example GetCompanyWallets, CreateUser, GetBankWithdrawTypes, LinkACHDebitBankBeneficiary, ReleaseACHDebitMicrodeposit, VerifyACHDebitMicrodeposit, FundCompanyWalletUsingCreditCard and FundWalletUsingACHDebit |
[] | DeleteBankBeneficiary, DeleteCard, CreateBeneficiary, UpdateBeneficiary, TransferTaxInformation, UserWithdrawFund, BeneficiaryCompanyWithdrawFund |
[""], an array holding one empty string | GetBeneficiaries, GetEntities, GetPrograms, ProgramCategory, ProgramType |
A non-empty Errors is therefore not a failure: [""] has one element on a successful call. Decide with Success, and treat Errors as detail: it explains a failure, and on a one-time password step it carries the message that a code was sent. On the two recipient transfer endpoints, also check that the transfer was made (see Check every response the same way). When you read it, we recommend normalizing it first: drop null, [] and empty strings, and keep whatever is left.
#Errors on a failed call
On a failed call, Errors is an array of strings, one message per problem: for example Issuer Account Number is Mandatory for a missing field, or CountryISO2 is invalid. Bank linking is the exception. When LinkBankBeneficiary or LinkACHDebitBankBeneficiary needs more information, Errors is an array of objects instead, each with an ErrorMessage, the FieldName and FieldLabel of a field to add or fix (for example RoutingNumber and Routing Number), IsRegulatoryField and valueset. On LinkBankBeneficiary, valueset lists the values a missing regulatory field accepts, each with an id and a text; otherwise it's null. Their other failures return strings.
We recommend logging the complete Errors value and the raw response body for every failure.
#HTTP status codes
| HTTP status | When | Body |
|---|---|---|
200 | The call succeeded, or one of the one-time password steps of UserWithdrawFund and BeneficiaryCompanyWithdrawFund (see Check every response the same way) | The envelope. Check Success. |
400 | A validation or business failure, such as a missing or invalid field, or a bank link that needs more information. Also the first call of a mobile-number change on UpdateUser, which sends a one-time password | The envelope, with Success false and the reasons in Errors. For that UpdateUser call, Success is true and Errors holds One Time Password sent to user. Please resubmit with One Time Password. An unexpected error that the endpoint doesn't catch returns {"Error": false, "StatusCode": 400, "Message": …} instead. |
401 | The token is fine, but it isn't allowed to act for the IssuerAccountNumber you sent | The envelope, with Errors ["Not authorized to access this resource."] |
401 | A token or IP address problem | {"error": …, "error_message": …}, as in Authentication errors |
404 | A path or API version that doesn't exist, or a GET to an endpoint that accepts only POST | {"StatusCode": 404, "Message": "The requested resource is not found"}, with no OperationStatus |
409 | Your company is already connected to the account, on GetOTPAuthorizedVendor and ValidateOTPAuthorizeVendor | The envelope, with Errors ["Already authorized vendor to access this resource"] |
415 | A POST without a supported Content-Type | {"error": "invalid_media_type", "error_message": …} |
500 | An unexpected error (some endpoints return 400 instead) | The envelope, with Errors ["There has been a temporary error. Please try again later."] |
503 | Xtrm can't get an exchange rate or complete a currency exchange right now, for example on GetExchangeRate and BookExchange | The envelope, with Errors ["Currency exchange service temporarily unavailable. Please try again later."]. Try again later; before you resend a BookExchange, check the wallet you convert from, as described in Exchange currency. |
GetAdvancedContactCountry accepts only POST. A GET returns HTTP 404 with {"StatusCode": 404, "Message": "The requested resource is not found"}, so send a POST with {} as the body. Any endpoint that accepts only POST answers a GET the same way.
Apart from the first call of an UpdateUser mobile-number change, we recommend treating any non-2xx status as a failure, and not assuming that its body is JSON or contains an OperationStatus.
#Responses without OperationStatus
Besides the batch payment endpoints, two endpoints don't use the envelope:
| Endpoint | How failures are reported |
|---|---|
/oAuth/token | Returns a flat token object. A failed token request returns HTTP 400 with {"error": …, "error_description": …} (see Authentication errors). |
GetConnectedCompanyFundRequest | Returns CSV text, not JSON. Its first line is the header row Account Number,Name,Credits,Debits,Currency, with no line before it. A failure returns the JSON envelope instead, with HTTP 400 or 500. We recommend checking the HTTP status and that the header row is present. |
#Error messages by area
These are the failure messages and signals to plan for on these endpoints, grouped by area.
#Bank accounts and bank debit
| Message or signal | Where it appears | What it means |
|---|---|---|
HTTP 400 with Success: false and field objects in Errors | LinkBankBeneficiary, LinkACHDebitBankBeneficiary | The bank needs more information, and nothing is linked. Send the whole request again with the fields in Errors added or fixed, and repeat until the response returns a BeneficiaryId: a resend can ask for more fields. |
ErrorMessage with FieldName, FieldLabel, IsRegulatoryField and valueset, for example RoutingNumber / Routing Number | The same two endpoints, in OperationStatus.Errors | FieldName is the parameter to send; FieldLabel is a readable label you can show in your interface. When IsRegulatoryField is true, send the value in RegulatoryFields as a Key/Value pair, with the FieldName as the Key. On LinkBankBeneficiary, valueset lists the values a missing regulatory field accepts. Some currencies need currency-specific information: repeat the request until it links. |
Regulatory field values are not required for this request. | LinkBankBeneficiary, in OperationStatus.Errors | You sent RegulatoryFields for a bank that needs none. Leave it out until a response lists a field whose IsRegulatoryField is true. |
IsValid: false | ValidateIBAN | The IBAN failed the structural and mathematical validity check. Success: true only means the call ran without server errors. |
Invalid amount., or the bank provider's message | VerifyACHDebitMicrodeposit, HTTP 400 | The micro-deposit amounts you sent don't match. An amount of 0 returns Amount_1 must be greater than 0 or Amount_2 must be greater than 0. If the amounts are refused too many times, delete the bank with DeleteBankBeneficiary and link it again. |
#Currency exchange
| Message or signal | Where it appears | What it means |
|---|---|---|
<FromWalletID> - Insufficient balance in the wallet, HTTP 400, for example 12345 - Insufficient balance in the wallet | BookExchange, in OperationStatus.Errors | The wallet in FromWalletID holds less than Amount. Xtrm rejects the exchange before it books anything, so no money is exchanged and nothing leaves the wallet. An Amount equal to the wallet balance is accepted. Add funds to the wallet or lower Amount, then send the request again. |
#Profiles and reports
| Message or signal | Where it appears | What it means |
|---|---|---|
HTTP 400, Missing profile information. Please ensure profile is complete. | TransferTaxInformation, in OperationStatus.Errors | For a recipient in the United States, Xtrm can't generate the 1099-K until the profile has the recipient's first and last name, email, tax ID (SSN or TIN), date of birth and full address (street, city, state, postal code and country). Recipients outside the United States are sent a CSV statement of their transactions instead, with no profile check. |
Message about approval status or missing requirements | CompanyAdvancedProfile | A system message about the submission. |
HTTP 404, The requested resource is not found, in answer to a GET | GetAdvancedContactCountry | The endpoint accepts only POST. Send a POST with an empty JSON object {} as the body. |
#Tokens and one-time passwords
| Message or signal | Where it appears | What it means |
|---|---|---|
HTTP 400, invalid_credentials (Credentials are invalid.) or invalid_grant | /oAuth/token | invalid_credentials: the client credentials aren't valid. invalid_grant: Xtrm doesn't accept the refresh_token you sent, for example because it has expired (60 days after it was issued). Request a new token with grant_type=password instead. |
HTTP 401 with error and error_message | Every endpoint except /oAuth/token | A missing, unrecognized or expired access token, or a call from an IP address your company doesn't allow. See Authentication errors. |
HTTP 200, Success: false, Invalid one time password. A new one has been sent and the original has been expired. Please use the new one. | UserWithdrawFund, BeneficiaryCompanyWithdrawFund | The one-time password was wrong, or it expired: a code expires 10 minutes after Xtrm sends it, counted in whole minutes, so send it back within 9 minutes. No money moved, the old code no longer works, and Xtrm has sent the recipient a new code. Ask the recipient for it and send the same request again with it in OTP. |
HTTP 200, Success: true, One Time Password sent to user. Please resubmit with One Time Password. | UserWithdrawFund, BeneficiaryCompanyWithdrawFund | Not a failure, and not a transfer: this is the response to the first request, or to one whose OTP is blank, 000000 or not a number. Xtrm has sent the recipient a new code, any earlier code no longer works, and no money moved. Send the same request again with the code in OTP. The transfer is made only when a response has PaymentStatus Completed and a PaymentTransactionId. |
HTTP 400, One Time Password must be an integer with a maximum length of 6 | The same two endpoints | The OTP you sent is longer than 6 characters. No code is sent. |
HTTP 400, Your previous transfer is in progress. Please wait or try later. | The same two endpoints | An earlier transfer from the recipient's wallet hasn't finished. Xtrm checks this before it sends a code and again after it accepts one; in the second case the code is used up. Wait, then start again with a first request. |
HTTP 400, Mobile # is not available in the user profile | The same two endpoints | You asked for the code by text message, and the recipient's profile has no mobile number. No code is sent. On UserWithdrawFund, any SendTransferCodeToMobile value that isn't empty asks for a text, "false" included, so leave the field out to get the code by email only. |
HTTP 400, Success: true, One Time Password sent to user. Please resubmit with One Time Password. | UpdateUser | You sent a MobileNumber that differs from the saved one, with its MobileCountryISO2 and with OTP set to "", and Xtrm texted a six-digit code to the new number. Nothing in the profile was updated. Within 10 minutes, send the same request again with the code in OTP. A wrong or expired code returns HTTP 400 with Success: false and Invalid one time password. A new one has been sent and the original has been expired. Please use the new one., and Xtrm texts a new code. |
Some endpoints also report unfinished or failed work in status fields rather than as errors; each endpoint's reference page lists those values. We recommend flagging a value you don't recognize for review instead of treating it as success, and handling any failure you don't recognize by logging it in full and surfacing it to a person, not by retrying it blindly.
#Check every response the same way
We recommend sending every call that uses the envelope through one check:
- If the HTTP status is not
2xx, treat the call as failed. Log the status and the raw body, and don't assume the body is JSON. - Parse the JSON and find
OperationStatusby searching for the key, because wrapper names vary. - If
Successistrue, the call succeeded, whateverErrorsholds. The two recipient transfer endpoints need one more check, described below. - Otherwise, treat the call as failed. Normalize
Errorsand keep what is left, together with the raw body, for your logs and for support.
The first, OTP-generating request of UserWithdrawFund and BeneficiaryCompanyWithdrawFund passes this check but moves no money: it returns HTTP 200 with Success set to true, and Errors holds One Time Password sent to user. Please resubmit with One Time Password. An OTP that is blank, 000000 or not a number counts as a first request too: Xtrm sends a new code, and the previous code stops working. On these two endpoints, the transfer is made only when the response has PaymentStatus Completed and a PaymentTransactionId; keep that ID to reconcile. After any other 200, get the code from the recipient and send the same request again with it in OTP. The code expires 10 minutes after Xtrm sends it, counted in whole minutes, so send it back within 9 minutes. Each code covers one attempt: once Xtrm accepts it, the code is used up, even if the transfer then fails, so start again with a first request.
The first call of a mobile-number change on UpdateUser, sent with OTP set to "", fails step 1 although nothing went wrong: it returns HTTP 400 with Success set to true and the same One Time Password sent to user. Please resubmit with One Time Password. message. Treat that response as the code being sent, and within 10 minutes send the same request again with the code in OTP.
This sample applies the four steps to GetCompanyWallets:
response=$(curl -sS -w '\n%{http_code}' -X POST "https://xapisandbox.xtrm.com/API/v4/Wallet/GetCompanyWallets" \
-H "Authorization: Bearer $XTRM_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"GetCompanyWallets": {
"request": {
"IssuerAccountNumber": "SPN1111222"
}
}
}')
http_status=$(printf '%s\n' "$response" | tail -n 1)
body=$(printf '%s\n' "$response" | sed '$d')
# OperationStatus.Success is the signal. Errors can be null, [] or [""] even on success.
# Exception: on UserWithdrawFund and BeneficiaryCompanyWithdrawFund, Success is also true when Xtrm
# only sent a code. There, a transfer is made only when PaymentStatus is Completed.
if [ "$http_status" -lt 200 ] || [ "$http_status" -ge 300 ]; then
echo "HTTP $http_status: $body" >&2
elif ! printf '%s' "$body" | grep -Eq '"Success"[[:space:]]*:[[:space:]]*true'; then
echo "Xtrm reported a failure: $body" >&2
else
echo "$body"
fi// Returns the OperationStatus object wherever it sits in the response.
function findOperationStatus(value) {
if (!value || typeof value !== 'object') return null;
if (value.OperationStatus && typeof value.OperationStatus === 'object') return value.OperationStatus;
for (const child of Object.values(value)) {
const found = findOperationStatus(child);
if (found) return found;
}
return null;
}
// Errors can be null, [] or [""] on success. Keep only real entries.
function errorEntries(errors) {
if (errors === null || errors === undefined || errors === '') return [];
if (Array.isArray(errors)) return errors.filter((e) => e !== null && e !== '');
if (typeof errors === 'object') return Object.keys(errors).length ? [errors] : [];
return [errors];
}
const response = await fetch('https://xapisandbox.xtrm.com/API/v4/Wallet/GetCompanyWallets', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.XTRM_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
GetCompanyWallets: {
request: {
IssuerAccountNumber: 'SPN1111222',
},
},
}),
});
const text = await response.text();
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${text}`);
}
const data = JSON.parse(text);
const status = findOperationStatus(data);
if (!status || status.Success !== true) {
const errors = errorEntries(status?.Errors);
throw new Error(`Xtrm reported a failure: ${JSON.stringify(errors.length ? errors : data)}`);
}
console.log(JSON.stringify(data, null, 2));import json
import os
import requests
def find_operation_status(value):
"""Return the OperationStatus object wherever it sits in the response."""
if isinstance(value, dict):
if isinstance(value.get("OperationStatus"), dict):
return value["OperationStatus"]
children = list(value.values())
elif isinstance(value, list):
children = value
else:
return None
for child in children:
found = find_operation_status(child)
if found is not None:
return found
return None
def error_entries(errors):
"""Errors can be None, [] or [""] on success. Keep only real entries."""
if errors is None or errors == "" or errors == {} or errors == []:
return []
if isinstance(errors, list):
return [e for e in errors if e is not None and e != ""]
return [errors]
response = requests.post(
"https://xapisandbox.xtrm.com/API/v4/Wallet/GetCompanyWallets",
headers={"Authorization": f"Bearer {os.environ['XTRM_ACCESS_TOKEN']}"},
json={
"GetCompanyWallets": {
"request": {
"IssuerAccountNumber": "SPN1111222",
},
},
},
)
if not 200 <= response.status_code < 300:
raise RuntimeError(f"HTTP {response.status_code}: {response.text}")
data = response.json()
status = find_operation_status(data)
if status is None or status.get("Success") is not True:
errors = error_entries(status.get("Errors") if status else None)
raise RuntimeError(f"Xtrm reported a failure: {json.dumps(errors or data)}")
print(json.dumps(data, indent=2))using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("XTRM_ACCESS_TOKEN"));
var json = """
{
"GetCompanyWallets": {
"request": {
"IssuerAccountNumber": "SPN1111222"
}
}
}
""";
var response = await client.PostAsync(
"https://xapisandbox.xtrm.com/API/v4/Wallet/GetCompanyWallets",
new StringContent(json, Encoding.UTF8, "application/json"));
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTTP {(int)response.StatusCode}: {body}");
}
using var document = JsonDocument.Parse(body);
var status = FindOperationStatus(document.RootElement);
var succeeded = status is JsonElement found
&& found.TryGetProperty("Success", out var success)
&& success.ValueKind == JsonValueKind.True;
if (!succeeded)
{
var errors = status is JsonElement s && s.TryGetProperty("Errors", out var raw)
? ErrorEntries(raw)
: new List<string>();
throw new Exception($"Xtrm reported a failure: {(errors.Count > 0 ? string.Join("; ", errors) : body)}");
}
Console.WriteLine(body);
// Returns the OperationStatus object wherever it sits in the response.
static JsonElement? FindOperationStatus(JsonElement element)
{
if (element.ValueKind == JsonValueKind.Object)
{
if (element.TryGetProperty("OperationStatus", out var operationStatus)
&& operationStatus.ValueKind == JsonValueKind.Object)
{
return operationStatus;
}
foreach (var property in element.EnumerateObject())
{
if (FindOperationStatus(property.Value) is JsonElement nested) return nested;
}
}
else if (element.ValueKind == JsonValueKind.Array)
{
foreach (var item in element.EnumerateArray())
{
if (FindOperationStatus(item) is JsonElement nested) return nested;
}
}
return null;
}
// Errors can be null, [] or [""] on success. Keep only real entries.
static List<string> ErrorEntries(JsonElement errors) => errors.ValueKind switch
{
JsonValueKind.Array => errors.EnumerateArray()
.Where(e => e.ValueKind != JsonValueKind.Null
&& !(e.ValueKind == JsonValueKind.String && e.GetString() == ""))
.Select(e => e.GetRawText())
.ToList(),
JsonValueKind.Object when errors.EnumerateObject().Any() => new List<string> { errors.GetRawText() },
JsonValueKind.String when errors.GetString() != "" => new List<string> { errors.GetString()! },
_ => new List<string>(),
};// Reads the response with Jackson (com.fasterxml.jackson.core:jackson-databind).
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
String json = """
{
"GetCompanyWallets": {
"request": {
"IssuerAccountNumber": "SPN1111222"
}
}
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Wallet/GetCompanyWallets"))
.header("Authorization", "Bearer " + System.getenv("XTRM_ACCESS_TOKEN"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new RuntimeException("HTTP " + response.statusCode() + ": " + response.body());
}
JsonNode root = new ObjectMapper().readTree(response.body());
// findValue searches the whole tree, so the varying wrapper names don't matter.
JsonNode status = root.findValue("OperationStatus");
if (status == null || !status.path("Success").isBoolean() || !status.path("Success").asBoolean()) {
// Errors can be null, [] or [""] on success. Keep only real entries.
List<String> errors = new ArrayList<>();
JsonNode raw = status == null ? null : status.get("Errors");
if (raw != null && raw.isArray()) {
for (JsonNode entry : raw) {
if (!entry.isNull() && !(entry.isTextual() && entry.asText().isEmpty())) {
errors.add(entry.toString());
}
}
} else if (raw != null && raw.isObject() && raw.size() > 0) {
errors.add(raw.toString());
} else if (raw != null && raw.isTextual() && !raw.asText().isEmpty()) {
errors.add(raw.asText());
}
throw new RuntimeException("Xtrm reported a failure: "
+ (errors.isEmpty() ? response.body() : String.join("; ", errors)));
}
System.out.println(response.body());<?php
// Returns the OperationStatus array wherever it sits in the response.
function findOperationStatus($value)
{
if (!is_array($value)) {
return null;
}
if (isset($value['OperationStatus']) && is_array($value['OperationStatus'])) {
return $value['OperationStatus'];
}
foreach ($value as $child) {
$found = findOperationStatus($child);
if ($found !== null) {
return $found;
}
}
return null;
}
// Errors can be null, [] or [""] on success. Keep only real entries.
function errorEntries($errors)
{
if ($errors === null || $errors === '' || $errors === []) {
return [];
}
if (is_array($errors) && array_keys($errors) === range(0, count($errors) - 1)) {
return array_values(array_filter($errors, fn ($e) => $e !== null && $e !== ''));
}
return [$errors];
}
$ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Wallet/GetCompanyWallets');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
'GetCompanyWallets' => [
'request' => [
'IssuerAccountNumber' => 'SPN1111222',
],
],
]),
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'),
'Content-Type: application/json',
],
]);
$body = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $httpStatus < 200 || $httpStatus >= 300) {
throw new RuntimeException("HTTP $httpStatus: " . ($body === false ? curl_error($ch) : $body));
}
$data = json_decode($body, true);
$status = findOperationStatus($data);
if ($status === null || ($status['Success'] ?? null) !== true) {
$errors = errorEntries($status['Errors'] ?? null);
throw new RuntimeException('Xtrm reported a failure: ' . json_encode($errors ?: $data));
}
print_r($data);#Handle failures on these endpoints
- Bank linking. When
LinkBankBeneficiaryorLinkACHDebitBankBeneficiaryreturnsSuccess: falsewith field objects inErrors, ask whoever holds the bank account (the individual or business recipient, or your company when you link a bank for bank debit) for the field named inFieldName, usingFieldLabelas the label. Send the whole request again with that field filled in, putting a field whoseIsRegulatoryFieldistrueinRegulatoryFields, and repeat until the response returns aBeneficiaryId. See Bank accounts & transfers. - IBANs. We recommend calling
ValidateIBANbefore you link a bank or start a transfer, to prevent failed transactions and routing errors. CheckIsValid, notSuccess. - Messages. Show the message in
ErrorsfromTransferTaxInformation, and theMessagefromCompanyAdvancedProfile, to the person who can complete the missing information. - Funds. Handle an insufficient-funds failure on a recipient transfer, or on another call outside batch payments, like any other
Success: falseresponse: log the messages inErrorsand show them to the person who can add funds. - Retries. These endpoints take no idempotency key, including the recipient transfers, the funding calls and
BookExchange. Before you resend one of them after a timeout or another failure with no clear outcome, check whether the first request took effect, for example in the wallet transactions. Send these calls one at a time, and don't run retries in parallel. - Everything else. For any other
Success: falseresponse, read the messages inErrors: a missing field, for example, returns a message such asIssuer Account Number is Mandatory. Then check the request against the endpoint's reference page: copy field names exactly as they appear there, including odd spellings such asIsPublicallyTraded, and note that many values are strings even when they hold numbers or booleans, while a few must be real booleans. See Requests & responses.
#Get help
If you can't resolve an error, email [email protected]. We recommend including the endpoint, the HTTP status and the raw response body, and for a batch payment the CustomerBatchId and CustomerTransactionId of the items concerned. See Support.