One Subaccount per Customer
Find your customer's subaccount, or make it on first use, with code you can call again and again for the same customer without making a second subaccount.
For: developers
Cards, transactions and webhooks belong to a subaccount, so one subaccount per customer of yours keeps each customer's data apart. This recipe finds the customer's subaccount, or makes it the first time, and can be called again and again with the same customer: it never makes a second one.
Before you start
- Scopes:
subaccounts:readandsubaccounts:write, pluswebhooks:readandwebhooks:writefor the webhook step (recipe 2). - A table in your database from your own customer reference to the subaccount id.
- Sandbox or production.
The code
How it stays at one subaccount per customer:
- Your table is checked first.
- The subaccount's name is your customer reference. If a run made the subaccount but stopped before saving it in your table, the next run finds it by name instead of making another. The subaccount list has no name filter, so that search reads the list page by page: it runs only when your table has no entry.
- Your table is written last, after the
preparestep where you register the webhook (pass a function that calls recipe 2'sensureWebhookfor the subaccount id), so a subaccount in your table always has its webhook. - Two calls for the same new customer at the same moment could each make one. Hold a lock on the customer in your database around the call, such as a row lock or a unique pending row.
The create asks for every country your account is set up for on each network ("countries": "*"). Leave out a network your account does not have: a create that names one is refused with 400.
/** Your table of customer reference to subaccount id. */
export interface CustomerDirectory {
subaccountFor(customerReference: string): Promise<string | undefined>;
saveSubaccount(customerReference: string, subaccountId: string): Promise<void>;
}class CustomerDirectory(Protocol):
"""Your table of customer reference to subaccount id."""
def subaccount_for(self, customer_reference: str) -> Optional[str]: ...
def save_subaccount(self, customer_reference: str, subaccount_id: str) -> None: .../** Your table of customer reference to subaccount id. */
public interface CustomerDirectory {
UUID subaccountFor(String customerReference);
void saveSubaccount(String customerReference, UUID subaccountId);
}The function that finds or makes the customer's subaccount:
/** Returns the customer's subaccount id, making the subaccount the first time. */
export async function subaccountForCustomer(
astrada: Astrada,
directory: CustomerDirectory,
customerReference: string,
prepare: (subaccountId: string) => Promise<void> = async () => {},
): Promise<string> {
const saved = await directory.subaccountFor(customerReference);
if (saved !== undefined) return saved;
// Not in your database: an earlier run may have made it and stopped before saving.
let subaccount: Subaccount | undefined;
for await (const candidate of astrada.subaccounts.listAll({ limit: 50 })) {
if (candidate.name === customerReference) {
subaccount = candidate;
break; // stops reading pages
}
}
if (subaccount === undefined) {
// The SDK retries this create under one Idempotency-Key, so a lost answer does not make two.
subaccount = await astrada.subaccounts.create({
name: customerReference,
// "*" takes every country your account is set up for on that network. List only the
// networks your account has: add `AMEX: { countries: '*' }` if Amex is set up for it.
configurations: {
VISA: { countries: '*' },
MASTERCARD: { countries: '*' },
},
});
}
await prepare(subaccount.id);
await directory.saveSubaccount(customerReference, subaccount.id);
return subaccount.id;
}def subaccount_for_customer(
client: astrada.Astrada,
directory: CustomerDirectory,
customer_reference: str,
prepare: Callable[[str], None] = lambda subaccount_id: None,
) -> str:
"""Returns the customer's subaccount id, making the subaccount the first time."""
saved = directory.subaccount_for(customer_reference)
if saved is not None:
return saved
# Not in your database: an earlier run may have made it and stopped before saving.
subaccount: Optional[astrada.Subaccount] = None
for candidate in client.subaccounts.list_all(limit=50):
if candidate.name == customer_reference:
subaccount = candidate
break # stops reading pages
if subaccount is None:
# The SDK retries this create under one Idempotency-Key, so a lost answer does not make two.
subaccount = client.subaccounts.create({
"name": customer_reference,
# "*" takes every country your account is set up for on that network. List only the
# networks your account has: add "AMEX": {"countries": "*"} if Amex is set up for it.
"configurations": {
"VISA": {"countries": "*"},
"MASTERCARD": {"countries": "*"},
},
})
prepare(str(subaccount.id))
directory.save_subaccount(customer_reference, str(subaccount.id))
return str(subaccount.id)/** Returns the customer's subaccount id, making the subaccount the first time. */
public static UUID subaccountForCustomer(ApiClient client, CustomerDirectory directory, String customerReference,
Consumer<UUID> prepare) {
UUID saved = directory.subaccountFor(customerReference);
if (saved != null) {
return saved;
}
// Not in your database: an earlier run may have made it and stopped before saving.
Subaccount subaccount = null;
for (Subaccount candidate : client.subaccounts().listAll(ListSubaccountsRequest.builder().limit(50).build())) {
if (customerReference.equals(candidate.getName())) {
subaccount = candidate;
break; // stops reading pages
}
}
if (subaccount == null) {
// The SDK retries this create under one Idempotency-Key, so a lost answer does not make two.
subaccount = client.subaccounts().create(new SubaccountCreateParams()
.name(customerReference)
// "*" takes every country your account is set up for on that network. List only
// the networks your account has: add
// .AMEX(new CreateSubaccountConfigurationsAMEX().countries("*")) if Amex is set up for it.
.configurations(new CreateSubaccountConfigurations()
.VISA(new CreateSubaccountConfigurationsVISA().countries("*"))
.MASTERCARD(new CreateSubaccountConfigurationsMASTERCARD().countries("*"))));
}
prepare.accept(subaccount.getId());
directory.saveSubaccount(customerReference, subaccount.getId());
return subaccount.getId();
}Whole example files: TypeScript, Python, Java.
What to expect
The first call for a customer creates the subaccount and returns its id; later calls return the same id. The SDK retries the create under one Idempotency-Key, so an answer lost on the way back does not make a second subaccount.
Check who owns a subaccount before you act for a userAstrada checks access per account, not per subaccount: your API client can read every subaccount of your account. Before you act for a signed-in user, check in your own database that the subaccount is theirs. Recipe 4 does this before it hands out a token.
Read more
- Accounts and Subaccounts: what a subaccount holds.
- Account & Subaccount Configuration: how account and subaccount settings combine.
- Create a subaccount and Read every page in the SDK guide.
Updated 24 minutes ago
