Create a batch payment
One request can pay a whole list of people and businesses, each the way that suits them: straight to a bank account, into an Xtrm wallet or onto a prepaid card. In this guide you choose the wallet that funds the batch, submit a batch that does all three, follow it until every payment has an outcome, and fix and retry a payment that fails, without ever paying anyone twice.
Xtrm processes a batch asynchronously. When you submit it, Xtrm checks the request and each payment's fields, stores the payments that pass and answers 202 Accepted. It doesn't check your balance or move any money at that point. It then processes the stored payments in the background, and the status endpoints report each payment's progress. For the model behind this flow, see How batch payments work.
#What you'll do
| Step | Call | What you keep |
|---|---|---|
| 1. Choose the source wallet | GetCompanyWallets | The WalletID you pay from |
| 2. Build and submit the batch | POST /Fund/BatchTransfer | Your CustomerBatchId and the accepted and rejected payments |
| 3. Track the batch | GET /Fund/BatchTransfer/{CustomerBatchId} | Each payment's Status |
| 4. Inspect a payment | GET /Fund/BatchTransfer/{CustomerBatchId}/Items/{CustomerTransactionId} | The payment's attempts and DeliveryType |
| 5. Retry a failed payment | GetLinkedBankAccounts, POST /Fund/BatchTransfer | A new attempt for the retried payment |
#Before you begin
You need:
An access token in the
XTRM_ACCESS_TOKENenvironment variable. Each sample in the steps reads it from there; the full example requests its own token withXTRM_CLIENT_IDandXTRM_CLIENT_SECRET. See Authentication.Your company's account number. It starts with
SPN, and the samples useSPN1111222. You send it asIssuerAccountNumber.A funded wallet in the currency you want to pay in. In the sandbox, Xtrm adds test funds to your wallets once your IP addresses are approved. To add money, see Fund your wallet.
Your recipients and their destinations. This guide pays three recipients:
Recipient Account Paid to Where the destination comes from A business SPN8888777Its linked bank account 41953ec32f3e4765a35a902c82bdd995The BeneficiaryIdthatLinkBankBeneficiaryreturns when you link the bank, or thatGetLinkedBankAccountslistsAnother business SPN8888776Its Xtrm wallet 122311The wallet's IDfromGetBeneficiaryWalletsJane Doe, an individual PAT9999888A prepaid virtual debit card, emailed to [email protected]The skuPREP9001fromGetPrepaidCardsCreate every recipient before you submit the batch. A batch pays existing Xtrm accounts only, by their account numbers, and a
RecipientIdwith no account fails during processing withRECIPIENT_NOT_FOUND. If a recipient doesn't have an account yet, create it first: withCreateUserfor a person, orCreateBeneficiaryfor a business. In the Xtrm web app you can add a person while you make a payment, but through the API you create each recipient first. Paying a recipient needs no connection to your company, but linking or listing a recipient's bank accounts and listing a business's wallets do. A recipient your company creates through the API is connected from the start; for an existing account, see Connections and manager services. To link a recipient's bank account and read back its ID, see Bank accounts.cURL, or one of Node.js 18+, Python 3 with
requests, .NET 8, Java 17+ or PHP 8 with the curl extension. The cURL samples use bash syntax.
#Create and track a batch
- Choose the source wallet
Every payment in a batch comes out of one of your company wallets, the source wallet, and that wallet sets the currency of the whole batch. List your wallets with
GetCompanyWalletsand pick one in the currency you want to pay in.curl -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" } } }'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 data = await response.json(); console.log(JSON.stringify(data, null, 2));import os import requests 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", }, }, }, ) response.raise_for_status() print(response.json())using System.Net.Http.Headers; using System.Text; 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")); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync());import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; 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()); System.out.println(response.body());<?php $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', ], ]); $response = curl_exec($ch); print_r(json_decode($response, true));Response{ "GetCompanyWalletResponse": { "CompanyWalletResult": { "CompanyWallets": { "CompanyWalletDetails": [ { "WalletID": 122181, "WalletName": "USD Wallet for Main Company", "WalletCurrency": "USD", "WalletBalance": 57715.15, "WalletType": "Standard", "IsBankLinked": false, "AllowWalletLinkedBankOverride": false, "EntityID": 12345 } ] }, "OperationStatus": { "Success": true, "Errors": null } } } }Your USD wallet is
122181, with USD 57,715.15. The batch in this guide pays USD 200.00, plus a fee for each payment, which Xtrm charges to the source wallet on top of the payment'sAmount. The submit call doesn't check your balance. Xtrm debits each payment when it processes it, and a payment the wallet can't cover at that point fails withINSUFFICIENT_BALANCE, so we recommend comparingWalletBalancewith the batch's total, plus fees, before you submit.Keep for later:
- The
WalletID,122181. You send it asSourceWalletId, a JSON number. - Its
WalletCurrency,USD: everyAmountin the batch is in this currency.
- The
- Build and submit the batch
A batch payment is one JSON object. Unlike most Xtrm requests, it has no wrapper object: these fields sit at the root of the body.
Field Required Description IssuerAccountNumberYes Your company's account number. SourceWalletIdYes The WalletIDfrom step 1, as a JSON number. It must be an active wallet your company owns.CustomerBatchIdYes Your ID for the batch: 1 to 128 letters, digits and ._-:@. Xtrm never generates one, and you need it to track the batch and retry its payments.CustomerBatchIdvalues are shared across all Xtrm accounts, so make yours unique, for example by including your account number or a UUID. See Batch and payment identifiers for every rule.EmailNotificationNo A JSON boolean. trueemails each recipient a "payment received" message when their wallet is credited.falseby default.ItemsYes The payments: at least one, and no more than your account's limit. Each entry in
Itemsis one payment:Field Required Description CustomerTransactionIdYes Your ID for the payment, with the same characters as CustomerBatchId. Xtrm never generates one. Give every payment its own.RecipientIdYes The recipient's account number: PAT…for an individual,SPN…for a business.AmountYes A positive JSON number in the batch's currency, with at most 2 decimal places. SendMethodIdYes The payment method. Take it from GetPaymentMethods: a batch accepts exactly its seven IDs, in capitals.DestinationYes The fields the payment method needs. Send it on every item, even when all of its fields are optional. DescriptionNo A note for the payment, up to 1,024 characters. Xtrm copies it to the wallet transactions the payment creates: the debit in your source wallet and the credit in the recipient's wallet, where the recipient sees it. Start it with the payment's CustomerTransactionId, as the samples do, so you can find those transactions withSearchParam; see Track & reconcile payments.Send each value with the JSON type shown, as the samples do:
SourceWalletIdandDestination.WalletIdas integers,Amountas a JSON number,EmailNotificationas a boolean, andCustomerBatchId,CustomerTransactionId,RecipientId,SendMethodId,Descriptionand theDestinationtext fields as strings. The batch endpoint also converts numeric strings, such as"100.00"and"122181", and the strings"true"and"false". A value it can't convert is read as empty, without a type error: anAmountof"abc"rejects the payment withAmount must be greater than zero., aSourceWalletIdof"abc"refuses the whole batch withInvalid source wallet id., and anEmailNotificationof"yes"is read asfalse. A text field sent as a JSON number is stored as text, so aCustomerTransactionIdof1001becomes"1001". See Numbers and booleans as strings.The
Destinationfields for the three payment methods in this batch:Payment method SendMethodIdDestinationfieldsBank XTR94500BeneficiaryBankID: the ID of a bank account linked to the recipient.BeneficiaryBankPaymentMethod(optional):ACH,WIREorRTP; without it, Xtrm uses the bank's primary rail.Business wallet XTR94504WalletId(optional): the business's wallet to credit, in the batch's currency. Without it, Xtrm credits the business's oldest active Standard wallet in that currency, or creates one.Prepaid virtual debit card XTR94503Email, which receives the card, andSKU, a card offered in the batch's currency. Both required. Individual recipients only.Individual wallets, digital gift cards, Rapid Transfer and checks work the same way. See Payment methods & destinations for every method's fields.
This request pays the three recipients from wallet
122181. Replace the sample IDs with your own unique values before you run it in the sandbox.curl -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-GUIDE-0001", "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0001", "RecipientId": "SPN8888777", "Amount": 100, "SendMethodId": "XTR94500", "Destination": { "BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryBankPaymentMethod": "ACH" }, "Description": "TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive" }, { "CustomerTransactionId": "TXN-GUIDE-0002", "RecipientId": "SPN8888776", "Amount": 50, "SendMethodId": "XTR94504", "Destination": { "WalletId": 122311 }, "Description": "TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus" }, { "CustomerTransactionId": "TXN-GUIDE-0003", "RecipientId": "PAT9999888", "Amount": 50, "SendMethodId": "XTR94503", "Destination": { "Email": "[email protected]", "SKU": "PREP9001" }, "Description": "TXN-GUIDE-0003 Q3 Top Performer Contractor Reward" } ] }'const 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-GUIDE-0001', Items: [ { CustomerTransactionId: 'TXN-GUIDE-0001', RecipientId: 'SPN8888777', Amount: 100, SendMethodId: 'XTR94500', Destination: { BeneficiaryBankID: '41953ec32f3e4765a35a902c82bdd995', BeneficiaryBankPaymentMethod: 'ACH', }, Description: 'TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive', }, { CustomerTransactionId: 'TXN-GUIDE-0002', RecipientId: 'SPN8888776', Amount: 50, SendMethodId: 'XTR94504', Destination: { WalletId: 122311, }, Description: 'TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus', }, { CustomerTransactionId: 'TXN-GUIDE-0003', RecipientId: 'PAT9999888', Amount: 50, SendMethodId: 'XTR94503', Destination: { Email: '[email protected]', SKU: 'PREP9001', }, Description: 'TXN-GUIDE-0003 Q3 Top Performer Contractor Reward', }, ], }), }); const data = await response.json(); console.log(JSON.stringify(data, null, 2));import os import requests 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-GUIDE-0001", "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0001", "RecipientId": "SPN8888777", "Amount": 100, "SendMethodId": "XTR94500", "Destination": { "BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryBankPaymentMethod": "ACH", }, "Description": "TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive", }, { "CustomerTransactionId": "TXN-GUIDE-0002", "RecipientId": "SPN8888776", "Amount": 50, "SendMethodId": "XTR94504", "Destination": { "WalletId": 122311, }, "Description": "TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus", }, { "CustomerTransactionId": "TXN-GUIDE-0003", "RecipientId": "PAT9999888", "Amount": 50, "SendMethodId": "XTR94503", "Destination": { "Email": "[email protected]", "SKU": "PREP9001", }, "Description": "TXN-GUIDE-0003 Q3 Top Performer Contractor Reward", }, ], }, ) print(f"HTTP {response.status_code}: {response.text}") response.raise_for_status()using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("XTRM_ACCESS_TOKEN")); var json = """ { "IssuerAccountNumber": "SPN1111222", "SourceWalletId": 122181, "CustomerBatchId": "BATCH-GUIDE-0001", "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0001", "RecipientId": "SPN8888777", "Amount": 100, "SendMethodId": "XTR94500", "Destination": { "BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryBankPaymentMethod": "ACH" }, "Description": "TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive" }, { "CustomerTransactionId": "TXN-GUIDE-0002", "RecipientId": "SPN8888776", "Amount": 50, "SendMethodId": "XTR94504", "Destination": { "WalletId": 122311 }, "Description": "TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus" }, { "CustomerTransactionId": "TXN-GUIDE-0003", "RecipientId": "PAT9999888", "Amount": 50, "SendMethodId": "XTR94503", "Destination": { "Email": "[email protected]", "SKU": "PREP9001" }, "Description": "TXN-GUIDE-0003 Q3 Top Performer Contractor Reward" } ] } """; var response = await client.PostAsync( "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer", new StringContent(json, Encoding.UTF8, "application/json")); var body = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}: {body}"); response.EnsureSuccessStatusCode();import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; String json = """ { "IssuerAccountNumber": "SPN1111222", "SourceWalletId": 122181, "CustomerBatchId": "BATCH-GUIDE-0001", "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0001", "RecipientId": "SPN8888777", "Amount": 100, "SendMethodId": "XTR94500", "Destination": { "BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryBankPaymentMethod": "ACH" }, "Description": "TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive" }, { "CustomerTransactionId": "TXN-GUIDE-0002", "RecipientId": "SPN8888776", "Amount": 50, "SendMethodId": "XTR94504", "Destination": { "WalletId": 122311 }, "Description": "TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus" }, { "CustomerTransactionId": "TXN-GUIDE-0003", "RecipientId": "PAT9999888", "Amount": 50, "SendMethodId": "XTR94503", "Destination": { "Email": "[email protected]", "SKU": "PREP9001" }, "Description": "TXN-GUIDE-0003 Q3 Top Performer Contractor Reward" } ] } """; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer")) .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()); System.out.println(response.body());<?php $ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode([ 'IssuerAccountNumber' => 'SPN1111222', 'SourceWalletId' => 122181, 'CustomerBatchId' => 'BATCH-GUIDE-0001', 'Items' => [ [ 'CustomerTransactionId' => 'TXN-GUIDE-0001', 'RecipientId' => 'SPN8888777', 'Amount' => 100, 'SendMethodId' => 'XTR94500', 'Destination' => [ 'BeneficiaryBankID' => '41953ec32f3e4765a35a902c82bdd995', 'BeneficiaryBankPaymentMethod' => 'ACH', ], 'Description' => 'TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive', ], [ 'CustomerTransactionId' => 'TXN-GUIDE-0002', 'RecipientId' => 'SPN8888776', 'Amount' => 50, 'SendMethodId' => 'XTR94504', 'Destination' => [ 'WalletId' => 122311, ], 'Description' => 'TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus', ], [ 'CustomerTransactionId' => 'TXN-GUIDE-0003', 'RecipientId' => 'PAT9999888', 'Amount' => 50, 'SendMethodId' => 'XTR94503', 'Destination' => [ 'Email' => '[email protected]', 'SKU' => 'PREP9001', ], 'Description' => 'TXN-GUIDE-0003 Q3 Top Performer Contractor Reward', ], ], ]), CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'), 'Content-Type: application/json', ], ]); $response = curl_exec($ch); print_r(json_decode($response, true));Xtrm checks the fields of every payment before it answers. When at least one passes, it answers
202 Accepted, with the result wrapped inBatchTransferResponse:Response{ "BatchTransferResponse": { "CustomerBatchId": "BATCH-GUIDE-0001", "Status": "Accepted", "ItemsCount": { "Total": 3, "Accepted": 3, "Rejected": 0 }, "Accepted": [ { "CustomerTransactionId": "TXN-GUIDE-0003", "Amount": 50.0, "Currency": "USD", "SendMethodId": "XTR94503", "RecipientId": "PAT9999888" }, { "CustomerTransactionId": "TXN-GUIDE-0002", "Amount": 50.0, "Currency": "USD", "SendMethodId": "XTR94504", "RecipientId": "SPN8888776" }, { "CustomerTransactionId": "TXN-GUIDE-0001", "Amount": 100.0, "Currency": "USD", "SendMethodId": "XTR94500", "RecipientId": "SPN8888777" } ], "Rejected": [] } }StatusAcceptedmeans all three payments passed the checks and are queued, listed inAcceptedin no particular order. Each entry echoes the payment'sAmountas a JSON number with the decimals you sent, so the100and50here come back as100.0and50.0. The status endpoints later return it as a string with 2 decimals, such as"100.00". Nobody has been paid yet, and a202doesn't prove that every payment inAcceptedwas stored, so confirm them in step 3. When some payments fail the checks,StatusisCompletedWithFailuresandRejectedlists each one with aKey, theFieldthat failed and aMessage; see Items rejected at submission. A202whoseStatusisFailedstored nothing; see A safe retry pattern. Any other HTTP status means Xtrm refused the whole batch; see The whole batch is refused.If a submit call times out
Wait, then resend the identical request with the same
CustomerBatchIdandCustomerTransactionIdvalues, and never have two requests for the sameCustomerBatchIdin flight at once. Xtrm never stores a payment twice: a409 CONFLICT_PROCESSINGreply, orCONFLICT_DUPLICATE_ITEMentries inRejected, mean your first request got through. A409doesn't prove that every payment was stored, though, for example in a batch of more than 500 payments, so check each one. See A safe retry pattern.Keep for later:
- Your
CustomerBatchId. Both status calls take it in the path. - The
CustomerTransactionIdof every payment, accepted or rejected.
- Your
- Track the batch until processing is over
Xtrm processes the accepted payments in the background. To follow them, poll
GET /Fund/BatchTransfer/{CustomerBatchId}. It returns the batch'sStatus, itsCurrency, the number of stored payments inItemsCountand one page ofItems, each with its ownStatus.recordsToSkipandrecordsToTakepage through the payments, andhistory=trueadds each payment's attempts.curl -X GET "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001?recordsToSkip=0&recordsToTake=50&history=true" \ -H "Authorization: Bearer $XTRM_ACCESS_TOKEN"const response = await fetch('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001?recordsToSkip=0&recordsToTake=50&history=true', { method: 'GET', headers: { Authorization: `Bearer ${process.env.XTRM_ACCESS_TOKEN}`, }, }); const data = await response.json(); console.log(JSON.stringify(data, null, 2));import os import requests response = requests.get( "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001?recordsToSkip=0&recordsToTake=50&history=true", headers={"Authorization": f"Bearer {os.environ['XTRM_ACCESS_TOKEN']}"}, ) response.raise_for_status() print(response.json())using System.Net.Http.Headers; 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-GUIDE-0001?recordsToSkip=0&recordsToTake=50&history=true"); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync());import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001?recordsToSkip=0&recordsToTake=50&history=true")) .header("Authorization", "Bearer " + System.getenv("XTRM_ACCESS_TOKEN")) .GET() .build(); HttpResponse<String> response = HttpClient.newHttpClient() .send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());<?php $ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001?recordsToSkip=0&recordsToTake=50&history=true'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'), ], ]); $response = curl_exec($ch); print_r(json_decode($response, true));The status object comes back at the root of the body, with no wrapper, and lists the payments in the order Xtrm stored them:
Response{ "CustomerBatchId": "BATCH-GUIDE-0001", "Status": "Completed", "Currency": "USD", "ItemsCount": 3, "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0001", "Status": "Success", "RecipientId": "SPN8888777", "SendMethodId": "XTR94500", "Amount": "100.00", "LastUpdatedAt": "2026-10-27T15:12:48.6410000Z", "Attempts": [ { "AttemptNo": 1, "Result": "Success", "ErrorCode": "SUCCESS", "CreatedAt": "2026-10-27T15:12:48.6370000Z", "CompletedAt": "2026-10-27T15:12:48.6410000Z" } ] }, { "CustomerTransactionId": "TXN-GUIDE-0002", "Status": "Success", "RecipientId": "SPN8888776", "SendMethodId": "XTR94504", "Amount": "50.00", "LastUpdatedAt": "2026-10-27T15:12:41.0230000Z", "Attempts": [ { "AttemptNo": 1, "Result": "Success", "ErrorCode": "SUCCESS", "CreatedAt": "2026-10-27T15:12:41.0190000Z", "CompletedAt": "2026-10-27T15:12:41.0230000Z" } ] }, { "CustomerTransactionId": "TXN-GUIDE-0003", "Status": "Success", "RecipientId": "PAT9999888", "SendMethodId": "XTR94503", "Amount": "50.00", "LastUpdatedAt": "2026-10-27T15:12:46.3080000Z", "Attempts": [ { "AttemptNo": 1, "Result": "Success", "ErrorCode": "SUCCESS", "CreatedAt": "2026-10-27T15:12:46.3040000Z", "CompletedAt": "2026-10-27T15:12:46.3080000Z" } ] } ], "Pagination": { "HasMore": false, "NextRecordsToSkip": 0 } }All three payments read
Success, so the batch readsCompleted. For the business wallet,Successmeans Xtrm credited the wallet. For the bank payment and the prepaid card, it means the provider accepted the payment: the bank transfer may not have settled yet, and Jane has been emailed her card but may not have claimed it.We recommend this polling loop:
- On each poll, read every page: while
Pagination.HasMoreistrue, call again withrecordsToSkipset toPagination.NextRecordsToSkip. - Stop when the batch reads
Completed,CompletedWithFailuresorFailedand no payment on any page isAccepted,ProcessingorVerified. Check both. The batch can briefly readFailedorCompletedWithFailureswhile payments are still being validated. A payment by any method other than a wallet readsRetainedInWalletas soon as Xtrm credits the recipient's wallet, while Xtrm is still delivering it to the destination, and the batch readsProcessinguntil that delivery is over. So while the batch readsProcessing, count aRetainedInWalletpayment as still in progress, and don't act on it. Wait longer between polls each time, and cap their number. - Record each payment's
Statusagainst itsCustomerTransactionId, and collect anyFailedpayments for step 5.
For what each batch and payment status means and what to do about it, see Batch and payment statuses. Instead of polling, you can also have Xtrm notify your server as payments complete; see Webhooks, and confirm final statuses with the status endpoints.
Keep for later: each payment's
CustomerTransactionIdandStatus, and the IDs of anyFailedpayments. - On each poll, read every page: while
- Inspect a payment and its attempts
To answer a recipient's question about one payment, or to see why it failed, call
GET /Fund/BatchTransfer/{CustomerBatchId}/Items/{CustomerTransactionId}. It reads only committed data, so it's also the call to confirm a payment's status before you act on it, for example before you resend it. A404from it can be temporary, so repeat the check a few times, at least a minute apart, before you conclude that a payment wasn't stored; see A safe retry pattern. This request readsTXN-GUIDE-0001, the bank payment.curl -X GET "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001/Items/TXN-GUIDE-0001?history=true" \ -H "Authorization: Bearer $XTRM_ACCESS_TOKEN"const response = await fetch('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001/Items/TXN-GUIDE-0001?history=true', { method: 'GET', headers: { Authorization: `Bearer ${process.env.XTRM_ACCESS_TOKEN}`, }, }); const data = await response.json(); console.log(JSON.stringify(data, null, 2));import os import requests response = requests.get( "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001/Items/TXN-GUIDE-0001?history=true", headers={"Authorization": f"Bearer {os.environ['XTRM_ACCESS_TOKEN']}"}, ) response.raise_for_status() print(response.json())using System.Net.Http.Headers; 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-GUIDE-0001/Items/TXN-GUIDE-0001?history=true"); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync());import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001/Items/TXN-GUIDE-0001?history=true")) .header("Authorization", "Bearer " + System.getenv("XTRM_ACCESS_TOKEN")) .GET() .build(); HttpResponse<String> response = HttpClient.newHttpClient() .send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());<?php $ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/BATCH-GUIDE-0001/Items/TXN-GUIDE-0001?history=true'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'), ], ]); $response = curl_exec($ch); print_r(json_decode($response, true));Response{ "CustomerBatchId": "BATCH-GUIDE-0001", "CustomerTransactionId": "TXN-GUIDE-0001", "Status": "Success", "RecipientId": "SPN8888777", "SendMethodId": "XTR94500", "Amount": "100.00", "Currency": "USD", "DeliveryType": "Bank", "LastUpdatedAt": "2026-10-27T15:12:48.6410000Z", "Attempts": [ { "AttemptNo": 1, "Result": "Success", "ErrorCode": "SUCCESS", "CreatedAt": "2026-10-27T15:12:40.1170000Z", "CompletedAt": "2026-10-27T15:12:48.6410000Z" } ] }Besides the fields in the batch's list, this endpoint returns the payment's
Currencyand itsDeliveryType:Bankhere, because the money went on from SPN8888777's wallet to its bank account. Each attempt has itsAttemptNo, itsResultand anErrorCode, which isSUCCESSwhen the attempt worked. Judge a payment by itsStatus, not by a single attempt: a payment can fail once and succeed when you retry it, as step 5 shows. See Attempts and history and Delivery type.Keep for later: the
DeliveryTypeandLastUpdatedAtfor your records. - Retry a failed payment
Every payment in
BATCH-GUIDE-0001succeeded, but sooner or later one won't. Say your next batch,BATCH-GUIDE-0002, pays SPN8888777 another USD 100.00 asTXN-GUIDE-0004, with a mistyped bank ID,00000000000000000000000000000000, that isn't linked to anyone. The payment passes the submit checks, then fails validation. Step 4's call forTXN-GUIDE-0004shows why:Response{ "CustomerBatchId": "BATCH-GUIDE-0002", "CustomerTransactionId": "TXN-GUIDE-0004", "Status": "Failed", "RecipientId": "SPN8888777", "SendMethodId": "XTR94500", "Amount": "100.00", "Currency": "USD", "DeliveryType": "", "LastUpdatedAt": "2026-10-27T16:20:05.1180000Z", "Attempts": [ { "AttemptNo": 1, "Result": "Failed", "ErrorCode": "BANKID_INVALID", "CreatedAt": "2026-10-27T16:20:04.9950000Z", "CompletedAt": "2026-10-27T16:20:05.1180000Z" } ] }BANKID_INVALIDmeans theBeneficiaryBankIDisn't one of the recipient's linked bank accounts. No money moved, and the payment isFailed, so you can fix it and retry it under the same IDs. Xtrm then records a new attempt instead of a new payment, so nobody is paid twice.First, look up the bank accounts linked to SPN8888777 with
GetLinkedBankAccounts. It needs SPN8888777 to be connected to your company, as it is when your company created it withCreateBeneficiary; to connect an existing account, see Connections and manager services.curl -X POST "https://xapisandbox.xtrm.com/API/v4/Bank/GetLinkedBankAccounts" \ -H "Authorization: Bearer $XTRM_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "GetLinkedBankAccounts": { "request": { "IssuerAccountNumber": "SPN1111222", "RecipientUserId": "SPN8888777" } } }'const response = await fetch('https://xapisandbox.xtrm.com/API/v4/Bank/GetLinkedBankAccounts', { method: 'POST', headers: { Authorization: `Bearer ${process.env.XTRM_ACCESS_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ GetLinkedBankAccounts: { request: { IssuerAccountNumber: 'SPN1111222', RecipientUserId: 'SPN8888777', }, }, }), }); const data = await response.json(); console.log(JSON.stringify(data, null, 2));import os import requests response = requests.post( "https://xapisandbox.xtrm.com/API/v4/Bank/GetLinkedBankAccounts", headers={"Authorization": f"Bearer {os.environ['XTRM_ACCESS_TOKEN']}"}, json={ "GetLinkedBankAccounts": { "request": { "IssuerAccountNumber": "SPN1111222", "RecipientUserId": "SPN8888777", }, }, }, ) response.raise_for_status() print(response.json())using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("XTRM_ACCESS_TOKEN")); var json = """ { "GetLinkedBankAccounts": { "request": { "IssuerAccountNumber": "SPN1111222", "RecipientUserId": "SPN8888777" } } } """; var response = await client.PostAsync( "https://xapisandbox.xtrm.com/API/v4/Bank/GetLinkedBankAccounts", new StringContent(json, Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync());import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; String json = """ { "GetLinkedBankAccounts": { "request": { "IssuerAccountNumber": "SPN1111222", "RecipientUserId": "SPN8888777" } } } """; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Bank/GetLinkedBankAccounts")) .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()); System.out.println(response.body());<?php $ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Bank/GetLinkedBankAccounts'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode([ 'GetLinkedBankAccounts' => [ 'request' => [ 'IssuerAccountNumber' => 'SPN1111222', 'RecipientUserId' => 'SPN8888777', ], ], ]), CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'), 'Content-Type: application/json', ], ]); $response = curl_exec($ch); print_r(json_decode($response, true));Response{ "GetLinkedBankAccountsResponse": { "GetLinkedBankAccountsResult": { "Beneficiary": { "BeneficiaryDetails": [ { "BeneficiaryId": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryName": "Northwind Traders LLC", "Currency": "USD", "Country": "United States of America", "TransferFee": 0, "PaymentMethods": { "Payment": "ACH" }, "BankDetails": { "BeneficiaryBankInformation": { "AccountNumber": "XXXX4321", "BankName": "WELLS FARGO BANK, N.A.", "BranchName": "Main Branch", "BankBeneficiaryStatus": "Approved", "ACHDebitApprovalStatus": null, "BankRoutingCode": "121000248", "EntityID": 0, "PaymentMethods": [ "ACH" ] } } } ] }, "OperationStatus": { "Success": true, "Errors": null } } } }SPN8888777's bank account is
41953ec32f3e4765a35a902c82bdd995, theBeneficiaryId. Now resubmitTXN-GUIDE-0004under its originalCustomerBatchId,BATCH-GUIDE-0002, with the correctedBeneficiaryBankID. A retry replaces the whole stored payment with the values you send, so send every field again, and keep the sameRecipientId,SendMethodId,SourceWalletIdandIssuerAccountNumber.curl -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-GUIDE-0002", "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0004", "RecipientId": "SPN8888777", "Amount": 100, "SendMethodId": "XTR94500", "Destination": { "BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryBankPaymentMethod": "ACH" }, "Description": "TXN-GUIDE-0004 Q4 Executive Sales Performance Incentive" } ] }'const 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-GUIDE-0002', Items: [ { CustomerTransactionId: 'TXN-GUIDE-0004', RecipientId: 'SPN8888777', Amount: 100, SendMethodId: 'XTR94500', Destination: { BeneficiaryBankID: '41953ec32f3e4765a35a902c82bdd995', BeneficiaryBankPaymentMethod: 'ACH', }, Description: 'TXN-GUIDE-0004 Q4 Executive Sales Performance Incentive', }, ], }), }); const data = await response.json(); console.log(JSON.stringify(data, null, 2));import os import requests 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-GUIDE-0002", "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0004", "RecipientId": "SPN8888777", "Amount": 100, "SendMethodId": "XTR94500", "Destination": { "BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryBankPaymentMethod": "ACH", }, "Description": "TXN-GUIDE-0004 Q4 Executive Sales Performance Incentive", }, ], }, ) print(f"HTTP {response.status_code}: {response.text}") response.raise_for_status()using System.Net.Http.Headers; using System.Text; using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("XTRM_ACCESS_TOKEN")); var json = """ { "IssuerAccountNumber": "SPN1111222", "SourceWalletId": 122181, "CustomerBatchId": "BATCH-GUIDE-0002", "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0004", "RecipientId": "SPN8888777", "Amount": 100, "SendMethodId": "XTR94500", "Destination": { "BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryBankPaymentMethod": "ACH" }, "Description": "TXN-GUIDE-0004 Q4 Executive Sales Performance Incentive" } ] } """; var response = await client.PostAsync( "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer", new StringContent(json, Encoding.UTF8, "application/json")); var body = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}: {body}"); response.EnsureSuccessStatusCode();import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; String json = """ { "IssuerAccountNumber": "SPN1111222", "SourceWalletId": 122181, "CustomerBatchId": "BATCH-GUIDE-0002", "Items": [ { "CustomerTransactionId": "TXN-GUIDE-0004", "RecipientId": "SPN8888777", "Amount": 100, "SendMethodId": "XTR94500", "Destination": { "BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995", "BeneficiaryBankPaymentMethod": "ACH" }, "Description": "TXN-GUIDE-0004 Q4 Executive Sales Performance Incentive" } ] } """; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer")) .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()); System.out.println(response.body());<?php $ch = curl_init('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode([ 'IssuerAccountNumber' => 'SPN1111222', 'SourceWalletId' => 122181, 'CustomerBatchId' => 'BATCH-GUIDE-0002', 'Items' => [ [ 'CustomerTransactionId' => 'TXN-GUIDE-0004', 'RecipientId' => 'SPN8888777', 'Amount' => 100, 'SendMethodId' => 'XTR94500', 'Destination' => [ 'BeneficiaryBankID' => '41953ec32f3e4765a35a902c82bdd995', 'BeneficiaryBankPaymentMethod' => 'ACH', ], 'Description' => 'TXN-GUIDE-0004 Q4 Executive Sales Performance Incentive', ], ], ]), CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('XTRM_ACCESS_TOKEN'), 'Content-Type: application/json', ], ]); $response = curl_exec($ch); print_r(json_decode($response, true));Xtrm answers
202, withTXN-GUIDE-0004inAccepted, and processes the payment again. The corrected bank ID takes effect becauseBANKID_INVALIDis a validation failure. Once Xtrm has finished, step 4's call forTXN-GUIDE-0004shows both attempts:Response{ "CustomerBatchId": "BATCH-GUIDE-0002", "CustomerTransactionId": "TXN-GUIDE-0004", "Status": "Success", "RecipientId": "SPN8888777", "SendMethodId": "XTR94500", "Amount": "100.00", "Currency": "USD", "DeliveryType": "Bank", "LastUpdatedAt": "2026-10-27T16:41:37.5520000Z", "Attempts": [ { "AttemptNo": 1, "Result": "Failed", "ErrorCode": "BANKID_INVALID", "CreatedAt": "2026-10-27T16:41:30.8030000Z", "CompletedAt": "2026-10-27T16:41:37.5520000Z" }, { "AttemptNo": 2, "Result": "Success", "ErrorCode": "SUCCESS", "CreatedAt": "2026-10-27T16:41:30.8030000Z", "CompletedAt": "2026-10-27T16:41:37.5520000Z" } ] }The payment is now
Success, and the failed first attempt stays in its history. On this endpoint every attempt repeats the payment's latest submission and update times, so go byAttemptNo, not the timestamps.Retry other failures the same way, once you've fixed the cause. A few things to know:
- Only a
Failedpayment can be retried. Resend only the payments you're retrying: any other payment you include comes back inRejectedasCONFLICT_DUPLICATE_ITEMand isn't paid again. - A corrected
Destinationtakes effect only after a validation failure, as here. After a failure at the wallet-credit stage, such asINSUFFICIENT_BALANCE, add funds and resend the payment unchanged: Xtrm keeps the destination it resolved the first time. - To pay a different recipient or use a different payment method, send a new payment with a new
CustomerTransactionIdinstead of changing the failed one. - Before you retry a payment whose latest attempt failed with
TEMPORARY_ERROR, contact Xtrm support: the money may already have moved.
For every rule, see Resubmit failed payments and Retry a batch payment.
Retry with the same IDs
Never retry a
Failedpayment under a newCustomerTransactionIdor a newCustomerBatchId. The same IDs are how Xtrm recognizes a retry and avoids paying twice; new IDs make it a new payment. Payments that were never stored are different: they go in a new batch, as described in Items rejected at submission.Keep for later: the
CustomerTransactionIdof each retried payment, to track its new attempt. - Only a
#What can go wrong
#The whole batch is refused
When the request fails a check on the whole batch, or none of its payments pass, Xtrm refuses the batch and stores nothing. For example:
- A
SourceWalletIdthat isn't an active wallet of your company, such as999999, gets403 Forbidden. - A missing
IssuerAccountNumberorCustomerBatchId, an emptyItemslist, more payments than your account's limit (LIMIT_EXCEEDED), or a batch whose every payment is rejected, gets422 Unprocessable Entity. When every payment is rejected and one of them isCONFLICT_DUPLICATE_ITEM, the status is409instead. - A
CustomerBatchIdthat is already in use, with none of its paymentsFailed, gets409 CONFLICT_PROCESSING. See Duplicate IDs and refused retries. - A missing or expired token gets
401 Unauthorized. Get a new token and send the same request again; see Authentication.
Log the full response body: it carries the reason in Key and Message, or error and error_message for a token problem. Fix the request and send it again. For every status and its body, see The whole request is refused.
#Items rejected at submission
A payment that fails the submit checks comes back in Rejected, with a Key, the Field that failed and a Message, while the rest of the batch goes ahead. For example, an Amount of 0, or a SendMethodId that isn't one of the seven batch methods, such as XTR99999, is rejected with INVALID_FIELD. What to do depends on the Key:
INVALID_FIELD,DUPLICATE_ITEM_IN_REQUESTorCURRENCY_MISMATCH. Xtrm didn't store the payment. Fix it and submit it in a new batch with a newCustomerBatchId; it can keep itsCustomerTransactionId.CONFLICT_DUPLICATE_ITEM. The payment is already stored in this batch, for example by an earlier request whose response you lost. Don't send it again, in this batch or a new one; follow it with the status endpoints.TEMPORARY_ERROR. Xtrm couldn't store the payment, but another request may have. Confirm with the payment status endpoint that it isn't stored, repeating the check a few times, at least a minute apart, before you submit it again; see A safe retry pattern.
See Items rejected at submission for every check.
#Duplicate IDs and refused retries
Xtrm uses your CustomerBatchId and CustomerTransactionId to tell a new payment from a resubmitted one. The same CustomerTransactionId twice in one request rejects every copy with DUPLICATE_ITEM_IN_REQUEST. Resending a stored payment under its original CustomerBatchId retries it if it's Failed, and otherwise returns CONFLICT_DUPLICATE_ITEM. A CustomerTransactionId you already used in a different batch is a new payment, and Xtrm pays it. So give every new payment a new CustomerTransactionId and every new batch a new CustomerBatchId, and never reuse an ID for a different payment. See Duplicate IDs.
#Payments that fail during processing
An accepted payment can still fail when Xtrm processes it. The latest attempt's ErrorCode says why. For example:
- A
RecipientIdthat isn't an Xtrm account, such asPAT0000001, fails withRECIPIENT_NOT_FOUND. Pay the right account as a new payment, with a newCustomerTransactionId. - A
BeneficiaryBankIDthat isn't linked to the recipient fails withBANKID_INVALID. Step 5 shows the fix. - A prepaid card
SKUthat isn't offered in the batch's currency, such asPREP0000, fails withSKU_NOT_FOUND. Take the SKU fromGetPrepaidCardsand retry. - A payment your source wallet can't cover, with its fee, when Xtrm processes it fails with
INSUFFICIENT_BALANCE. Add funds and retry it unchanged.
For every code and what to do about it, see Error codes on attempts. We recommend sending any code you don't recognize to manual review, and contacting support when you can't tell the cause from the code.
#Payments retained in a wallet
A bank, card, check, gift card or prepaid payment shows RetainedInWallet while Xtrm delivers it from the recipient's wallet, usually only briefly, before it moves on to Success. Don't act on it while its batch still reads Processing: it may still be on its way to the destination. If the payment is still RetainedInWallet once the batch status is final, the delivery didn't go through, and its newest attempt's ErrorCode says why. The money is in the recipient's Xtrm wallet, so treat it like a wallet payment: the recipient signs in to transfer it out (Xtrm emailed them when the money reached their wallet, if the batch set EmailNotification to true), or, if the recipient is connected to your company, you can request the transfer for them with their one-time password. You can't retry or resubmit the payment, and the fee isn't refunded. See When a payment stays RetainedInWallet.
#The batch stays in progress
A batch reads Processing while at least one of its payments is still in progress. We recommend capping your polling loop, as the full example does, so it can't run forever. If a batch is still Processing when your loop gives up, check it again later. A batch also stays Processing while Xtrm holds a payment's delivery, for example for a compliance review: the payment stays RetainedInWallet with no new attempt. If that lasts more than one business day, contact Xtrm support with the CustomerBatchId and CustomerTransactionId; see When a payment stays RetainedInWallet.
#Limits and other rules
- Batch size. Your account has a maximum number of payments per batch, and every request has a maximum size. Split a larger set of payments into several batches, each with its own
CustomerBatchId. See Limits. - One currency per batch. The source wallet sets the currency. To pay in several currencies, submit one batch per wallet. To move money into a wallet in another currency, see Exchange currency.
- One request per batch at a time. Xtrm accepts different batches at the same time, but never send two requests with the same
CustomerBatchIdat once. See Don't overlap requests for one batch.
#Full example
This program runs the whole flow. It gets an access token and submits the three-payment batch from step 2. It then polls the batch's status, reading every page each time, until the batch reads final and no payment is still Accepted, Processing or Verified (waiting 5 seconds, then twice as long each time up to 60 seconds, for at most 20 polls). While the batch reads Processing, it counts a RetainedInWallet payment as still in progress. Finally, it reads every payment again with its attempts and prints each payment's status with a note: paid, failed with the newest attempt's ErrorCode, in wallet, not delivered with the newest attempt's ErrorCode for a payment that stayed RetainedInWallet, or in progress. It reads XTRM_CLIENT_ID and XTRM_CLIENT_SECRET from the environment. Replace SPN1111222, the wallet ID and the recipients with your own values before you run it. CustomerBatchId values are shared across all Xtrm accounts, so also replace the sample IDs with your own unique values, for example ones that include your account number or a UUID.
#!/usr/bin/env bash
# Save as batch-payment.sh and run: bash batch-payment.sh
set -euo pipefail
BATCH_ID="BATCH-GUIDE-0001" # the CustomerBatchId in the body below
MAX_POLLS=20
# 1. Get an access token.
TOKEN_RESPONSE=$(curl -sS -X POST "https://xapisandbox.xtrm.com/oAuth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "grant_type=password" \
--data-urlencode "client_id=$XTRM_CLIENT_ID" \
--data-urlencode "client_secret=$XTRM_CLIENT_SECRET")
ACCESS_TOKEN=$(printf '%s' "$TOKEN_RESPONSE" | sed -n 's/.*"access_token" *: *"\([^"]*\)".*/\1/p')
if [ -z "$ACCESS_TOKEN" ]; then
echo "Token request failed: $TOKEN_RESPONSE" >&2
exit 1
fi
# 2. Submit the batch. Xtrm answers 202 Accepted when at least one item passes validation.
SUBMIT=$(curl -sS -w '\n%{http_code}' -X POST "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-GUIDE-0001",
"Items": [
{
"CustomerTransactionId": "TXN-GUIDE-0001",
"RecipientId": "SPN8888777",
"Amount": 100,
"SendMethodId": "XTR94500",
"Destination": {
"BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995",
"BeneficiaryBankPaymentMethod": "ACH"
},
"Description": "TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive"
},
{
"CustomerTransactionId": "TXN-GUIDE-0002",
"RecipientId": "SPN8888776",
"Amount": 50,
"SendMethodId": "XTR94504",
"Destination": {
"WalletId": 122311
},
"Description": "TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus"
},
{
"CustomerTransactionId": "TXN-GUIDE-0003",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001"
},
"Description": "TXN-GUIDE-0003 Q3 Top Performer Contractor Reward"
}
]
}')
HTTP_STATUS=$(printf '%s' "$SUBMIT" | tail -n 1)
SUBMIT_BODY=$(printf '%s' "$SUBMIT" | sed '$d' | tr -d '\r\n')
# In the documented response, the first Status is the batch's.
SUBMIT_STATUS=$( (printf '%s' "$SUBMIT_BODY" | grep -o '"Status" *: *"[^"]*"' || true) | sed -n '1s/.*"\([^"]*\)"$/\1/p')
case "$HTTP_STATUS" in
2??)
if [ "$SUBMIT_STATUS" = "Failed" ]; then
# TEMPORARY_ERROR: this call stored nothing, but an earlier request may have. Wait, then confirm
# what was stored with the batch status endpoint before you run the program again.
echo "This call stored nothing: $SUBMIT_BODY" >&2
exit 1
fi
echo "Submitted $BATCH_ID: $( (printf '%s' "$SUBMIT_BODY" | grep -o '"ItemsCount" *: *{[^}]*}' || true) | sed 's/^"ItemsCount" *: *//')"
# The pattern skips brackets inside strings, such as the item index in a rejected Field path.
echo "Rejected: $( (printf '%s' "$SUBMIT_BODY" | grep -oE '"Rejected" *: *\[([^]"]|"[^"]*")*\]' || true) | sed 's/^"Rejected" *: *//')"
;;
409)
# The batch ID is already in use, for example by an earlier batch of this program: track that batch.
echo "$BATCH_ID is already in use (HTTP 409): $SUBMIT_BODY"
;;
*) echo "Batch not accepted (HTTP $HTTP_STATUS): $SUBMIT_BODY" >&2; exit 1 ;;
esac
# Gets one page of the batch status, as a single line of JSON. $1 is recordsToSkip, $2 is history.
get_page() {
curl -sS -f "https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/$BATCH_ID?recordsToSkip=$1&recordsToTake=50&history=$2" \
-H "Authorization: Bearer $ACCESS_TOKEN" | tr -d '\r\n'
}
# Reads every page of the batch status. Prints the batch Status on the first line,
# then one line per item, with its attempts. $1 is history (true or false).
read_batch() {
local page next
page=$(get_page 0 "$1") || return 1
# In the documented response, the batch Status comes before the Items array.
echo "$( (printf '%s' "$page" | grep -o '"Status" *: *"[^"]*"' || true) | sed -n '1s/.*"\([^"]*\)"$/\1/p')"
while :; do
# Start a new line at each item, then drop the part before the first item.
printf '%s\n' "$page" | awk '{ gsub(/"CustomerTransactionId"/, "\n&"); print }' | sed '1d'
if [ "$( (printf '%s' "$page" | grep -o '"HasMore" *: *[a-z]*' || true) | sed 's/.*: *//')" != "true" ]; then
break
fi
next=$( (printf '%s' "$page" | grep -o '"NextRecordsToSkip" *: *[0-9]*' || true) | sed 's/.*: *//')
page=$(get_page "$next" "$1") || return 1
done
}
# Prints the first value of a string field in one line of JSON. $1 is the line, $2 the field name.
field() {
(printf '%s' "$1" | grep -o "\"$2\" *: *\"[^\"]*\"" || true) | sed -n '1s/.*"\([^"]*\)"$/\1/p'
}
# 3. Poll until the batch status is final and no item is still in progress, waiting longer
# between polls. A batch can read Failed or CompletedWithFailures while some items are
# still being validated, so check the items too.
DELAY=5
POLL=1
while :; do
BATCH=$(read_batch false)
BATCH_STATUS=$(printf '%s\n' "$BATCH" | sed -n '1p')
# While the batch reads Processing, a RetainedInWallet item is still on its way to the destination.
OPEN_STATUSES='Accepted|Processing|Verified'
if [ "$BATCH_STATUS" = "Processing" ]; then
OPEN_STATUSES="$OPEN_STATUSES|RetainedInWallet"
fi
# Each item line has one Status, the item's (attempts use Result).
OPEN=$(printf '%s\n' "$BATCH" | sed '1d' | grep -cE "\"Status\" *: *\"($OPEN_STATUSES)\"" || true)
echo "Poll $POLL: batch is $BATCH_STATUS, $OPEN item(s) still in progress"
case "$BATCH_STATUS" in
Completed | CompletedWithFailures | Failed)
if [ "$OPEN" -eq 0 ]; then
break
fi
;;
esac
if [ "$POLL" -ge "$MAX_POLLS" ]; then
echo "Batch still in progress after $MAX_POLLS polls. Check it again later." >&2
exit 1
fi
sleep "$DELAY"
DELAY=$(( DELAY * 2 > 60 ? 60 : DELAY * 2 ))
POLL=$(( POLL + 1 ))
done
# 4. Read every item again with its attempts, and print its status with a note.
read_batch true | sed '1d' | while IFS= read -r ITEM; do
STATUS=$(field "$ITEM" Status)
# The newest attempt is the one with the highest AttemptNo. In the documented response,
# each attempt lists AttemptNo, Result and ErrorCode in that order.
NEWEST=$( (printf '%s' "$ITEM" | grep -oE '"AttemptNo" *: *[0-9]+ *, *"Result" *: *"[^"]*" *, *"ErrorCode" *: *"[^"]*"' || true) \
| sed -E 's/"AttemptNo" *: *([0-9]+) *, *"Result" *: *"([^"]*)" *, *"ErrorCode" *: *"([^"]*)"/\1 \2 \3/' \
| sort -n | tail -n 1)
CODE=$(printf '%s' "$NEWEST" | cut -s -d ' ' -f 3)
# The batch is final here, so a RetainedInWallet item has stuck: its delivery didn't go through.
case "$STATUS" in
Success) NOTE="paid" ;;
Failed) NOTE="failed: $CODE" ;;
RetainedInWallet) NOTE="in wallet, not delivered: $CODE" ;;
*) NOTE="in progress" ;;
esac
echo "$(field "$ITEM" CustomerTransactionId) $STATUS $(field "$ITEM" Amount) $(field "$ITEM" RecipientId) $NOTE"
done// Save as batch-payment.mjs and run: node batch-payment.mjs (Node.js 18+)
const BATCH_ID = 'BATCH-GUIDE-0001'; // the CustomerBatchId in the body below
const FINAL_STATUSES = ['Completed', 'CompletedWithFailures', 'Failed'];
const OPEN_STATUSES = ['Accepted', 'Processing', 'Verified'];
const MAX_POLLS = 20;
// 1. Get an access token.
const tokenResponse = await fetch('https://xapisandbox.xtrm.com/oAuth/token', {
method: 'POST',
body: new URLSearchParams({
grant_type: 'password',
client_id: process.env.XTRM_CLIENT_ID,
client_secret: process.env.XTRM_CLIENT_SECRET,
}),
});
if (!tokenResponse.ok) throw new Error(`Token request failed with HTTP ${tokenResponse.status}`);
const { access_token: accessToken } = await tokenResponse.json();
const auth = { Authorization: `Bearer ${accessToken}` };
// 2. Submit the batch. Xtrm answers 202 Accepted when at least one item passes validation.
const submitResponse = await fetch('https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer', {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json' },
body: JSON.stringify({
IssuerAccountNumber: 'SPN1111222',
SourceWalletId: 122181,
CustomerBatchId: 'BATCH-GUIDE-0001',
Items: [
{
CustomerTransactionId: 'TXN-GUIDE-0001',
RecipientId: 'SPN8888777',
Amount: 100,
SendMethodId: 'XTR94500',
Destination: {
BeneficiaryBankID: '41953ec32f3e4765a35a902c82bdd995',
BeneficiaryBankPaymentMethod: 'ACH',
},
Description: 'TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive',
},
{
CustomerTransactionId: 'TXN-GUIDE-0002',
RecipientId: 'SPN8888776',
Amount: 50,
SendMethodId: 'XTR94504',
Destination: {
WalletId: 122311,
},
Description: 'TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus',
},
{
CustomerTransactionId: 'TXN-GUIDE-0003',
RecipientId: 'PAT9999888',
Amount: 50,
SendMethodId: 'XTR94503',
Destination: {
Email: '[email protected]',
SKU: 'PREP9001',
},
Description: 'TXN-GUIDE-0003 Q3 Top Performer Contractor Reward',
},
],
}),
});
const submitText = await submitResponse.text();
if (submitResponse.status === 409) {
// The batch ID is already in use, for example by an earlier batch of this program: track that batch.
console.log(`${BATCH_ID} is already in use (HTTP 409): ${submitText}`);
} else if (!submitResponse.ok) {
throw new Error(`Batch not accepted (HTTP ${submitResponse.status}): ${submitText}`);
} else {
const submitted = JSON.parse(submitText).BatchTransferResponse;
if (submitted.Status === 'Failed') {
// TEMPORARY_ERROR: this call stored nothing, but an earlier request may have. Wait, then confirm
// what was stored with the batch status endpoint before you run the program again.
throw new Error(`This call stored nothing: ${submitText}`);
}
const counts = submitted.ItemsCount;
console.log(`Batch ${submitted.CustomerBatchId}: ${counts.Accepted} of ${counts.Total} items accepted, ${counts.Rejected} rejected`);
for (const item of submitted.Rejected ?? []) {
console.log(` rejected ${item.CustomerTransactionId}: ${item.Field} ${item.Message}`);
}
}
// Gets one page of the batch status.
async function getPage(skip, history) {
const response = await fetch(
`https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/${BATCH_ID}?recordsToSkip=${skip}&recordsToTake=50&history=${history}`,
{ headers: auth },
);
if (!response.ok) throw new Error(`Status request failed with HTTP ${response.status}: ${await response.text()}`);
return response.json();
}
// Reads every page of the batch status and returns the first page with all of the batch's items.
async function readBatch(history) {
let page = await getPage(0, history);
const batch = { ...page, Items: [...page.Items] };
while (page.Pagination?.HasMore) {
page = await getPage(page.Pagination.NextRecordsToSkip, history);
batch.Items.push(...page.Items);
}
return batch;
}
// 3. Poll until the batch status is final and no item is still in progress, waiting longer between polls.
// A batch can read Failed or CompletedWithFailures while some items are still being validated,
// so check the items too.
let delaySeconds = 5;
for (let poll = 1; ; poll++) {
const batch = await readBatch(false);
// While the batch reads Processing, a RetainedInWallet item is still on its way to the destination.
const open = batch.Items.filter(
(item) => OPEN_STATUSES.includes(item.Status) || (batch.Status === 'Processing' && item.Status === 'RetainedInWallet'),
).length;
console.log(`Poll ${poll}: batch is ${batch.Status}, ${open} item(s) still in progress`);
if (FINAL_STATUSES.includes(batch.Status) && open === 0) break;
if (poll >= MAX_POLLS) throw new Error(`Batch still in progress after ${MAX_POLLS} polls. Check it again later.`);
await new Promise((resolve) => setTimeout(resolve, delaySeconds * 1000));
delaySeconds = Math.min(delaySeconds * 2, 60);
}
// 4. Read every item again with its attempts, and print its status with a note.
const report = await readBatch(true);
for (const item of report.Items) {
// The newest attempt is the one with the highest AttemptNo.
const newest = [...(item.Attempts ?? [])].sort((a, b) => b.AttemptNo - a.AttemptNo)[0];
let note = 'in progress';
if (item.Status === 'Success') note = 'paid';
else if (item.Status === 'Failed') note = `failed: ${newest?.ErrorCode ?? ''}`;
// The batch is final here, so a RetainedInWallet item has stuck: its delivery didn't go through.
else if (item.Status === 'RetainedInWallet') note = `in wallet, not delivered: ${newest?.ErrorCode ?? ''}`;
console.log(`${item.CustomerTransactionId} ${item.Status} ${item.Amount} ${report.Currency} ${item.RecipientId} ${note}`);
}# Save as batch_payment.py and run: python batch_payment.py (Python 3 with requests)
import os
import sys
import time
import requests
BATCH_ID = "BATCH-GUIDE-0001" # the CustomerBatchId in the body below
FINAL_STATUSES = {"Completed", "CompletedWithFailures", "Failed"}
OPEN_STATUSES = {"Accepted", "Processing", "Verified"}
MAX_POLLS = 20
# 1. Get an access token.
response = requests.post(
"https://xapisandbox.xtrm.com/oAuth/token",
data={
"grant_type": "password",
"client_id": os.environ["XTRM_CLIENT_ID"],
"client_secret": os.environ["XTRM_CLIENT_SECRET"],
},
)
response.raise_for_status()
headers = {"Authorization": f"Bearer {response.json()['access_token']}"}
# 2. Submit the batch. Xtrm answers 202 Accepted when at least one item passes validation.
response = requests.post(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer",
headers=headers,
json={
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-GUIDE-0001",
"Items": [
{
"CustomerTransactionId": "TXN-GUIDE-0001",
"RecipientId": "SPN8888777",
"Amount": 100,
"SendMethodId": "XTR94500",
"Destination": {
"BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995",
"BeneficiaryBankPaymentMethod": "ACH",
},
"Description": "TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive",
},
{
"CustomerTransactionId": "TXN-GUIDE-0002",
"RecipientId": "SPN8888776",
"Amount": 50,
"SendMethodId": "XTR94504",
"Destination": {
"WalletId": 122311,
},
"Description": "TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus",
},
{
"CustomerTransactionId": "TXN-GUIDE-0003",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001",
},
"Description": "TXN-GUIDE-0003 Q3 Top Performer Contractor Reward",
},
],
},
)
if response.status_code == 409:
# The batch ID is already in use, for example by an earlier batch of this program: track that batch.
print(f"{BATCH_ID} is already in use (HTTP 409): {response.text}")
elif not response.ok:
sys.exit(f"Batch not accepted (HTTP {response.status_code}): {response.text}")
else:
submitted = response.json()["BatchTransferResponse"]
if submitted["Status"] == "Failed":
# TEMPORARY_ERROR: this call stored nothing, but an earlier request may have. Wait, then confirm
# what was stored with the batch status endpoint before you run the program again.
sys.exit(f"This call stored nothing: {response.text}")
counts = submitted["ItemsCount"]
print(
f"Batch {submitted['CustomerBatchId']}: {counts['Accepted']} of {counts['Total']} items accepted, "
f"{counts['Rejected']} rejected"
)
for item in submitted.get("Rejected") or []:
print(f" rejected {item['CustomerTransactionId']}: {item['Field']} {item['Message']}")
def get_page(skip, history):
"""Gets one page of the batch status."""
response = requests.get(
f"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/{BATCH_ID}",
headers=headers,
params={"recordsToSkip": skip, "recordsToTake": 50, "history": "true" if history else "false"},
)
response.raise_for_status()
return response.json()
def read_batch(history):
"""Reads every page of the batch status and returns the first page with all of the batch's items."""
page = get_page(0, history)
batch = dict(page, Items=list(page["Items"]))
while (page.get("Pagination") or {}).get("HasMore"):
page = get_page(page["Pagination"]["NextRecordsToSkip"], history)
batch["Items"].extend(page["Items"])
return batch
# 3. Poll until the batch status is final and no item is still in progress, waiting longer between polls.
# A batch can read Failed or CompletedWithFailures while some items are still being validated,
# so check the items too.
delay = 5
for poll in range(1, MAX_POLLS + 1):
batch = read_batch(history=False)
# While the batch reads Processing, a RetainedInWallet item is still on its way to the destination.
open_statuses = (OPEN_STATUSES | {"RetainedInWallet"}) if batch["Status"] == "Processing" else OPEN_STATUSES
still_open = sum(1 for item in batch["Items"] if item["Status"] in open_statuses)
print(f"Poll {poll}: batch is {batch['Status']}, {still_open} item(s) still in progress")
if batch["Status"] in FINAL_STATUSES and still_open == 0:
break
if poll == MAX_POLLS:
sys.exit(f"Batch still in progress after {MAX_POLLS} polls. Check it again later.")
time.sleep(delay)
delay = min(delay * 2, 60)
# 4. Read every item again with its attempts, and print its status with a note.
report = read_batch(history=True)
for item in report["Items"]:
# The newest attempt is the one with the highest AttemptNo.
newest = max(item.get("Attempts") or [], key=lambda attempt: attempt["AttemptNo"], default=None)
if item["Status"] == "Success":
note = "paid"
elif item["Status"] == "Failed":
note = f"failed: {newest['ErrorCode'] if newest else ''}"
elif item["Status"] == "RetainedInWallet":
# The batch is final here, so a RetainedInWallet item has stuck: its delivery didn't go through.
note = f"in wallet, not delivered: {newest['ErrorCode'] if newest else ''}"
else:
note = "in progress"
print(f"{item['CustomerTransactionId']} {item['Status']} {item['Amount']} {report['Currency']} {item['RecipientId']} {note}")// Create a console app (dotnet new console), replace Program.cs with this file, then run: dotnet run
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
const string BatchId = "BATCH-GUIDE-0001"; // the CustomerBatchId in the body below
const int MaxPolls = 20;
string[] finalStatuses = { "Completed", "CompletedWithFailures", "Failed" };
string[] openStatuses = { "Accepted", "Processing", "Verified" };
using var client = new HttpClient();
// 1. Get an access token.
var form = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "password",
["client_id"] = Environment.GetEnvironmentVariable("XTRM_CLIENT_ID")!,
["client_secret"] = Environment.GetEnvironmentVariable("XTRM_CLIENT_SECRET")!,
});
var tokenResponse = await client.PostAsync("https://xapisandbox.xtrm.com/oAuth/token", form);
tokenResponse.EnsureSuccessStatusCode();
var token = await tokenResponse.Content.ReadFromJsonAsync<JsonElement>();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token.GetProperty("access_token").GetString());
// 2. Submit the batch. Xtrm answers 202 Accepted when at least one item passes validation.
var batchJson = """
{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-GUIDE-0001",
"Items": [
{
"CustomerTransactionId": "TXN-GUIDE-0001",
"RecipientId": "SPN8888777",
"Amount": 100,
"SendMethodId": "XTR94500",
"Destination": {
"BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995",
"BeneficiaryBankPaymentMethod": "ACH"
},
"Description": "TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive"
},
{
"CustomerTransactionId": "TXN-GUIDE-0002",
"RecipientId": "SPN8888776",
"Amount": 50,
"SendMethodId": "XTR94504",
"Destination": {
"WalletId": 122311
},
"Description": "TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus"
},
{
"CustomerTransactionId": "TXN-GUIDE-0003",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001"
},
"Description": "TXN-GUIDE-0003 Q3 Top Performer Contractor Reward"
}
]
}
""";
var submitResponse = await client.PostAsync(
"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer",
new StringContent(batchJson, Encoding.UTF8, "application/json"));
var submitBody = await submitResponse.Content.ReadAsStringAsync();
var submitStatus = (int)submitResponse.StatusCode;
if (submitStatus == 409)
{
// The batch ID is already in use, for example by an earlier batch of this program: track that batch.
Console.WriteLine($"{BatchId} is already in use (HTTP 409): {submitBody}");
}
else if (!submitResponse.IsSuccessStatusCode)
{
Console.Error.WriteLine($"Batch not accepted (HTTP {submitStatus}): {submitBody}");
return 1;
}
else
{
var submitted = JsonDocument.Parse(submitBody).RootElement.GetProperty("BatchTransferResponse");
if (submitted.GetProperty("Status").GetString() == "Failed")
{
// TEMPORARY_ERROR: this call stored nothing, but an earlier request may have. Wait, then confirm
// what was stored with the batch status endpoint before you run the program again.
Console.Error.WriteLine($"This call stored nothing: {submitBody}");
return 1;
}
var counts = submitted.GetProperty("ItemsCount");
Console.WriteLine($"Batch {submitted.GetProperty("CustomerBatchId")}: {counts.GetProperty("Accepted")} of " +
$"{counts.GetProperty("Total")} items accepted, {counts.GetProperty("Rejected")} rejected");
if (submitted.TryGetProperty("Rejected", out var rejected) && rejected.ValueKind == JsonValueKind.Array)
{
foreach (var item in rejected.EnumerateArray())
{
Console.WriteLine($" rejected {item.GetProperty("CustomerTransactionId")}: " +
$"{item.GetProperty("Field")} {item.GetProperty("Message")}");
}
}
}
// 3. Poll until the batch status is final and no item is still in progress, waiting longer between polls.
// A batch can read Failed or CompletedWithFailures while some items are still being validated,
// so check the items too.
var delaySeconds = 5;
for (var poll = 1; ; poll++)
{
var (status, _, items) = await ReadBatch(false);
// While the batch reads Processing, a RetainedInWallet item is still on its way to the destination.
var open = items.Count(item =>
{
var current = item.GetProperty("Status").GetString();
return openStatuses.Contains(current) || (status == "Processing" && current == "RetainedInWallet");
});
Console.WriteLine($"Poll {poll}: batch is {status}, {open} item(s) still in progress");
if (finalStatuses.Contains(status) && open == 0)
{
break;
}
if (poll >= MaxPolls)
{
Console.Error.WriteLine($"Batch still in progress after {MaxPolls} polls. Check it again later.");
return 1;
}
await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
delaySeconds = Math.Min(delaySeconds * 2, 60);
}
// 4. Read every item again with its attempts, and print its status with a note.
var (_, currency, report) = await ReadBatch(true);
foreach (var item in report)
{
var itemStatus = item.GetProperty("Status").GetString();
// The newest attempt is the one with the highest AttemptNo.
JsonElement? newest = item.GetProperty("Attempts").EnumerateArray()
.OrderByDescending(attempt => attempt.GetProperty("AttemptNo").GetInt32())
.Select(attempt => (JsonElement?)attempt)
.FirstOrDefault();
var errorCode = newest?.GetProperty("ErrorCode").GetString();
// The batch is final here, so a RetainedInWallet item has stuck: its delivery didn't go through.
var note = itemStatus switch
{
"Success" => "paid",
"Failed" => $"failed: {errorCode}",
"RetainedInWallet" => $"in wallet, not delivered: {errorCode}",
_ => "in progress",
};
Console.WriteLine($"{item.GetProperty("CustomerTransactionId")} {itemStatus} {item.GetProperty("Amount")} " +
$"{currency} {item.GetProperty("RecipientId")} {note}");
}
return 0;
// Gets one page of the batch status.
async Task<JsonElement> GetPage(int skip, bool history)
{
var response = await client.GetAsync(
$"https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/{BatchId}?recordsToSkip={skip}&recordsToTake=50&history={(history ? "true" : "false")}");
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<JsonElement>();
}
// Reads every page of the batch status: the batch Status, its Currency and all of its items.
async Task<(string Status, string Currency, List<JsonElement> Items)> ReadBatch(bool history)
{
var page = await GetPage(0, history);
var batchStatus = page.GetProperty("Status").GetString() ?? "";
var batchCurrency = page.GetProperty("Currency").GetString() ?? "";
var allItems = new List<JsonElement>();
while (true)
{
allItems.AddRange(page.GetProperty("Items").EnumerateArray());
var pagination = page.GetProperty("Pagination");
if (!pagination.GetProperty("HasMore").GetBoolean())
{
break;
}
page = await GetPage(pagination.GetProperty("NextRecordsToSkip").GetInt32(), history);
}
return (batchStatus, batchCurrency, allItems);
}// Save as BatchPayment.java and run: java BatchPayment.java (Java 17+)
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BatchPayment {
private static final HttpClient CLIENT = HttpClient.newHttpClient();
private static final String BATCH_ID = "BATCH-GUIDE-0001"; // the CustomerBatchId in the body below
private static final List<String> FINAL_STATUSES = List.of("Completed", "CompletedWithFailures", "Failed");
private static final List<String> OPEN_STATUSES = List.of("Accepted", "Processing", "Verified");
private static final int MAX_POLLS = 20;
public static void main(String[] args) throws Exception {
// 1. Get an access token.
String form = "grant_type=password"
+ "&client_id=" + URLEncoder.encode(System.getenv("XTRM_CLIENT_ID"), StandardCharsets.UTF_8)
+ "&client_secret=" + URLEncoder.encode(System.getenv("XTRM_CLIENT_SECRET"), StandardCharsets.UTF_8);
HttpResponse<String> token = CLIENT.send(HttpRequest.newBuilder()
.uri(URI.create("https://xapisandbox.xtrm.com/oAuth/token"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(form))
.build(), HttpResponse.BodyHandlers.ofString());
String accessToken = field(token.body(), "access_token");
if (token.statusCode() / 100 != 2 || accessToken == null) {
throw new IllegalStateException("Token request failed: " + token.body());
}
// 2. Submit the batch. Xtrm answers 202 Accepted when at least one item passes validation.
String batch = """
{
"IssuerAccountNumber": "SPN1111222",
"SourceWalletId": 122181,
"CustomerBatchId": "BATCH-GUIDE-0001",
"Items": [
{
"CustomerTransactionId": "TXN-GUIDE-0001",
"RecipientId": "SPN8888777",
"Amount": 100,
"SendMethodId": "XTR94500",
"Destination": {
"BeneficiaryBankID": "41953ec32f3e4765a35a902c82bdd995",
"BeneficiaryBankPaymentMethod": "ACH"
},
"Description": "TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive"
},
{
"CustomerTransactionId": "TXN-GUIDE-0002",
"RecipientId": "SPN8888776",
"Amount": 50,
"SendMethodId": "XTR94504",
"Destination": {
"WalletId": 122311
},
"Description": "TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus"
},
{
"CustomerTransactionId": "TXN-GUIDE-0003",
"RecipientId": "PAT9999888",
"Amount": 50,
"SendMethodId": "XTR94503",
"Destination": {
"Email": "[email protected]",
"SKU": "PREP9001"
},
"Description": "TXN-GUIDE-0003 Q3 Top Performer Contractor Reward"
}
]
}
""";
HttpResponse<String> submitted = CLIENT.send(HttpRequest.newBuilder()
.uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer"))
.header("Authorization", "Bearer " + accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(batch))
.build(), HttpResponse.BodyHandlers.ofString());
if (submitted.statusCode() == 409) {
// The batch ID is already in use, for example by an earlier batch of this program: track that batch.
System.out.println(BATCH_ID + " is already in use (HTTP 409): " + submitted.body());
} else if (submitted.statusCode() / 100 != 2) {
throw new IllegalStateException(
"Batch not accepted (HTTP " + submitted.statusCode() + "): " + submitted.body());
} else if ("Failed".equals(field(submitted.body(), "Status"))) {
// TEMPORARY_ERROR: this call stored nothing, but an earlier request may have. Wait, then confirm
// what was stored with the batch status endpoint before you run the program again.
// In the documented response, the first Status is the batch's.
throw new IllegalStateException("This call stored nothing: " + submitted.body());
} else {
System.out.println("Submitted " + BATCH_ID + ": " + find(submitted.body(), "\"ItemsCount\"\\s*:\\s*\\{[^}]*\\}"));
// Skips brackets inside strings, such as the item index in a rejected Field path.
System.out.println(find(submitted.body(), "\"Rejected\"\\s*:\\s*\\[(?:[^\\]\"]++|\"[^\"]*+\")*+\\]"));
}
// 3. Poll until the batch status is final and no item is still in progress, waiting longer between polls.
// A batch can read Failed or CompletedWithFailures while some items are still being validated,
// so check the items too.
int delaySeconds = 5;
for (int poll = 1; ; poll++) {
Batch current = readBatch(accessToken, false);
// While the batch reads Processing, a RetainedInWallet item is still on its way to the destination.
boolean batchProcessing = "Processing".equals(current.status());
long open = current.items().stream()
.map(item -> field(item, "Status"))
.filter(status -> status != null
&& (OPEN_STATUSES.contains(status) || (batchProcessing && status.equals("RetainedInWallet"))))
.count();
System.out.println("Poll " + poll + ": batch is " + current.status() + ", " + open + " item(s) still in progress");
if (current.status() != null && FINAL_STATUSES.contains(current.status()) && open == 0) {
break;
}
if (poll >= MAX_POLLS) {
throw new IllegalStateException(
"Batch still in progress after " + MAX_POLLS + " polls. Check it again later.");
}
Thread.sleep(delaySeconds * 1000L);
delaySeconds = Math.min(delaySeconds * 2, 60);
}
// 4. Read every item again with its attempts, and print its status with a note.
Batch report = readBatch(accessToken, true);
for (String item : report.items()) {
String status = field(item, "Status");
String newest = newestAttempt(item);
String errorCode = newest == null ? "" : field(newest, "ErrorCode");
String note;
if ("Success".equals(status)) {
note = "paid";
} else if ("Failed".equals(status)) {
note = "failed: " + errorCode;
} else if ("RetainedInWallet".equals(status)) {
// The batch is final here, so a RetainedInWallet item has stuck: its delivery didn't go through.
note = "in wallet, not delivered: " + errorCode;
} else {
note = "in progress";
}
System.out.println(field(item, "CustomerTransactionId") + " " + status + " " + field(item, "Amount") + " "
+ report.currency() + " " + field(item, "RecipientId") + " " + note);
}
}
// The batch Status and Currency, and one JSON chunk per item.
private record Batch(String status, String currency, List<String> items) {
}
// Gets one page of the batch status.
private static String getPage(String accessToken, int skip, boolean history) throws Exception {
HttpResponse<String> response = CLIENT.send(HttpRequest.newBuilder()
.uri(URI.create("https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/" + BATCH_ID
+ "?recordsToSkip=" + skip + "&recordsToTake=50&history=" + history))
.header("Authorization", "Bearer " + accessToken)
.GET()
.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() / 100 != 2) {
throw new IllegalStateException(
"Status request failed (HTTP " + response.statusCode() + "): " + response.body());
}
return response.body();
}
// Reads every page of the batch status.
private static Batch readBatch(String accessToken, boolean history) throws Exception {
String page = getPage(accessToken, 0, history);
String head = batchFields(page);
List<String> items = new ArrayList<>();
while (true) {
int itemsAt = page.indexOf("\"Items\"");
if (itemsAt >= 0) {
// Each item starts with its CustomerTransactionId. Attempts use Result, not Status,
// so the only Status in each chunk is the item's.
for (String item : page.substring(itemsAt).split("(?=\"CustomerTransactionId\")")) {
if (item.startsWith("\"CustomerTransactionId\"")) {
items.add(item);
}
}
}
if (!"true".equals(field(page, "HasMore"))) {
break;
}
page = getPage(accessToken, Integer.parseInt(field(page, "NextRecordsToSkip")), history);
}
return new Batch(field(head, "Status"), field(head, "Currency"), items);
}
// The batch-level part of a status page. In the documented response, these fields come before Items.
private static String batchFields(String page) {
int itemsAt = page.indexOf("\"Items\"");
return itemsAt < 0 ? page : page.substring(0, itemsAt);
}
// Returns the attempt with the highest AttemptNo in an item chunk, or null when it has none.
private static String newestAttempt(String item) {
String newest = null;
int newestNo = -1;
for (String attempt : item.split("(?=\"AttemptNo\")")) {
if (attempt.startsWith("\"AttemptNo\"")) {
int attemptNo = Integer.parseInt(field(attempt, "AttemptNo"));
if (attemptNo > newestNo) {
newestNo = attemptNo;
newest = attempt;
}
}
}
return newest;
}
// Reads the first value of a field from a JSON string. This keeps the example free of
// dependencies; we recommend a JSON library such as Jackson in production code.
private static String field(String json, String name) {
Matcher m = Pattern.compile("\"" + Pattern.quote(name) + "\"\\s*:\\s*(?:\"([^\"]*)\"|([^,}\\]\\s]+))").matcher(json);
if (!m.find()) {
return null;
}
return m.group(1) != null ? m.group(1) : m.group(2);
}
// Returns the first match of a regular expression, or an empty string.
private static String find(String text, String regex) {
Matcher m = Pattern.compile(regex).matcher(text);
return m.find() ? m.group() : "";
}
}<?php
// Save as batch_payment.php and run: php batch_payment.php (PHP 8 with the curl extension)
const BATCH_ID = 'BATCH-GUIDE-0001'; // the CustomerBatchId in the body below
const FINAL_STATUSES = ['Completed', 'CompletedWithFailures', 'Failed'];
const OPEN_STATUSES = ['Accepted', 'Processing', 'Verified'];
const MAX_POLLS = 20;
// Sends a request (a POST when there is a body) and returns the HTTP status and the response body.
function xtrm_request(string $url, array $headers, ?string $body = null): array
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$response = curl_exec($ch);
if ($response === false) {
throw new RuntimeException("$url failed: " . curl_error($ch));
}
return [curl_getinfo($ch, CURLINFO_RESPONSE_CODE), $response];
}
// Gets one page of the batch status.
function get_page(array $headers, int $skip, bool $history): array
{
[$status, $body] = xtrm_request(
'https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer/' . BATCH_ID
. "?recordsToSkip=$skip&recordsToTake=50&history=" . ($history ? 'true' : 'false'),
$headers
);
if ($status >= 300) {
throw new RuntimeException("Status request failed with HTTP $status: $body");
}
return json_decode($body, true);
}
// Reads every page of the batch status and returns the first page with all of the batch's items.
function read_batch(array $headers, bool $history): array
{
$page = get_page($headers, 0, $history);
$batch = $page;
while (!empty($page['Pagination']['HasMore'])) {
$page = get_page($headers, $page['Pagination']['NextRecordsToSkip'], $history);
$batch['Items'] = array_merge($batch['Items'], $page['Items']);
}
return $batch;
}
// 1. Get an access token.
[$status, $body] = xtrm_request('https://xapisandbox.xtrm.com/oAuth/token', [
'Content-Type: application/x-www-form-urlencoded',
], http_build_query([
'grant_type' => 'password',
'client_id' => getenv('XTRM_CLIENT_ID'),
'client_secret' => getenv('XTRM_CLIENT_SECRET'),
]));
$token = json_decode($body, true);
if ($status >= 300 || empty($token['access_token'])) {
throw new RuntimeException("Token request failed: $body");
}
$auth = ['Authorization: Bearer ' . $token['access_token']];
// 2. Submit the batch. Xtrm answers 202 Accepted when at least one item passes validation.
[$status, $body] = xtrm_request(
'https://xapisandbox.xtrm.com/API/v4/Fund/BatchTransfer',
[...$auth, 'Content-Type: application/json'],
json_encode([
'IssuerAccountNumber' => 'SPN1111222',
'SourceWalletId' => 122181,
'CustomerBatchId' => 'BATCH-GUIDE-0001',
'Items' => [
[
'CustomerTransactionId' => 'TXN-GUIDE-0001',
'RecipientId' => 'SPN8888777',
'Amount' => 100,
'SendMethodId' => 'XTR94500',
'Destination' => [
'BeneficiaryBankID' => '41953ec32f3e4765a35a902c82bdd995',
'BeneficiaryBankPaymentMethod' => 'ACH',
],
'Description' => 'TXN-GUIDE-0001 Q3 Executive Sales Performance Incentive',
],
[
'CustomerTransactionId' => 'TXN-GUIDE-0002',
'RecipientId' => 'SPN8888776',
'Amount' => 50,
'SendMethodId' => 'XTR94504',
'Destination' => [
'WalletId' => 122311,
],
'Description' => 'TXN-GUIDE-0002 Q3 Channel Partner Marketing Bonus',
],
[
'CustomerTransactionId' => 'TXN-GUIDE-0003',
'RecipientId' => 'PAT9999888',
'Amount' => 50,
'SendMethodId' => 'XTR94503',
'Destination' => [
'Email' => '[email protected]',
'SKU' => 'PREP9001',
],
'Description' => 'TXN-GUIDE-0003 Q3 Top Performer Contractor Reward',
],
],
])
);
if ($status === 409) {
// The batch ID is already in use, for example by an earlier batch of this program: track that batch.
echo BATCH_ID . " is already in use (HTTP 409): $body", PHP_EOL;
} elseif (intdiv($status, 100) !== 2) {
fwrite(STDERR, "Batch not accepted (HTTP $status): $body\n");
exit(1);
} else {
$submitted = json_decode($body, true)['BatchTransferResponse'];
if ($submitted['Status'] === 'Failed') {
// TEMPORARY_ERROR: this call stored nothing, but an earlier request may have. Wait, then confirm
// what was stored with the batch status endpoint before you run the program again.
fwrite(STDERR, "This call stored nothing: $body\n");
exit(1);
}
$counts = $submitted['ItemsCount'];
printf(
"Batch %s: %d of %d items accepted, %d rejected\n",
$submitted['CustomerBatchId'],
$counts['Accepted'],
$counts['Total'],
$counts['Rejected']
);
foreach ($submitted['Rejected'] ?? [] as $item) {
printf(" rejected %s: %s %s\n", $item['CustomerTransactionId'], $item['Field'], $item['Message']);
}
}
// 3. Poll until the batch status is final and no item is still in progress, waiting longer between polls.
// A batch can read Failed or CompletedWithFailures while some items are still being validated,
// so check the items too.
$delay = 5;
for ($poll = 1; ; $poll++) {
$batch = read_batch($auth, false);
// While the batch reads Processing, a RetainedInWallet item is still on its way to the destination.
$openStatuses = $batch['Status'] === 'Processing' ? [...OPEN_STATUSES, 'RetainedInWallet'] : OPEN_STATUSES;
$open = count(array_filter($batch['Items'], fn ($item) => in_array($item['Status'], $openStatuses, true)));
echo "Poll $poll: batch is {$batch['Status']}, $open item(s) still in progress", PHP_EOL;
if (in_array($batch['Status'], FINAL_STATUSES, true) && $open === 0) {
break;
}
if ($poll >= MAX_POLLS) {
fwrite(STDERR, 'Batch still in progress after ' . MAX_POLLS . " polls. Check it again later.\n");
exit(1);
}
sleep($delay);
$delay = min($delay * 2, 60);
}
// 4. Read every item again with its attempts, and print its status with a note.
$report = read_batch($auth, true);
foreach ($report['Items'] as $item) {
// The newest attempt is the one with the highest AttemptNo.
$attempts = $item['Attempts'] ?? [];
usort($attempts, fn ($a, $b) => $b['AttemptNo'] <=> $a['AttemptNo']);
$newest = $attempts[0] ?? null;
// The batch is final here, so a RetainedInWallet item has stuck: its delivery didn't go through.
$note = match (true) {
$item['Status'] === 'Success' => 'paid',
$item['Status'] === 'Failed' => 'failed: ' . ($newest['ErrorCode'] ?? ''),
$item['Status'] === 'RetainedInWallet' => 'in wallet, not delivered: ' . ($newest['ErrorCode'] ?? ''),
default => 'in progress',
};
printf(
"%s %s %s %s %s %s\n",
$item['CustomerTransactionId'],
$item['Status'],
$item['Amount'],
$report['Currency'],
$item['RecipientId'],
$note
);
}The cURL version reads the responses with grep, sed and awk; for anything more, use a JSON tool such as jq. The Java version reads fields with regular expressions to avoid dependencies; we recommend a JSON library such as Jackson in production code.
Act on the notes the program prints. Fix and retry failed payments as in step 5. The note in wallet, not delivered marks a payment that stayed RetainedInWallet after the batch finished: the money is in the recipient's Xtrm wallet, and you can't retry the payment; see Payments retained in a wallet.
The program sends fixed IDs, so running it again resends BATCH-GUIDE-0001 instead of creating a new batch. Xtrm retries any Failed payment as a new attempt and returns the others in Rejected as CONFLICT_DUPLICATE_ITEM without paying them again. If no payment in the batch is Failed, Xtrm answers 409, and the program tracks the existing batch. If Xtrm answers 202 with Status Failed, that call stored nothing and the program stops; see A safe retry pattern. To create a new batch, change CustomerBatchId and every CustomerTransactionId.
#Next steps
How a batch is processed and wallet-first delivery, end to end.
Batch paymentsBatch and payment statusesEvery batch, payment and attempt status, and what to do about each.
Batch paymentsWebhooksReceive batch and payment events instead of polling.
Batch paymentsRetries & idempotencyResubmit a batch safely and never pay anyone twice.
GuideTrack & reconcile paymentsMatch wallet transactions to your own records.
API referenceBatch paymentsEvery field of the three batch payment endpoints.