PURCHASE
Purchase flow - Android
Purchasing flow is a multistage process, which involves payment collection, purchase validation and consumption. Purchases a player already made are recovered separately, through restoration.
Launch a billing flow
You have multiple options on how to start a purchasing flow depending on your needs and goals.
- Standard
- Payment Token
- Buy Button
To start a purchasing flow, pass one of the ProductDetails acquired earlier with a BillingFlowParams into launchBillingFlow method:
// Parent activity to open the Xsolla Pay Station with.
final Activity activity = // ...
mBillingClient.launchBillingFlow(activity, BillingFlowParams
.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams
.newBuilder()
.setProductDetails(productDetails)
.build()
))
.build()
);
Advanced Settings
BillingFlowParams.Builder supports multiple other properties that can be specified prior to launching a billing flow using BillingClient.launchBillingFlow():
| Setting | Value | Description |
|---|---|---|
| setObfuscatedAccountId | string | Sets an obfuscated account ID that can be used upon purchasing flow completion (callback or webhook). |
| setObfuscatedProfileId | string | Sets an obfuscated account ID that can be used upon purchasing flow completion (callback or webhook). |
| setDeveloperPayload | string | Allows passing developer's arbitrary meta-data with the purchasing flow, which can be used upon purchasing flow completion (callback or webhook). |
| setExternalTransactionId | string | Allows setting a custom unique transaction ID that should be associated with the launched purchasing flow (make sure to enable external transaction IDs in your Publisher Account as well or the purchasing flow will fail). |
| setExternalTransactionToken | string | Attaches a Google Play external transaction token (from enableUserChoiceBilling, createBillingProgramReportingDetailsAsync, or createAlternativeBillingOnlyReportingDetailsAsync) to the launched purchasing flow, so it carries through to your order. See Reporting External Transactions to Google Play. |
| setTrackingId | string | A tracking ID intended for Xsolla's internal analytics (consult with your integration manager beforehand). |
| setForcePaymentMethodId | int | Forces a specific payment method to be selected for the launched purchasing flow (IDs can be found in your Publisher Account). |
| setCanceller | BillingFlowCanceller | Attaches a canceller that lets you programmatically cancel the billing flow after it has been launched. |
Cancelling a billing flow
Create a BillingFlowCanceller, pass it to the params builder, and call cancel() when needed (for example, on a timeout or user action). The SDK will stop any in-progress retries and return a USER_CANCELED result.
final BillingFlowCanceller canceller = new BillingFlowCanceller();
mBillingClient.launchBillingFlow(activity, BillingFlowParams
.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams
.newBuilder()
.setProductDetails(productDetails)
.build()
))
.setCanceller(canceller)
.build()
);
// Cancel the flow at any point from any thread
canceller.cancel();
This approach allows to initiate the billing flow using an externally generated Xsolla Pay Station payment token.
// Parent activity to open the Xsolla Pay Station with.
final Activity activity = // ...
final String paymentToken = "<your-externally-generated-payment-token>";
final String developerPayload = null;
mBillingClient.launchBillingFlow(
activity, paymentToken, developerPayload
);
Advanced Settings
For more control over the token-based billing flow, use the BillingFlowTokenParams builder instead:
final BillingFlowCanceller canceller = new BillingFlowCanceller();
mBillingClient.launchBillingFlow(activity, BillingFlowTokenParams
.newBuilder()
.setPaymentToken("<your-externally-generated-payment-token>")
.setDeveloperPayload(null)
.setCanceller(canceller)
.build()
);
// Cancel the flow at any point from any thread
canceller.cancel();
| Setting | Value | Description |
|---|---|---|
| setPaymentToken | string | The externally generated Xsolla Pay Station payment token. |
| setDeveloperPayload | string | Allows passing developer's arbitrary meta-data with the purchasing flow, which can be used upon purchasing flow completion (callback or webhook). |
| setCanceller | BillingFlowCanceller | Attaches a canceller that lets you programmatically cancel the billing flow after it has been launched. |
Two ways to integrate Buy Button: redirect users to your Web Shop, or use the native in-app Buy Button Solution.
Following the Epic v. Google ruling effective October 29, 2025, U.S. Google Play apps can use the Xsolla SDK purchasing flow directly, but must first detect the storefront country code using the guide provided here.
Validate the purchase (recommended)
For instructions on how to validate your purchases, see Purchase validation.
Although validation is NOT a mandatory step, it's highly recommended to minimize the chance of fraud and any other malevolent intents.
Consume purchased goods
The final step in the purchasing flow is to award the purchased goods to the user and mark them as processed. This is known as purchase consumption. Once consumed, the item is no longer listed as a pending purchase and — depending on your product configuration — the user may purchase it again.
How consumption is handled depends on whether your integration processes purchases on the client or on your backend via webhooks.
Client-based (no webhooks)
In a client-based integration, the game client is responsible for awarding goods to the user and notifying Xsolla that the purchase has been processed. This is done inside the PurchasesUpdatedListener.onPurchasesUpdated() callback after a successful purchase (and, ideally, after validation):
final Purchase purchase = // ...
final ConsumeParams consumeParams = ConsumeParams
.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
// Notify Xsolla that the purchase has been processed and mark it as consumed.
mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
@Override
public void onConsumeResponse(
@NonNull final BillingResult billingResult, final String purchaseToken
) {
if (billingResult.isSuccess()) {
// Consumption succeeded — award the purchased goods to the user here.
} else {
// Consumption failed — do not grant entitlement.
}
}
});
It's highly recommended to perform at least some form of validation before consuming the purchased goods.
Server-based (webhooks)
In a server-based integration, your backend handles the full purchase lifecycle — validation, awarding, and consumption — triggered by a webhook from Xsolla. The PurchasesUpdatedListener.onPurchasesUpdated() callback is still invoked on the client when a purchase completes, but it carries no authority in this flow and should not be used to drive any purchase logic.
The simplest approach is to ignore the callback entirely and let your backend confirm the outcome.
A more complete approach is to use it purely for UI purposes — for example, showing a pending state for the purchased product and clearing it once your server confirms the result:
final PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(
@NonNull final BillingResult billingResult, @Nullable final List<Purchase> purchases
) {
if (billingResult.isSuccess() && purchases != null) {
// The purchase was initiated successfully.
// Your backend will handle validation, consumption, and entitlement via webhook.
// Optionally, show a pending/processing state in the UI here and
// update it once your server relays the confirmed result back to the client.
} else {
// The purchase did not complete (e.g. user cancelled or a connection error occurred).
// No action required — your backend will not receive a webhook for this purchase.
}
}
};
For details on how the webhook-based flow works end-to-end, including consumption handled on the backend, see Purchase validation — Server-side.
Restore existing purchases
Restoration hands you purchases a player already made — after a reinstall, on a new device, or when the client never confirmed the original transaction. BillingClient.queryPurchases() is a manual call; the SDK never invokes it for you.
Restored purchases come from one of two backends — Inventory API, the default, or Events API. See Purchase Restoration Settings for how a project selects one, and Inventory API vs. Events API for what each does under the hood.
Restoration is most useful for confirming ownership of non-consumable products whose SKUs the app knows upfront. Where your own server is the authority on purchase state, it is generally not needed for consumables.
What a restored purchase contains
| Accessor | Inventory API | Events API |
|---|---|---|
getOrigin() | INVENTORY_RESTORE | EVENTS_RESTORE |
isRestored() | true | true |
getPurchaseTime() | Always 0 | Time of the original payment |
getOrderId() — the invoice ID | Synthesized locally, stable across queries | Real invoice ID from the original order |
getOriginalOrderId() — the order (cart) ID | The same synthesized value as getOrderId() | Real order ID from the original order |
getQuantity() | 1 by default — a holding is split into one Purchase per unit; the full quantity when collapsed | Quantity from the original order |
isFree() | Always false — the inventory doesn't distinguish paid items from free ones | true if the order carried no invoice |
Despite the names, getOrderId() returns the Xsolla invoice ID and getOriginalOrderId() returns the Xsolla order (cart) ID — the Purchase class mirrors Google Play Billing Library's naming, where getOrderId() is the post-payment identifier. If you're matching a purchase against your own order records, that's getOriginalOrderId().
getPurchaseState() always reports PURCHASED and isAcknowledged() is always false — acknowledgement isn't supported by either backend, so there's no acknowledge step to implement. Neither field indicates a restore; use getOrigin() or isRestored() for that.
Under Inventory API, getOrderId() and getOriginalOrderId() are not real order identifiers — never send them to your backend as one.
They're derived locally from the SKU and the unit's position in the holding, and the same made-up value is written into both fields, which is why they're equal in this mode. No Xsolla system — Publisher Account, order lookup, webhook payload, anything — will recognize them. Treating one as a real order reference — to match an order, check for fraud, look up a refund, or help a player through support — will silently match nothing.
The values are stable across repeated queryPurchasesAsync() calls for the same held units, and consuming part of a holding leaves the remaining units' values unchanged — as of Android SDK 3.0.55 ↗. Before that release, they were drawn at random on every query.
This is the mode a project restores from by default — see Selecting a mode.
iOS behaves differently here — the equivalent identifiers are left empty rather than synthesized, since the iOS SDK models StoreKit (where the identifier is optional) while Android models Play Billing Library (where it's populated once a purchase reaches PURCHASED). Neither platform is going to converge on the other's behavior.
What restores, by product type
Inventory API restoration reads the player's item inventory, which only ever reports virtual goods and virtual currency. A product type with no inventory representation comes back empty:
ProductType | Restored under Inventory API |
|---|---|
INAPP | ✔ Virtual goods the player holds — except time-limited items, which are filtered out |
VIRTUAL_CURRENCY | ✔ One Purchase per currency, from a balance endpoint |
BUNDLE | ✘ Nothing — including virtual currency packages, which the catalog classifies as bundles |
SUBS, PLAY_PASS_SUBS | ✘ Nothing — unsupported product types |
A BUNDLE query restores nothing under Inventory API, and virtual currency packages are bundles — the catalog classifies them as such, not as currency.
The currency a package granted is still recoverable: it lands in the player's balance, so a VIRTUAL_CURRENCY query returns it. What can't be recovered is the package purchase itself. Under Events API it can be — but it arrives as the bundle's content items, never as the bundle SKU, so match against the contents rather than the SKU the player paid for.
A VIRTUAL_CURRENCY query returns getQuantity() set to the player's cumulative balance rather than a list of transactions. Because a balance is a single figure, it always collapses into one Purchase per currency regardless of withCollapseRestoredMultiUnitPurchases. Zero and negative balances are omitted, and a balance above Integer.MAX_VALUE is clamped to it.
Product type is an Inventory API filter only. Under Events API a restore query returns every unconsumed event whatever type you pass, so expect virtual currency and bundle contents alongside in-app products.
Consuming a restored purchase
A restored purchase is consumed exactly like a fresh one — take its getPurchaseToken() and pass it to consumeAsync(), as in Consume purchased goods. The token identifies the purchase in both modes; there's nothing mode-specific to handle.
A bundle's content items are consumed individually. The SDK tracks partial consumption locally and settles the underlying order once every item has been consumed.
Practices worth adopting
How many of these you need depends on how much of the purchase lifecycle you own:
| Practice | If ignored | When you need it |
|---|---|---|
| Check your own records before you grant. Restoration hands you purchases the player may already have been given, so a purchase you've handled must not be granted again. | Critical — players awarded the same purchase twice | Always, including client-only integrations |
Treat getPurchaseTime() == 0 as unknown, not as an instant. Every Inventory API restore reports 0, so sorting a mixed list by time buckets them all at the epoch. | Low — purchase history sorts wrongly | If you sort or display purchase history |
Check getOrigin() rather than guessing from a field's value. isRestored() tells you the purchase is an old one coming back; getOrigin() also tells you which backend it came from, and the two give you different things. | Medium — old purchases trigger first-purchase UI and rewards | If restored purchases take a different path from fresh ones, such as suppressing a "purchase complete" popup |
| Only match purchases by order ID where the ID means something. Events API IDs are real and stable, so they work anywhere. Inventory API IDs are stable but local to the device, so they match nothing on your server or on another device. | High — the check on your server silently stops working | If your server checks for purchases it has already handled, or you check across devices |
| Compare against your own record of what you've granted before switching backends. Once Events API is enabled for the project, events are recorded whether or not the SDK reads them — so switching to it hands you a history the client has never seen. | Critical — that backlog arrives at once, granting purchases twice or dropping them | Only when migrating a live project — see Migrating a live project |