Transactions and Their Messages
Read every transaction of a subaccount page by page, newest first, with the messages the card network sent for each one, in the order Astrada recorded them.
For: developers
A transaction is the summary: status, amounts, merchant. Its messages are what the card network sent: the authorization, then the clearing, a reversal or a refund. This recipe reads every transaction of a subaccount, page by page and newest first, and for each one fetches the messages its _links.messages lists, in the order Astrada recorded them (createdDateTime).
Before you start
- Scopes:
transactions:readandtransaction-messages:read. - A subaccount with transactions. In the sandbox, simulate card activity on an enrolled card: Sandbox API Reference.
- Sandbox or production.
The code
Read transactions with their messages
Pages are fetched as you read: stop the loop and no more pages are read. The code fetches one message at a time, which stays well clear of rate limits.
/** One transaction and its messages. */
export interface TransactionWithMessages {
transaction: Transaction;
messages: TransactionMessage[];
}
/** The message id at the end of a link. A link is `{ href }`; a bare path string is read too. */
export function messageIdOf(link: { href: string } | string): string {
const href = typeof link === 'string' ? link : link.href;
const id = href.split('?')[0]!.split('/').filter(Boolean).pop();
if (!id) throw new Error(`No message id in link ${href}`);
return id;
}@dataclass
class TransactionWithMessages:
"""One transaction and its messages."""
transaction: astrada.Transaction
messages: List[astrada.TransactionMessage]
def message_id_of(link: astrada.Link) -> str:
"""The message id at the end of a link. (A link sent as a bare path is read as its href.)"""
href = link.href or ""
message_id = next((part for part in reversed(href.split("?")[0].split("/")) if part), None)
if not message_id:
raise ValueError("No message id in link %r" % href)
return message_id/** One transaction and its messages. */
public static final class TransactionWithMessages {
public final Transaction transaction;
public final List<TransactionMessage> messages;
TransactionWithMessages(Transaction transaction, List<TransactionMessage> messages) {
this.transaction = transaction;
this.messages = messages;
}
}
/** The message id at the end of a link. (A link sent as a bare path is read as its href.) */
public static UUID messageIdOf(Link link) {
String href = link.getHref() == null ? "" : link.getHref();
String path = href.split("\\?", 2)[0];
String[] parts = path.split("/");
for (int i = parts.length - 1; i >= 0; i--) {
if (!parts[i].isEmpty()) {
return UUID.fromString(parts[i]);
}
}
throw new IllegalArgumentException("No message id in link " + href);
}The function that reads the transactions and their messages, page by page:
/**
* Yields each transaction of the subaccount with its messages. Pages are fetched as you read:
* stop the loop and no more pages are read. `maxTransactions` caps the total.
*/
export async function* transactionsWithMessages(
astrada: Astrada,
subaccountId: string,
maxTransactions?: number,
): AsyncGenerator<TransactionWithMessages> {
for await (const transaction of astrada.transactions.listAll({ subaccountId, order: 'desc', limit: 50 }, { maxItems: maxTransactions })) {
const messages: TransactionMessage[] = [];
// One call per message, one at a time, which stays well clear of rate limits.
for (const link of transaction._links?.messages ?? []) {
messages.push(await astrada.transactionMessages.get(messageIdOf(link)));
}
// A message without a readable createdDateTime goes last rather than upsetting the sort.
const time = (message: TransactionMessage) => {
const parsed = Date.parse(message.createdDateTime);
return Number.isNaN(parsed) ? Number.MAX_SAFE_INTEGER : parsed;
};
messages.sort((a, b) => time(a) - time(b));
yield { transaction, messages };
}
}def transactions_with_messages(
client: astrada.Astrada, subaccount_id: str, max_transactions: Optional[int] = None
) -> Iterator[TransactionWithMessages]:
"""Yields each transaction of the subaccount with its messages. Pages are fetched as you read:
stop the loop and no more pages are read. `max_transactions` caps the total."""
transactions = client.transactions.list_all(subaccount_id=subaccount_id, order="desc", limit=50)
for transaction in itertools.islice(transactions, max_transactions):
# One call per message, one at a time, which stays well clear of rate limits.
messages = [client.transaction_messages.get(message_id_of(link))
for link in transaction.links.messages or []]
messages.sort(key=lambda message: message.created_date_time)
yield TransactionWithMessages(transaction, messages)/**
* Hands each transaction of the subaccount, with its messages, to {@code each}. Pages are fetched
* as the loop reaches them, and {@code maxTransactions} (null for all) stops it early.
*/
public static void forEachTransaction(ApiClient client, UUID subaccountId, Integer maxTransactions,
Consumer<TransactionWithMessages> each) {
int seen = 0;
for (Transaction transaction : client.transactions().listAll(ListTransactionsRequest.builder()
.subaccountId(subaccountId).order("desc").limit(50).build())) {
List<TransactionMessage> messages = new ArrayList<>();
// One call per message, one at a time, which stays well clear of rate limits.
List<Link> links = transaction.getLinks() == null ? null : transaction.getLinks().getMessages();
for (Link link : links == null ? List.<Link>of() : links) {
messages.add(client.transactionMessages().get(messageIdOf(link)));
}
// A message without createdDateTime goes last rather than failing the sort.
messages.sort(Comparator.comparing(TransactionMessage::getCreatedDateTime,
Comparator.nullsLast(Comparator.naturalOrder())));
each.accept(new TransactionWithMessages(transaction, messages));
seen++;
if (maxTransactions != null && seen >= maxTransactions) {
break; // stops reading pages
}
}
}Read a message's time
A message's dateTime is the network's own value. Mastercard sends the merchant's local time with no time zone, and clearings often carry 23:59:59 on their date. So read it with the SDK's date and time type, which says whether the value has an offset, and use the transaction's transactionOccurrenceDate for its date. That is the network's date of the transaction; for Mastercard it is often the settlement date, which can be a day before or after the purchase's local date (recipe 15).
for await (const { transaction, messages } of transactionsWithMessages(astrada, requireEnv('ASTRADA_SUBACCOUNT_ID'), max)) {
console.log(transaction.transactionOccurrenceDate, transaction.status, transaction.transactionHoldAmount,
transaction.transactionCurrency, transaction.descriptor);
for (const message of messages) {
const when = TransactionDateTime.parse(message.dateTime);
console.log(' ', message.messageType, message.result, message.transactionAmount,
when.hasOffset ? when.toDate()!.toISOString() : `${when.raw} (local time)`);
}
}for item in transactions_with_messages(client, require_env("ASTRADA_SUBACCOUNT_ID"), maximum):
t = item.transaction
print(t.transaction_occurrence_date, t.status, t.transaction_hold_amount,
t.transaction_currency, t.descriptor)
for message in item.messages:
when = message.date_time
shown = when.isoformat() if when.tzinfo else "%s (local time)" % when.isoformat()
print(" ", message.message_type, message.result, message.transaction_amount, shown)forEachTransaction(clientFromEnv(), UUID.fromString(requireEnv("ASTRADA_SUBACCOUNT_ID")), max, item -> {
Transaction t = item.transaction;
System.out.println(t.getTransactionOccurrenceDate() + " " + t.getStatusRawValue() + " "
+ t.getTransactionHoldAmount() + " " + t.getTransactionCurrency() + " " + t.getDescriptor());
for (TransactionMessage message : item.messages) {
TransactionDateTime when = message.getDateTime();
String shown = when.hasOffset() ? when.toInstant().map(Object::toString).orElse(when.getRaw())
: when.getRaw() + " (local time)";
System.out.println(" " + message.getMessageType() + " " + message.getResult() + " "
+ message.getTransactionAmount() + " " + shown);
}
});Whole example files: TypeScript, Python, Java.
What to expect
- Each transaction once, newest first, with its messages oldest first.
- A time with an offset prints as an exact moment; a time without one prints as it came, marked as local time.
- The demo stops after 20 transactions unless you set
MAX_TRANSACTIONS.
Read more
- Transaction: statuses, the amount fields, and how messages change a transaction.
- Transaction Message: message types and their fields.
- Read every page: how the SDKs walk list pages.
Updated 24 minutes ago
