Buying and acknowledging
A purchase on Android goes through these steps:
- Connect a
BillingClientto Google Play. - Load the products with
queryProductDetails: names, localized prices, and for subscriptions their base plans and offers. - Launch the purchase flow: Google Play shows its own payment sheet.
- Receive the result in a listener: the purchase, or an error, or a cancellation.
- Grant access, then acknowledge the purchase (or consume it, for items that can be bought again).
The step everyone forgets is acknowledging. If a purchase isn’t acknowledged within three days, Google Play refunds it automatically and removes it. That’s what happened to the finance team in the story above.
Two more cases to handle:
- Pending purchases: the user chose to pay with cash at a store or a bank transfer. The purchase exists but isn’t paid yet. Don’t grant access until it becomes
PURCHASED. - Restoring: on every app start (and when returning to the app), ask Google Play for the user’s current purchases with
queryPurchasesAsync. Purchases made on another device, renewals and refunds show up there.
BillingClient needs enablePendingPurchases(...) and reconnection handling (BillingClientStateListener, retry with backoff; the service can disconnect). queryProductDetails returns subscriptions with subscriptionOfferDetails (base plans and offers, each with an offerToken and pricing phases); pick offers the user is eligible for (Play only returns eligible ones for the signed-in account) and show formattedPrice from the right phase. launchBillingFlow needs ProductDetailsParams with the offerToken, and should carry setObfuscatedAccountId (your user id, hashed) so purchases can be tied to accounts. Results arrive in PurchasesUpdatedListener and later through queryPurchasesAsync (for purchases completed outside the flow: pending completions, other devices, promo codes). Only Purchase.PurchaseState.PURCHASED grants access; PENDING waits. Every purchase must be acknowledged (acknowledgePurchase, ideally by your server after verification) or consumed (consumeAsync for consumables) within 3 days, or it’s refunded and revoked. Treat the client as untrusted: send the purchase token to your server, verify with the Play Developer API, then grant and acknowledge.
class BillingRepository(
context: Context,
private val scope: CoroutineScope,
private val backend: EntitlementsApi, // our server: verifies tokens with Google
) : PurchasesUpdatedListener {
private val client = BillingClient.newBuilder(context)
.setListener(this)
.enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())
.build()
private val _hasPro = MutableStateFlow(false)
val hasPro: StateFlow<Boolean> = _hasPro
suspend fun connect() = suspendCancellableCoroutine { cont ->
client.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(result: BillingResult) {
if (cont.isActive) cont.resume(result.responseCode == BillingClient.BillingResponseCode.OK)
}
override fun onBillingServiceDisconnected() { /* reconnect with backoff on next use */ }
})
}
suspend fun proDetails(): ProductDetails? {
val params = QueryProductDetailsParams.newBuilder().setProductList(listOf(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("recipes_pro")
.setProductType(BillingClient.ProductType.SUBS)
.build()
)).build()
return client.queryProductDetails(params).productDetailsList?.firstOrNull()
}
fun buy(activity: Activity, details: ProductDetails, offerToken: String, accountId: String) {
val flow = BillingFlowParams.newBuilder()
.setProductDetailsParamsList(listOf(
BillingFlowParams.ProductDetailsParams.newBuilder()
.setProductDetails(details)
.setOfferToken(offerToken) // the base plan or offer the user picked
.build()
))
.setObfuscatedAccountId(accountId) // ties the purchase to our user
.build()
client.launchBillingFlow(activity, flow)
}
override fun onPurchasesUpdated(result: BillingResult, purchases: List<Purchase>?) {
if (result.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
scope.launch { purchases.forEach { handle(it) } }
}
}
/** Call on every app start and resume: renewals, other devices and completed pending purchases. */
suspend fun refresh() {
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
val purchases = client.queryPurchasesAsync(params).purchasesList
purchases.forEach { handle(it) }
_hasPro.value = purchases.any { it.purchaseState == Purchase.PurchaseState.PURCHASED }
}
private suspend fun handle(purchase: Purchase) {
if (purchase.purchaseState != Purchase.PurchaseState.PURCHASED) return // PENDING: wait
val verified = backend.verifyAndAcknowledge(purchase.purchaseToken) // server checks and acknowledges
if (verified) _hasPro.value = true
}
}enablePendingPurchasesis required: without it, users can’t pick payment methods like cash at a store.proDetailsloads the subscription from Google Play, with its base plans and offers and their localized prices.setOfferTokensays which plan or offer the user chose (monthly, yearly, the free trial).handleignoresPENDINGpurchases, sendsPURCHASEDones to our server, which checks them with Google and acknowledges them, and only then unlocks Pro.refreshruns on every start and resume, so renewals and purchases from another phone are picked up.
Predict the output
The app grants Pro as soon as onPurchasesUpdated reports a PURCHASED subscription, but never calls acknowledgePurchase (and neither does the server). What happens three days later?
Unacknowledged purchases are treated as not delivered: after three days Google refunds them and revokes the entitlement. Revenue disappears and users are confused. Acknowledge every verified purchase (from the server with the Play Developer API, or from the app with acknowledgePurchase), and monitor acknowledgment failures.
Tap the line with the bug.
override fun onPurchasesUpdated(result: BillingResult, purchases: List<Purchase>?) {
if (result.responseCode != BillingClient.BillingResponseCode.OK) return
purchases?.forEach { purchase ->
prefs.edit { putBoolean("isPro", true) }
client.acknowledgePurchase(
AcknowledgePurchaseParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build()
) { }
}
}Hint: What states can a Purchase be in, and who checked this one?
Three problems on one line and around it:
- Pending purchases also arrive here, with
purchaseState == PENDING; this code grants Pro before the user has paid (and may never pay). - Nothing verified the purchase: a modified app can call this listener with fake data.
isProin SharedPreferences never turns off: cancellations, refunds and expirations don’t reach it.
Grant access only for PURCHASED, after the server verified the token with Google, and compute access from current purchases (and the server’s entitlement), not from a flag saved once.
Show the plans
The Pro subscription has two base plans, monthly and yearly, and the yearly plan has a 7-day free trial offer. Using ProductDetails, how do you build the list of options to show, with correct prices?
›
Each entry in subscriptionOfferDetails is a base plan or an offer, with a list of pricing phases.
SolutionTry it yourself first
data class PlanOption(val title: String, val price: String, val offerToken: String, val trial: Boolean)
fun planOptions(details: ProductDetails): List<PlanOption> =
details.subscriptionOfferDetails.orEmpty().map { offer ->
val phases = offer.pricingPhases.pricingPhaseList
val recurring = phases.last() // the price after any trial or intro phase
PlanOption(
title = if (offer.basePlanId == "yearly") "Yearly" else "Monthly",
price = recurring.formattedPrice, // localized by Google Play
offerToken = offer.offerToken,
trial = phases.any { it.priceAmountMicros == 0L }, // a free phase means a trial
)
}Google Play only returns offers the signed-in user is eligible for, so someone who already had a trial won’t see the trial offer. Always show formattedPrice, never your own currency formatting.
Upgrades, downgrades and replacement modes
Changing plans is a new purchase that replaces the old one: pass SubscriptionUpdateParams with the old purchase token and a replacement mode: CHARGE_PRORATED_PRICE or WITH_TIME_PRORATION for upgrades (immediate, with proration), DEFERRED for downgrades (takes effect at renewal), CHARGE_FULL_PRICE to start a new billing date now. The new purchase has a new token and linkedPurchaseToken pointing to the old one: your server must move the entitlement and stop treating the old token as active, or one user ends up with two subscriptions in your database.
BillingClientwithenablePendingPurchases, reconnect with backoff.queryProductDetails→subscriptionOfferDetails(base plans, offers,offerToken, pricing phases; only eligible offers returned).launchBillingFlowwithofferTokenandsetObfuscatedAccountId. Results viaPurchasesUpdatedListenerandqueryPurchasesAsyncon start/resume.- Only
PURCHASEDgrants;PENDINGwaits. Acknowledge (or consume) within 3 days or auto-refund and revocation. - Server verifies tokens before granting and acknowledging. Plan changes: replacement modes and
linkedPurchaseToken.
Check this part
What happens to a purchase that isn't acknowledged within three days?
A purchase arrives with state PENDING. Should the app grant Pro?
Why call queryPurchasesAsync on every start and resume?
What does linkedPurchaseToken on a new subscription purchase mean?