Skip to main content

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.

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():

SettingValueDescription
setObfuscatedAccountIdstringSets an obfuscated account ID that can be used upon purchasing flow completion (callback or webhook).
setObfuscatedProfileIdstringSets an obfuscated account ID that can be used upon purchasing flow completion (callback or webhook).
setDeveloperPayloadstringAllows passing developer's arbitrary meta-data with the purchasing flow, which can be used upon purchasing flow completion (callback or webhook).
setExternalTransactionIdstringAllows 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).
setExternalTransactionTokenstringAttaches 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.
setTrackingIdstringA tracking ID intended for Xsolla's internal analytics (consult with your integration manager beforehand).
setForcePaymentMethodIdintForces a specific payment method to be selected for the launched purchasing flow (IDs can be found in your Publisher Account).
setCancellerBillingFlowCancellerAttaches 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();
important

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.

For instructions on how to validate your purchases, see Purchase validation.

warning

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.
}
}
});
important

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.
}
}
};
info

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​

AccessorInventory APIEvents API
getOrigin()INVENTORY_RESTOREEVENTS_RESTORE
isRestored()truetrue
getPurchaseTime()Always 0Time of the original payment
getOrderId() — the invoice IDSynthesized locally, stable across queriesReal invoice ID from the original order
getOriginalOrderId() — the order (cart) IDThe 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 collapsedQuantity from the original order
isFree()Always false — the inventory doesn't distinguish paid items from free onestrue 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.

warning

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:

ProductTypeRestored 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
warning

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:

PracticeIf ignoredWhen 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 twiceAlways, 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 wronglyIf 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 rewardsIf 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 workingIf 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 themOnly when migrating a live project — see Migrating a live project