Retries & idempotency
Your CustomerBatchId and CustomerTransactionId values make a resubmission safe. They tie every submission to the same payments, and Xtrm stores each pair at most once, so a resend can never store a payment twice.
Xtrm processes batch payments asynchronously (see How batch payments work). When you submit a batch to POST /Fund/BatchTransfer, Xtrm validates it, responds with 202 Accepted, and processes the payments in the background. Two things can leave you unsure what happened:
- The call fails. After a timeout or a dropped connection, you can't tell whether Xtrm received the batch.
- A payment fails during processing. The batch was accepted, but one or more payments didn't go through.
In both cases you resubmit with the same identifiers. The exception is a payment that stays RetainedInWallet. Bank, card, check, gift card and prepaid payments pass through that status briefly while Xtrm delivers them, so don't act on it while the batch is still Processing. A payment still RetainedInWallet once the batch status is final didn't reach its destination: the money is in the recipient's Xtrm wallet, and you can't retry or resubmit the payment. When a payment stays RetainedInWallet explains how to tell and how that money reaches the recipient.
An item stored as Failed gets a new attempt with the values you send, any other stored item comes back as CONFLICT_DUPLICATE_ITEM and nothing changes, and if no item of the batch is Failed, Xtrm refuses the whole request with 409 CONFLICT_PROCESSING. What you resend differs: after a timeout, resend the identical request; after a payment fails, we recommend resubmitting only the failed payments, with every field.
#Batch and payment identifiers
A batch payment uses two identifiers of your own. Both are required: Xtrm never generates either one.
| Field | Where it goes | If you omit it |
|---|---|---|
CustomerBatchId | The root of the request body, one per batch | The whole request fails with 422 INVALID_FIELD (Customer batch id is required.) and nothing is stored. |
CustomerTransactionId | Each entry in Items, one per payment | The item is rejected with 422 INVALID_FIELD (Customer transaction id is required.); the other items go ahead. |
Xtrm echoes both IDs, as it stored them, in its responses and webhooks, so you can match each batch and payment to your own records. They are also how you look a payment up later:
- The batch status endpoint,
GET /Fund/BatchTransfer/{CustomerBatchId}, returns the batch status and a paginated list of its payments. - The payment status endpoint,
GET /Fund/BatchTransfer/{CustomerBatchId}/Items/{CustomerTransactionId}, returns one payment.
Both IDs follow these rules:
| Rule | Detail |
|---|---|
| Length | 1 to 128 characters. |
| Characters | A–Z, a–z, 0–9, and . _ - : @. |
| Reserved prefixes | A CustomerBatchId can't start with cb_, and a CustomerTransactionId can't start with ct_. |
| Sanitizing | Before it checks and stores an ID, Xtrm trims spaces at either end and removes --, @@ and some SQL keywords (such as sysobjects), so don't use those sequences. Use each ID exactly as the create response echoes it. |
| Case | Xtrm treats IDs that differ only in case as the same ID: BATCH-1 and batch-1 are the same batch. Don't use two IDs that differ only in case. |
A CustomerBatchId that breaks the length, character or prefix rules fails the whole request with 422 INVALID_FIELD, and a CustomerTransactionId that breaks them rejects its item.
The sample on this page uses BATCH-RETRY-0001, with items TXN-RETRY-0001 and TXN-RETRY-0002.
If you're a managing platform
Batch IDs must be unique across all your client companies too. Include the client company's SPN or a UUID in every CustomerBatchId.
Make CustomerBatchId unique across Xtrm
CustomerBatchId values are shared across all Xtrm accounts, so a CustomerBatchId that is already in use, by you or by any other account, can make your request fail with 409 CONFLICT_PROCESSING. Make every CustomerBatchId globally unique, for example by including your account number or a UUID.
#The logical key
Xtrm identifies each payment by two values together:
CustomerBatchIdCustomerTransactionId
Your IssuerAccountNumber isn't part of the key. Requests that carry the same pair refer to the same payment, and Xtrm stores at most one item per pair, even when requests overlap, with no expiry. That is what makes a resubmission a retry rather than a new payment. Once an item is stored, its IDs never change: a retry replaces the item's other fields but keeps its IDs.
The two IDs have different scopes:
CustomerBatchIdis global. Xtrm looks a batch up by itsCustomerBatchIdalone, across all Xtrm accounts.CustomerTransactionIdis unique only within its batch. The sameCustomerTransactionIdunder a differentCustomerBatchIdis a new, separate payment, and Xtrm pays it.
#Duplicate IDs
| What you send | What happens |
|---|---|
The same CustomerTransactionId twice in one request (the same Items array) | Xtrm rejects every copy with DUPLICATE_ITEM_IN_REQUEST and processes none of them. |
The same CustomerBatchId and CustomerTransactionId in a later request | If the stored item is Failed, Xtrm re-queues it as a new attempt with the values you sent. Otherwise that item comes back as CONFLICT_DUPLICATE_ITEM and nothing changes. If no item of the batch is Failed, Xtrm refuses the whole request with 409 CONFLICT_PROCESSING. See Retry a batch payment. |
A CustomerTransactionId already used in a different batch | Xtrm accepts it as a new payment and pays it. Never reuse an ID for a different payment. |
A new CustomerTransactionId under an existing CustomerBatchId | Added only while the batch has a Failed item; otherwise the whole request gets 409 CONFLICT_PROCESSING. Put new payments in a new batch. |
#Retry a batch payment
To retry, submit POST /Fund/BatchTransfer again under the original CustomerBatchId, with each item's original CustomerTransactionId. Xtrm accepts the request only while the batch has at least one Failed item; otherwise it refuses the whole request with 409 CONFLICT_PROCESSING and stores nothing. We recommend resubmitting only the failed items, with every field.
Any other already-stored item you include comes back in Rejected as CONFLICT_DUPLICATE_ITEM, which is harmless: that entry is part of a 202 with Status CompletedWithFailures, and the HTTP status is 409 only when no item is accepted. Don't include new CustomerTransactionId values: Xtrm adds them to the batch and pays them as new payments. What happens to each item depends on its stored status:
| Item's status | What the resubmission does |
|---|---|
Failed | Xtrm accepts the item and queues it again in the same record: its status goes back to Accepted, the values you send replace the stored ones, and its next attempt gets the next AttemptNo. The earlier attempts stay in its history. There's no time limit and no limit on the number of retries. Before you retry an item whose latest attempt is TEMPORARY_ERROR, check with Xtrm support: the money may already have moved. |
Accepted, Processing or Verified | The item comes back as CONFLICT_DUPLICATE_ITEM and keeps processing. Wait until its status changes. |
Success | The item comes back as CONFLICT_DUPLICATE_ITEM and isn't paid again. |
RetainedInWallet | The item comes back as CONFLICT_DUPLICATE_ITEM, and nothing changes. While the batch is Processing, Xtrm is still delivering the payment: wait. If it's still RetainedInWallet once the batch status is final, the delivery didn't go through and the money is in the recipient's Xtrm wallet, so treat it like a wallet payment, not a retry: under new IDs it would be paid a second time. The fee you paid for it isn't refunded. See When a payment stays RetainedInWallet. |
Rejected at submission (listed in Rejected) | The item was never stored. Fix it, then resubmit it under the same CustomerBatchId only if nothing of that batch was stored or the batch has a Failed item; otherwise submit it in a new batch with a new CustomerBatchId. Either way, it can keep its CustomerTransactionId. Its first accepted submission is attempt 1. |
Never send two requests for the same CustomerBatchId at the same time; see Don't overlap requests for one batch. For what each status means, see Batch and payment statuses.
#Attempt history
To follow an item after you resubmit it, read its history: request it with history=true on either status endpoint. The attempts of a resubmission carry the next AttemptNo, and the earlier attempts stay in the item's Attempts. The attempts don't include the field values an earlier attempt used: a retry replaces them, and no endpoint returns the old ones. We recommend keeping your own record of what you sent on each attempt.
For example, Get one payment shows TXN-2026-9912A, whose first attempt failed with INSUFFICIENT_BALANCE and whose second attempt, resubmitted under the same IDs after the source wallet was funded, succeeded. Attempts and history explains each attempt field and how the two status endpoints order attempts.
#What you can change on a retry
A retry replaces the whole stored item with the values you send, not only the fields you changed: IssuerAccountNumber, SourceWalletId, EmailNotification, RecipientId, SendMethodId, Amount, Description and every Destination field. A Destination field you leave out becomes empty. Xtrm doesn't block a change to any of these fields and returns no error for one, and the status endpoints then show only the new values. New values apply only to an item whose stored status is Failed.
So send every field again. We recommend correcting only what caused the failure and keeping the fields that define the payment:
| Correct if needed | Keep the same |
|---|---|
Amount, Description and EmailNotification | RecipientId and SendMethodId |
Destination and its fields, such as BeneficiaryBankID, CardToken, WalletId, Email, SKU and the check address fields | IssuerAccountNumber, SourceWalletId, and the item's CustomerBatchId and CustomerTransactionId |
To pay a different recipient or use a different payment method, create a new payment with a new CustomerTransactionId, in a new batch: new items join an existing batch only while it has a Failed item.
A corrected destination doesn't always take effect. Once an item has passed validation, Xtrm keeps the destination it resolved then, such as the bank account, its rail or the card, for every later retry, even if a later retry fails validation. That is the case for an item that failed while Xtrm was debiting your wallet, for example with SEND_LIMIT_EXCEEDED, INSUFFICIENT_BALANCE, WALLET_AUTO_CREATE_FAILED, SEND_FAILED or TEMPORARY_ERROR. A corrected BeneficiaryBankID or CardToken therefore takes effect only if the item has never passed validation, that is, when every earlier attempt failed at the validation stage. SENDMETHODID_NOT_FOUND can come from either stage.
A retry after a timeout is different: you don't know whether the first request arrived, so resend exactly the same body, with nothing changed. See A safe retry pattern.
#Don't overlap requests for one batch
One request per batch at a time
Never send two requests with the same CustomerBatchId at the same time. Wait for the response to one, or for its timeout and the wait that follows, before you send the next.
Xtrm still stores each item at most once, but the later of two overlapping requests can't tell you what the first one stored. Depending on timing, it can get 409 CONFLICT_PROCESSING, because it saw the first request's items, or a 202 with TEMPORARY_ERROR, because its own insert collided with them: either as the Key of a Failed response, or as entries in Rejected of a CompletedWithFailures response.
You can submit different batches at the same time, and Xtrm processes the items of one source wallet one at a time, across batches. To pay more people, we recommend adding items to one batch, up to your account's limit (the MaxAllowed value in a LIMIT_EXCEEDED error message), rather than submitting many small batches.
#A safe retry pattern
The steps below are our recommendation for submitting a batch so that you can always retry it safely. In short:
When you get no usable response (a timeout, a dropped connection or an HTTP 5xx), wait, then resend exactly the same body, with the same CustomerBatchId and the same CustomerTransactionId on every item. Xtrm stores each item at most once, so the resend can't create a duplicate. If an item of the batch failed in the meantime, though, the resend retries it; see the steps below. Don't build a new batch or generate new IDs: Xtrm doesn't compare a new batch with earlier ones, so new IDs pay again. Never have two requests for the same CustomerBatchId in flight at once. Read the response: on a resend, 409 CONFLICT_PROCESSING, or CONFLICT_DUPLICATE_ITEM entries in Rejected, mean the first request stored payments of the batch, though not necessarily all of them. On the very first send of a batch, 409 CONFLICT_PROCESSING means the CustomerBatchId is already in use, possibly by another account. Then check every payment you sent with the status endpoints. A 404 can be temporary, so repeat the check a few times, at least a minute apart. Submit the payments that still return 404, and only those, in a new batch with a new CustomerBatchId.
- Generate the IDs once
Create the
CustomerBatchIdand each item'sCustomerTransactionIdwhen you create the payments in your own system, not when you build the HTTP request. Every attempt then carries the same values. Make theCustomerBatchIdunique across all of Xtrm, for example by including your account number or a UUID. - Store them before the first call
Save the IDs with your payment records before you call Xtrm. If your process crashes or restarts mid-request, it picks up the stored IDs and retries with them instead of generating new ones.
- Send one request per batch at a time
Never send two requests with the same
CustomerBatchIdat the same time, and that includes a resend while the original request may still be running. See Don't overlap requests for one batch. - Wait, then resend the identical request
When you get no usable response (a timeout, a dropped connection, an HTTP
5xxstatus, or a400whoseMessageisSequence contains no elements), wait before you resend: Xtrm keeps working on a request after your client gives up. Then resend exactly the same body, with the sameCustomerBatchIdand the sameCustomerTransactionIdon every item. A resend can never store an item twice. It can retry one, though: if an item of the batch failed while you waited, the resend queues it again with the same values, and it appears inAccepted.When you confirm the batch afterwards, check any item with a
TEMPORARY_ERRORattempt with Xtrm support: that code can be recorded after the money moved. Don't build a new batch or generate new IDs: Xtrm doesn't compare a new batch with earlier ones, so the same payments under a newCustomerBatchIdare paid again. Wait longer between resends and cap their number. If your access token expired in the meantime, get a new one and resend the same body. - Read the response
The response to a resend tells you what this call stored:
202withStatusAcceptedorCompletedWithFailures: this call accepted the items inAccepted; confirm that they were stored in the next step.Acceptedcan include items of the batch that had failed and that this call queued again. Entries inRejectedwithCONFLICT_DUPLICATE_ITEMwere already stored by the earlier request; they aren't errors. ATEMPORARY_ERRORentry inRejectedmeans that item's insert was rolled back, possibly because it collided with the original request: confirm it with the status endpoints before you resend it.409withKeyCONFLICT_PROCESSING: the batch has stored payments, and this call stored nothing. It doesn't prove that every payment was stored, so confirm each one in the next step.202withStatusFailedandKeyTEMPORARY_ERROR: this call stored nothing. It may have collided with the original request, still running: wait, then go to the next step.409withStatusFailedand onlyCONFLICT_DUPLICATE_ITEMentries inRejected: the earlier request already stored every item. Follow the batch.422withStatusFailed, or a409with other codes inRejected: this call stored nothing new. Fix the items listed and resubmit them as described in Retry a batch payment.401: Xtrm refused the request before storing anything. If your token expired (invalid_token), get a new one and resend the same body. AKeyofUnauthorizedmeans the token can't act forIssuerAccountNumber.
If the very first request for a batch gets
409 CONFLICT_PROCESSING, theCustomerBatchIdis already in use, possibly by another account: submit the payments under a newCustomerBatchId. A401from the batch status endpoint for that ID means another account owns it. In a202,ItemsCountcounts this request, and each rejected item has aKey, theFieldthat failed and aMessage. - Confirm what was stored
Neither a
202nor a409proves that every payment was stored. A202can list a payment inAcceptedthat Xtrm didn't store, and a409 CONFLICT_PROCESSINGon a resend means the batch has stored payments, not that it has all of them. That409also hides any item that the first request rejected at submission, because Xtrm checks theCustomerBatchIdbefore it checks the items. Xtrm stores a batch of more than 500 payments in groups of 500, each group on its own, and a group that fails doesn't undo the groups before it. A batch of 500 payments or fewer is stored all at once or not at all. If a group fails to store, the202lists its payments inRejectedwithTEMPORARY_ERROR. If storing a group breaks off inside Xtrm, for example on a database timeout, the202can still list the group's payments inAccepted.So after a
202or a409, check every payment you sent; this matters most for a batch of more than 500 payments. Get the batch withGET /Fund/BatchTransfer/{CustomerBatchId}and compare its items with what you sent. Then check each payment that's missing from it withGET /Fund/BatchTransfer/{CustomerBatchId}/Items/{CustomerTransactionId}, which answers404withCustomerTransactionId not found within the specified batch.for a payment that isn't stored. The batch status endpoint can show changes that are still in progress, while the payment status endpoint reads only committed data.A
404from either status endpoint doesn't prove that a batch or a payment is missing: a failed database read behind the check returns the same404as an unknown ID, and right after a submit call times out, the payment endpoint can return404while the original request is still storing the batch. When a status request fails explains both cases. A payment that still returns404after you've repeated the check a few times, at least a minute apart, wasn't stored. A500from a status check is temporary too: repeat the check. - Submit missing payments in a new batch
Submit the payments that weren't stored, and only those, in a new batch with a new
CustomerBatchId. They keep theirCustomerTransactionIdvalues: Xtrm checks an ID only against its own batch. Don't resend them under the originalCustomerBatchId: Xtrm refuses that with409 CONFLICT_PROCESSINGunless the batch has aFailedpayment. Never put a stored payment in the new batch: Xtrm doesn't compare batches, so it would be paid twice. - Resubmit failed items under the same IDs
Follow processing with webhooks or the status endpoints. To retry an item whose
StatusisFailed, resubmit it under its originalCustomerBatchIdandCustomerTransactionId. Send only the failed items, with every field, because a retry replaces the whole item; see What you can change on a retry. Other already-stored items you include come back asCONFLICT_DUPLICATE_ITEM, which is harmless. Don't include newCustomerTransactionIdvalues: Xtrm would add them and pay them as new payments. - Never reuse an ID for a different payment
A new payment, or a payment to a different recipient or by a different payment method, gets a new
CustomerTransactionId. A new batch gets a newCustomerBatchId. Reusing aCustomerBatchIdfor new payments gets409 CONFLICT_PROCESSING, or adds them to the old batch if it has aFaileditem. Reusing aCustomerTransactionIdin the same batch getsCONFLICT_DUPLICATE_ITEM(or409 CONFLICT_PROCESSINGfor the whole request when no item of the batch isFailed), or replaces the old item with the new payment if that item isFailed.
#What not to do
- Don't generate new IDs, or a new
CustomerBatchId, for a payment until you've confirmed that it's missing. Xtrm never compares a new batch with earlier ones, so the same payment under a newCustomerBatchIdis paid again. - Don't treat a
404from either status endpoint as proof that a payment is missing until you've repeated the check a few times, at least a minute apart. The original request may still be running, and both endpoints also answer404when their database read fails. Until then, resend only under the originalCustomerBatchIdandCustomerTransactionIdvalues: Xtrm's duplicate check works only within oneCustomerBatchId, so it protects a resend under the original IDs and never one under new IDs. - Don't treat the
Acceptedlist of a202, or a409 CONFLICT_PROCESSINGon a resend, as proof that every payment was stored. - Don't resubmit a
RetainedInWalletpayment. While the batch isProcessing, it's still on its way to the destination; once the batch status is final, it has stuck and the money is in the recipient's Xtrm wallet. Under the same IDs it comes back asCONFLICT_DUPLICATE_ITEM, and under new IDs it's paid a second time. - Don't change
RecipientId,SendMethodId,SourceWalletIdorIssuerAccountNumberwhen you retry aFaileditem. Xtrm would apply the change without an error. A different recipient or method is a new payment with a newCustomerTransactionId. - Don't retry a
Faileditem whose latest attempt isTEMPORARY_ERRORwithout first checking with Xtrm support. That code can be recorded after the money moved, so a retry could pay twice. - Don't use two IDs that differ only in case: Xtrm treats them as the same ID.
#Example: resend a batch with the same IDs
This sample submits a batch of two payments with fixed IDs. When there's no usable response (a timeout, a dropped connection, a 5xx, or a 400 with Sequence contains no elements), it waits and sends the identical request again, up to three times in all (the cURL tab resends on fewer of these cases; see below). It then reads the response as in Read the response.
A 409 with only CONFLICT_DUPLICATE_ITEM entries in Rejected means an earlier request already stored the items, so the sample reports them as stored. A 409 with CONFLICT_PROCESSING means a batch with this CustomerBatchId already exists: most likely from the earlier attempt if the sample had to resend, but possibly another account's, especially if this is your first submission of these payments. So the sample doesn't report your items as stored. It tells you to check the batch with the batch status endpoint: a 401 there means another account owns the ID, so submit the payments under a new CustomerBatchId; otherwise compare its items with what you sent, and confirm each missing payment as in Confirm what was stored. In every other case it reports how many items this call accepted and why any were rejected. In production, read the IDs from your payment records instead of hard-coding them, and then confirm what was stored with the status endpoints.
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.
In the cURL tab, --retry 2 resends the identical request after a timeout or an HTTP 500, 502, 503 or 504 response, --retry-all-errors (curl 7.71 or later) adds dropped connections and other transfer errors, and --retry-delay waits 30 seconds before each resend. curl doesn't resend after other 5xx codes or the 400 with Sequence contains no elements: for those, wait, then run the same command again. -o writes the final response to batch-response.json, and -w prints its HTTP status, or HTTP 000 when no response arrived.
# Every attempt sends the same CustomerBatchId and CustomerTransactionId values.
curl -X POST "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer" \
--retry 2 --retry-all-errors --retry-delay 30 --max-time 60 \
-o batch-response.json -w "HTTP %{http_code}\n" \
-H "Authorization: Bearer $XTRM_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-RETRY-0001",
"Items": [
{
"CustomerTransactionId": "TXN-RETRY-0001",
"RecipientId": "SPN8888776",
"Amount": 50,
"SendMethodId": "XTR94504",
"Destination": {
"WalletId": 122311
}
},
{
"CustomerTransactionId": "TXN-RETRY-0002",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001"
}
}
]
}'
# HTTP 000 (no response after the last attempt), any 5xx, or 400 with "Sequence contains no elements":
# the outcome is unknown. Wait, then run the same command again.
# HTTP 202: Xtrm accepted the items in Accepted (confirm with the batch status endpoint). Accepted can
# include items of this batch that had failed and that this call queued again. Rejected entries with
# CONFLICT_DUPLICATE_ITEM were stored by an earlier request; TEMPORARY_ERROR entries weren't stored by
# this call. Status Failed with TEMPORARY_ERROR means this call stored nothing.
# HTTP 409 with only CONFLICT_DUPLICATE_ITEM entries in Rejected: an earlier request stored the items.
# HTTP 409 with CONFLICT_PROCESSING: a batch with this CustomerBatchId already exists, from your earlier
# request or, if this is your first send of these payments, from another account. Check it with the
# batch status endpoint: a 401 there means another account owns the ID, so use a new CustomerBatchId.
# HTTP 422, or 409 with other codes: this call stored nothing new. Fix the items listed.
# Then confirm what was stored with the batch status endpoint.// Generate these IDs once, store them with your payment records, and reuse them on every attempt.
const body = JSON.stringify({
IssuerAccountNumber: 'SPN1111222',
SourceWalletId: 122181,
CustomerBatchId: 'BATCH-RETRY-0001',
Items: [
{
CustomerTransactionId: 'TXN-RETRY-0001',
RecipientId: 'SPN8888776',
Amount: 50,
SendMethodId: 'XTR94504',
Destination: {
WalletId: 122311,
},
},
{
CustomerTransactionId: 'TXN-RETRY-0002',
RecipientId: 'PAT9999888',
Amount: 50,
SendMethodId: 'XTR94503',
Destination: {
Email: '[email protected]',
SKU: 'PREP9001',
},
},
],
});
const MAX_ATTEMPTS = 3;
let attempt = 0;
let response;
let text;
while (!response) {
attempt++;
try {
const res = 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,
signal: AbortSignal.timeout(60_000),
});
// Read the whole body inside the attempt, so a connection that drops mid-response is retried too.
const resText = await res.text();
// No usable response: a server error, or a 400 "Sequence contains no elements".
if (res.status >= 500 || (res.status === 400 && resText.includes('Sequence contains no elements'))) {
throw new Error(`HTTP ${res.status}`);
}
response = res;
text = resText;
} catch (err) {
// The outcome is unknown, and Xtrm may still be working on the request,
// so wait, then resend the same body with the same IDs.
if (attempt === MAX_ATTEMPTS) throw err;
await new Promise((resolve) => setTimeout(resolve, attempt * 30_000));
}
}
let batch = {};
try {
batch = JSON.parse(text).BatchTransferResponse ?? {};
} catch {
// Not a batch response.
}
const rejected = batch.Rejected ?? [];
// A 409 with only CONFLICT_DUPLICATE_ITEM rejections: an earlier request already stored every item.
const alreadyStored =
response.status === 409 && rejected.length > 0 && rejected.every((item) => item.Key === 'CONFLICT_DUPLICATE_ITEM');
if (alreadyStored) {
console.log('Already stored by an earlier request. Follow batch BATCH-RETRY-0001 with the status endpoints.');
process.exit(0);
}
// A 409 with CONFLICT_PROCESSING: a batch with this CustomerBatchId already exists. After a resend it is most
// likely yours, but CustomerBatchId values are shared across all Xtrm accounts, so it can be another account's.
if (response.status === 409 && batch.Key === 'CONFLICT_PROCESSING') {
console.log(
attempt > 1
? 'Batch BATCH-RETRY-0001 already exists, most likely from the earlier attempt.'
: 'CustomerBatchId BATCH-RETRY-0001 is already in use, by an earlier request of yours or by another account.',
);
console.log(
'Check it with GET /Fund/BatchTransfer/BATCH-RETRY-0001: a 401 means another account owns it, ' +
'so send the payments under a new CustomerBatchId. Otherwise compare its items with what you sent.',
);
process.exit(attempt > 1 ? 0 : 1);
}
if (response.status === 202 && batch.Status === 'Failed') {
// TEMPORARY_ERROR: this call stored nothing, possibly because the original request is still running.
console.error('This call stored nothing. Wait, then check batch BATCH-RETRY-0001 with the status endpoints.');
process.exit(1);
}
if (!response.ok) {
// 422, or a 409 with other codes: this call stored nothing new, so fix the items listed.
// 401: if the token expired (invalid_token), get a new one and resend the same body.
console.error(`HTTP ${response.status}: ${text}`);
process.exit(1);
}
// Accepted can include items of this batch that had failed and that this call queued again.
console.log(`Batch ${batch.CustomerBatchId}: this call accepted ${batch.ItemsCount.Accepted} of ${batch.ItemsCount.Total} items`);
for (const item of rejected) {
if (item.Key === 'CONFLICT_DUPLICATE_ITEM') {
console.log(`Already stored by an earlier request: ${item.CustomerTransactionId}`);
} else {
console.log(`Rejected ${item.CustomerTransactionId} (${item.Key}): ${item.Field} ${item.Message}`);
}
}
console.log('Confirm what was stored with the batch status endpoint before you act on any item.');import os
import time
import requests
# Generate these IDs once, store them with your payment records, and reuse them on every attempt.
payload = {
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-RETRY-0001",
"Items": [
{
"CustomerTransactionId": "TXN-RETRY-0001",
"RecipientId": "SPN8888776",
"Amount": 50,
"SendMethodId": "XTR94504",
"Destination": {
"WalletId": 122311,
},
},
{
"CustomerTransactionId": "TXN-RETRY-0002",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001",
},
},
],
}
MAX_ATTEMPTS = 3
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
response = requests.post(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer",
headers={"Authorization": f"Bearer {os.environ['XTRM_ACCESS_TOKEN']}"},
json=payload,
timeout=60,
)
# No usable response: a server error, or a 400 "Sequence contains no elements".
if response.status_code >= 500 or (
response.status_code == 400 and "Sequence contains no elements" in response.text
):
raise requests.HTTPError(f"HTTP {response.status_code}")
break
except (
requests.ConnectionError,
requests.Timeout,
requests.HTTPError,
requests.exceptions.ChunkedEncodingError,
):
# The outcome is unknown, and Xtrm may still be working on the request,
# so wait, then resend the same body with the same IDs.
if attempt == MAX_ATTEMPTS:
raise
time.sleep(30 * attempt)
text = response.text
try:
batch = response.json().get("BatchTransferResponse") or {}
except ValueError:
batch = {} # Not a batch response.
rejected = batch.get("Rejected") or []
# A 409 with only CONFLICT_DUPLICATE_ITEM rejections: an earlier request already stored every item.
already_stored = (
response.status_code == 409
and len(rejected) > 0
and all(item.get("Key") == "CONFLICT_DUPLICATE_ITEM" for item in rejected)
)
if already_stored:
print("Already stored by an earlier request. Follow batch BATCH-RETRY-0001 with the status endpoints.")
raise SystemExit(0)
# A 409 with CONFLICT_PROCESSING: a batch with this CustomerBatchId already exists. After a resend it is most
# likely yours, but CustomerBatchId values are shared across all Xtrm accounts, so it can be another account's.
if response.status_code == 409 and batch.get("Key") == "CONFLICT_PROCESSING":
if attempt > 1:
print("Batch BATCH-RETRY-0001 already exists, most likely from the earlier attempt.")
else:
print("CustomerBatchId BATCH-RETRY-0001 is already in use, by an earlier request of yours or by another account.")
print(
"Check it with GET /Fund/BatchTransfer/BATCH-RETRY-0001: a 401 means another account owns it, "
"so send the payments under a new CustomerBatchId. Otherwise compare its items with what you sent."
)
raise SystemExit(0 if attempt > 1 else 1)
if response.status_code == 202 and batch.get("Status") == "Failed":
# TEMPORARY_ERROR: this call stored nothing, possibly because the original request is still running.
raise SystemExit("This call stored nothing. Wait, then check batch BATCH-RETRY-0001 with the status endpoints.")
if not response.ok:
# 422, or a 409 with other codes: this call stored nothing new, so fix the items listed.
# 401: if the token expired (invalid_token), get a new one and resend the same body.
raise SystemExit(f"HTTP {response.status_code}: {text}")
# Accepted can include items of this batch that had failed and that this call queued again.
counts = batch["ItemsCount"]
print(f"Batch {batch['CustomerBatchId']}: this call accepted {counts['Accepted']} of {counts['Total']} items")
for item in rejected:
if item["Key"] == "CONFLICT_DUPLICATE_ITEM":
print(f"Already stored by an earlier request: {item['CustomerTransactionId']}")
else:
print(f"Rejected {item['CustomerTransactionId']} ({item['Key']}): {item['Field']} {item['Message']}")
print("Confirm what was stored with the batch status endpoint before you act on any item.")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"));
// Generate these IDs once, store them with your payment records, and reuse them on every attempt.
var json = """
{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-RETRY-0001",
"Items": [
{
"CustomerTransactionId": "TXN-RETRY-0001",
"RecipientId": "SPN8888776",
"Amount": 50,
"SendMethodId": "XTR94504",
"Destination": {
"WalletId": 122311
}
},
{
"CustomerTransactionId": "TXN-RETRY-0002",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001"
}
}
]
}
""";
const int maxAttempts = 3;
var attempt = 0;
HttpResponseMessage response;
string responseBody;
while (true)
{
attempt++;
try
{
response = await client.PostAsync(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer",
new StringContent(json, Encoding.UTF8, "application/json"));
responseBody = await response.Content.ReadAsStringAsync();
// No usable response: a server error, or a 400 "Sequence contains no elements".
var code = (int)response.StatusCode;
if (code >= 500 || (code == 400 && responseBody.Contains("Sequence contains no elements")))
throw new HttpRequestException($"HTTP {code}");
break;
}
catch (Exception ex) when (attempt < maxAttempts && (ex is HttpRequestException || ex is TaskCanceledException))
{
// The outcome is unknown, and Xtrm may still be working on the request,
// so wait, then resend the same body with the same IDs.
await Task.Delay(TimeSpan.FromSeconds(30 * attempt));
}
}
var status = (int)response.StatusCode;
JsonElement batch = default;
try
{
using var doc = JsonDocument.Parse(responseBody);
if (doc.RootElement.ValueKind == JsonValueKind.Object
&& doc.RootElement.TryGetProperty("BatchTransferResponse", out var wrapped))
batch = wrapped.Clone();
}
catch (JsonException)
{
// Not a batch response.
}
string? Text(JsonElement e, string name) =>
e.ValueKind == JsonValueKind.Object && e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString()
: null;
var rejected = batch.ValueKind == JsonValueKind.Object
&& batch.TryGetProperty("Rejected", out var list) && list.ValueKind == JsonValueKind.Array
? list.EnumerateArray().ToList()
: new List<JsonElement>();
// A 409 with only CONFLICT_DUPLICATE_ITEM rejections: an earlier request already stored every item.
var alreadyStored = status == 409
&& rejected.Count > 0 && rejected.All(item => Text(item, "Key") == "CONFLICT_DUPLICATE_ITEM");
if (alreadyStored)
{
Console.WriteLine("Already stored by an earlier request. Follow batch BATCH-RETRY-0001 with the status endpoints.");
return;
}
// A 409 with CONFLICT_PROCESSING: a batch with this CustomerBatchId already exists. After a resend it is most
// likely yours, but CustomerBatchId values are shared across all Xtrm accounts, so it can be another account's.
if (status == 409 && Text(batch, "Key") == "CONFLICT_PROCESSING")
{
Console.WriteLine(attempt > 1
? "Batch BATCH-RETRY-0001 already exists, most likely from the earlier attempt."
: "CustomerBatchId BATCH-RETRY-0001 is already in use, by an earlier request of yours or by another account.");
Console.WriteLine("Check it with GET /Fund/BatchTransfer/BATCH-RETRY-0001: a 401 means another account owns it, " +
"so send the payments under a new CustomerBatchId. Otherwise compare its items with what you sent.");
Environment.ExitCode = attempt > 1 ? 0 : 1;
return;
}
if (status == 202 && Text(batch, "Status") == "Failed")
{
// TEMPORARY_ERROR: this call stored nothing, possibly because the original request is still running.
Console.Error.WriteLine("This call stored nothing. Wait, then check batch BATCH-RETRY-0001 with the status endpoints.");
Environment.ExitCode = 1;
return;
}
if (!response.IsSuccessStatusCode)
{
// 422, or a 409 with other codes: this call stored nothing new, so fix the items listed.
// 401: if the token expired (invalid_token), get a new one and resend the same body.
Console.Error.WriteLine($"HTTP {status}: {responseBody}");
Environment.ExitCode = 1;
return;
}
// Accepted can include items of this batch that had failed and that this call queued again.
var counts = batch.GetProperty("ItemsCount");
Console.WriteLine($"Batch {Text(batch, "CustomerBatchId")}: this call accepted " +
$"{counts.GetProperty("Accepted").GetInt32()} of {counts.GetProperty("Total").GetInt32()} items");
foreach (var item in rejected)
{
if (Text(item, "Key") == "CONFLICT_DUPLICATE_ITEM")
Console.WriteLine($"Already stored by an earlier request: {Text(item, "CustomerTransactionId")}");
else
Console.WriteLine($"Rejected {Text(item, "CustomerTransactionId")} ({Text(item, "Key")}): " +
$"{Text(item, "Field")} {Text(item, "Message")}");
}
Console.WriteLine("Confirm what was stored with the batch status endpoint before you act on any item.");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;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Generate these IDs once, store them with your payment records, and reuse them on every attempt.
String json = """
{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-RETRY-0001",
"Items": [
{
"CustomerTransactionId": "TXN-RETRY-0001",
"RecipientId": "SPN8888776",
"Amount": 50,
"SendMethodId": "XTR94504",
"Destination": {
"WalletId": 122311
}
},
{
"CustomerTransactionId": "TXN-RETRY-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();
HttpClient client = HttpClient.newHttpClient();
int maxAttempts = 3;
int attempt = 0;
HttpResponse<String> response = null;
while (response == null) {
attempt++;
try {
HttpResponse<String> r = client.send(request, HttpResponse.BodyHandlers.ofString());
// No usable response: a server error, or a 400 "Sequence contains no elements".
if (r.statusCode() >= 500 || (r.statusCode() == 400 && r.body().contains("Sequence contains no elements"))) {
throw new IOException("HTTP " + r.statusCode());
}
response = r;
} catch (IOException e) {
// Timeout (HttpTimeoutException), dropped connection or no usable response: the outcome is
// unknown, and Xtrm may still be working on the request, so wait, then resend the same body.
if (attempt == maxAttempts) throw e;
Thread.sleep(30_000L * attempt);
}
}
int status = response.statusCode();
String body = response.body();
// Every "Key" in the body: the batch-level Key and the Key of each rejected item.
List<String> keys = new ArrayList<>();
Matcher keyMatcher = Pattern.compile("\"Key\"\\s*:\\s*\"([^\"]*)\"").matcher(body);
while (keyMatcher.find()) keys.add(keyMatcher.group(1));
// A 409 with only CONFLICT_DUPLICATE_ITEM rejections: an earlier request already stored every item.
boolean alreadyStored = status == 409 && !keys.isEmpty()
&& keys.stream().allMatch(k -> k.equals("CONFLICT_DUPLICATE_ITEM"));
// A 409 with CONFLICT_PROCESSING: a batch with this CustomerBatchId already exists. After a resend it is most
// likely yours, but CustomerBatchId values are shared across all Xtrm accounts, so it can be another account's.
boolean batchIdInUse = status == 409 && keys.contains("CONFLICT_PROCESSING");
// A 202 with Status Failed (TEMPORARY_ERROR): this call stored nothing.
boolean storedNothing = status == 202 && Pattern.compile("\"Status\"\\s*:\\s*\"Failed\"").matcher(body).find();
if (alreadyStored) {
System.out.println("Already stored by an earlier request. Follow batch BATCH-RETRY-0001 with the status endpoints.");
} else if (batchIdInUse) {
System.out.println(attempt > 1
? "Batch BATCH-RETRY-0001 already exists, most likely from the earlier attempt."
: "CustomerBatchId BATCH-RETRY-0001 is already in use, by an earlier request of yours or by another account.");
System.out.println("Check it with GET /Fund/BatchTransfer/BATCH-RETRY-0001: a 401 means another account owns it, "
+ "so send the payments under a new CustomerBatchId. Otherwise compare its items with what you sent.");
if (attempt == 1) System.exit(1);
} else if (storedNothing) {
// Possibly because the original request is still running.
System.err.println("This call stored nothing. Wait, then check batch BATCH-RETRY-0001 with the status endpoints.");
System.exit(1);
} else if (status >= 400) {
// 422, or a 409 with other codes: this call stored nothing new, so fix the items listed.
// 401: if the token expired (invalid_token), get a new one and resend the same body.
System.err.println("HTTP " + status + ": " + body);
System.exit(1);
} else {
// 2xx: parse BatchTransferResponse with your JSON library and check ItemsCount and Rejected.
// Accepted can include items of this batch that had failed and that this call queued again.
// CONFLICT_DUPLICATE_ITEM entries were stored by an earlier request; other entries have a Key,
// a Field and a Message. Then confirm what was stored with the batch status endpoint.
System.out.println(status + " " + body);
}<?php
// Generate these IDs once, store them with your payment records, and reuse them on every attempt.
$body = json_encode([
'IssuerAccountNumber' => 'SPN1111222',
'SourceWalletId' => 122181,
'CustomerBatchId' => 'BATCH-RETRY-0001',
'Items' => [
[
'CustomerTransactionId' => 'TXN-RETRY-0001',
'RecipientId' => 'SPN8888776',
'Amount' => 50,
'SendMethodId' => 'XTR94504',
'Destination' => [
'WalletId' => 122311,
],
],
[
'CustomerTransactionId' => 'TXN-RETRY-0002',
'RecipientId' => 'PAT9999888',
'Amount' => 50,
'SendMethodId' => 'XTR94503',
'Destination' => [
'Email' => '[email protected]',
'SKU' => 'PREP9001',
],
],
],
]);
$maxAttempts = 3;
for ($attempt = 1; ; $attempt++) {
$ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'),
'Content-Type: application/json',
],
]);
$response = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
// No usable response: a timeout or dropped connection, a server error,
// or a 400 "Sequence contains no elements".
$outcomeUnknown = $response === false
|| $httpStatus >= 500
|| ($httpStatus === 400 && str_contains($response, 'Sequence contains no elements'));
if (!$outcomeUnknown) {
break;
}
// Xtrm may still be working on the request, so wait, then resend the same body with the same IDs.
if ($attempt === $maxAttempts) {
fwrite(STDERR, "Batch outcome unknown after $maxAttempts attempts\n");
exit(1);
}
sleep(30 * $attempt);
}
$batch = json_decode($response, true)['BatchTransferResponse'] ?? [];
$rejected = $batch['Rejected'] ?? [];
// A 409 with only CONFLICT_DUPLICATE_ITEM rejections: an earlier request already stored every item.
$alreadyStored = $httpStatus === 409
&& $rejected && !array_diff(array_column($rejected, 'Key'), ['CONFLICT_DUPLICATE_ITEM']);
if ($alreadyStored) {
echo "Already stored by an earlier request. Follow batch BATCH-RETRY-0001 with the status endpoints.\n";
exit(0);
}
// A 409 with CONFLICT_PROCESSING: a batch with this CustomerBatchId already exists. After a resend it is most
// likely yours, but CustomerBatchId values are shared across all Xtrm accounts, so it can be another account's.
if ($httpStatus === 409 && ($batch['Key'] ?? null) === 'CONFLICT_PROCESSING') {
echo $attempt > 1
? "Batch BATCH-RETRY-0001 already exists, most likely from the earlier attempt.\n"
: "CustomerBatchId BATCH-RETRY-0001 is already in use, by an earlier request of yours or by another account.\n";
echo "Check it with GET /Fund/BatchTransfer/BATCH-RETRY-0001: a 401 means another account owns it, "
. "so send the payments under a new CustomerBatchId. Otherwise compare its items with what you sent.\n";
exit($attempt > 1 ? 0 : 1);
}
if ($httpStatus === 202 && ($batch['Status'] ?? null) === 'Failed') {
// TEMPORARY_ERROR: this call stored nothing, possibly because the original request is still running.
fwrite(STDERR, "This call stored nothing. Wait, then check batch BATCH-RETRY-0001 with the status endpoints.\n");
exit(1);
}
if ($httpStatus >= 400) {
// 422, or a 409 with other codes: this call stored nothing new, so fix the items listed.
// 401: if the token expired (invalid_token), get a new one and resend the same body.
fwrite(STDERR, "HTTP $httpStatus: $response\n");
exit(1);
}
// Accepted can include items of this batch that had failed and that this call queued again.
echo "Batch {$batch['CustomerBatchId']}: this call accepted {$batch['ItemsCount']['Accepted']} of {$batch['ItemsCount']['Total']} items\n";
foreach ($rejected as $item) {
if ($item['Key'] === 'CONFLICT_DUPLICATE_ITEM') {
echo "Already stored by an earlier request: {$item['CustomerTransactionId']}\n";
} else {
echo "Rejected {$item['CustomerTransactionId']} ({$item['Key']}): {$item['Field']} {$item['Message']}\n";
}
}
echo "Confirm what was stored with the batch status endpoint before you act on any item.\n";#Duplicate webhook deliveries
The same webhook event can be delivered more than once; see Retries and duplicates.
#Related
The batch lifecycle and wallet-first delivery.
Create a batch paymentBuild a batch, submit it, and track every payment to a final status.
Batch and payment statusesWhat each batch and payment status means, and which ones are final.
WebhooksGet notified as payments complete or fail, instead of polling.
Batch payments referencePOST /Fund/BatchTransfer and both status endpoints in full.