Skip to content
Commitwise
Menu
Android Development

Google Play Billing and subscriptions

Sell subscriptions and one-time products with the Play Billing Library, from loading product details and offers to launching the purchase flow, handling pending purchases, acknowledging within three days, restoring on startup, and verifying purchases on your server with Real-time Developer Notifications and the subscription lifecycle (grace period, account hold, pause, cancellation, revocation).

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The recipe app launches Pro on Android. A week later, finance notices that a third of the first purchases were automatically refunded by Google. Support hears from users whose payment “is pending” at a convenience store, and from users who were charged but don’t have Pro on their second phone. A forum thread shares a purchase token that unlocks Pro for anyone who pastes it into a modified app.

Google Play Billing is the required way to sell digital goods in apps distributed on Google Play (with regional exceptions). The library’s API is small. Like StoreKit on iOS, what makes or breaks it is the model around it: acknowledging purchases, handling pending ones, computing access from current purchases, and letting your server verify everything and follow the subscription lifecycle.

New to some of these? Open what you need, or skip ahead.

Basics:Products, base plans and offers

In Play Console you create products: one-time products (an in-app item, consumable or not) and subscriptions. A subscription has one or more base plans (monthly, yearly) and optional offers on top (a free trial, an introductory price). The app loads them with their localized prices from Google Play, never hard-coding “€4.99”.

Basics:What is a purchase token?

When a purchase completes, Google Play gives the app a purchase token, a long string identifying that purchase. Your server can send the token to Google’s API to check that the purchase is real and still active. The token, not anything the app says, is the proof of purchase.

Part Not started

Buying and acknowledging

A purchase on Android goes through these steps:

  1. Connect a BillingClient to Google Play.
  2. Load the products with queryProductDetails: names, localized prices, and for subscriptions their base plans and offers.
  3. Launch the purchase flow: Google Play shows its own payment sheet.
  4. Receive the result in a listener: the purchase, or an error, or a cancellation.
  5. 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
    }
}
  • enablePendingPurchases is required: without it, users can’t pick payment methods like cash at a store.
  • proDetails loads the subscription from Google Play, with its base plans and offers and their localized prices.
  • setOfferToken says which plan or offer the user chose (monthly, yearly, the free trial).
  • handle ignores PENDING purchases, sends PURCHASED ones to our server, which checks them with Google and acknowledges them, and only then unlocks Pro.
  • refresh runs 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?

Spot the bugPro before the money arrives

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()
        ) { }
    }
}

Exercisemedium

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.

  • BillingClient with enablePendingPurchases, reconnect with backoff. queryProductDetails → subscriptionOfferDetails (base plans, offers, offerToken, pricing phases; only eligible offers returned).
  • launchBillingFlow with offerToken and setObfuscatedAccountId. Results via PurchasesUpdatedListener and queryPurchasesAsync on start/resume.
  • Only PURCHASED grants; PENDING waits. 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

  1. What happens to a purchase that isn't acknowledged within three days?

  2. A purchase arrives with state PENDING. Should the app grant Pro?

  3. Why call queryPurchasesAsync on every start and resume?

  4. What does linkedPurchaseToken on a new subscription purchase mean?

Connect a BillingClient (with pending purchases enabled), load ProductDetails with their offers, launch the billing flow, and handle results in the PurchasesUpdatedListener. Only PURCHASED purchases grant access; PENDING ones wait. Every purchase must be acknowledged (or consumed) within three days, or Google refunds it automatically. Query existing purchases on every app start and resume to restore access.

Part Not started

The server and the subscription lifecycle

A subscription keeps changing after the purchase, usually while the app isn’t running:

  • It renews every period, or the card fails. Then Google retries: during a grace period the user keeps access; after it, the subscription goes on hold and access stops until the user fixes the payment.
  • The user can pause it for a while (if you allow it), or cancel it: access continues until the end of the period they paid for.
  • Google can revoke it after a refund.

Your server learns about all of this from Real-time Developer Notifications (RTDN)Real-time Developer NotificationsMessages Google Play sends to your server through Cloud Pub/Sub when a subscription or purchase changes.Open in glossary →: Google sends a message to your server through Google Cloud Pub/Sub every time a subscription changes. The message only says “something changed for this purchase token”; the server then asks Google’s API for the current state and updates the user’s access.

The server also protects against fraud: the app sends it the purchase token, and the server checks with Google that it’s real, and that it isn’t already used by another account.

The backend owns entitlements. Verification: the client posts the purchase token; the server calls purchases.subscriptionsv2.get (Play Developer API, service account), checks package and product, subscriptionState, line items and expiry, the externalAccountIdentifiers.obfuscatedExternalAccountId against the requesting user, and refuses a token already bound to a different account (shared or replayed tokens); then acknowledges via the API. RTDN: Play publishes notifications to a Cloud Pub/Sub topic (push to your endpoint or pull); payloads carry notificationType (PURCHASED, RENEWED, IN_GRACE_PERIOD, ON_HOLD, RECOVERED, PAUSED, CANCELED, EXPIRED, REVOKED, …) and the token; always re-fetch the full state rather than trusting the type, process idempotently, and handle out-of-order delivery. States to access: ACTIVE and IN_GRACE_PERIOD → access (with a fix-payment prompt in grace); ON_HOLD and PAUSED → no access; CANCELED → access until expiry; EXPIRED/REVOKED → none. One-time purchase refunds and chargebacks come through the Voided Purchases API, which should be polled to revoke consumables or items. In the app, deep-link users to Play’s subscription center to fix payment or cancel.

// Server (Spring): the app posts the purchase token after a PURCHASED result
@PostMapping("/billing/google/verify")
fun verify(@AuthenticationPrincipal user: User, @RequestBody body: VerifyRequest): EntitlementResponse {
    val sub = play.purchases().subscriptionsv2().get(PACKAGE_NAME, body.purchaseToken).execute()

    val accountId = sub.externalAccountIdentifiers?.obfuscatedExternalAccountId
    require(accountId == user.obfuscatedId) { "Purchase belongs to a different account" }
    tokens.bindOrFail(body.purchaseToken, user.id)              // unique constraint: one token, one user

    entitlements.applyFrom(user.id, sub)                        // ACTIVE / IN_GRACE_PERIOD → access until expiry
    if (sub.acknowledgementState == "ACKNOWLEDGEMENT_STATE_PENDING") {
        play.purchases().subscriptions()
            .acknowledge(PACKAGE_NAME, sub.lineItems.first().productId, body.purchaseToken, SubscriptionPurchasesAcknowledgeRequest())
            .execute()
    }
    return entitlements.current(user.id).toResponse()
}

// Real-time Developer Notifications via Cloud Pub/Sub push
@PostMapping("/billing/google/rtdn")
fun rtdn(@RequestBody message: PubSubPush): ResponseEntity<Unit> {
    val notification = decode(message)                          // base64 JSON with subscriptionNotification
    val token = notification.subscriptionNotification?.purchaseToken ?: return ResponseEntity.ok().build()
    if (!processed.markIfNew(message.message.messageId)) return ResponseEntity.ok().build()   // duplicates

    val sub = play.purchases().subscriptionsv2().get(PACKAGE_NAME, token).execute()          // always re-fetch state
    tokens.userFor(token)?.let { userId -> entitlements.applyFrom(userId, sub) }
    return ResponseEntity.ok().build()
}
  • subscriptionsv2().get asks Google for the real state of the purchase. The app’s word isn’t enough.
  • obfuscatedExternalAccountId is the id the app passed when buying. If it doesn’t match the user sending the token, someone is reusing another person’s purchase.
  • bindOrFail stores which user owns the token; a second account trying the same token is refused.
  • The RTDN handler doesn’t trust the notification’s type alone: it fetches the current state from Google and updates access.

Predict the output

A user's card fails at renewal. The app has a 7-day grace period configured. On day 3, what does the server's entitlement say, and what should the app show?

Production puzzles

Predict the output

The server verifies tokens with Google but doesn't check which account they belong to. A user posts their valid purchase token on a forum. What happens?

Exercisehard

One entitlement across stores

Recipes Pro is sold through Google Play, the App Store and the web. A user subscribes on Android, then signs in on iOS and the web. Design how each client learns the user has Pro, and what happens if the same user later subscribes again on iOS.

›

Separate the per-store subscription records from the single entitlement the features check.

SolutionTry it yourself first
  • Records per store: subscriptions(store, store_ref, user_id, state, expires_at, in_grace); Google rows keyed by purchase token (and linked tokens for replacements), Apple rows by original transaction id, web rows by the provider’s subscription id.
  • One entitlement: Pro if any record is active or in grace. Every client asks the server, which returns the entitlement (optionally a signed token for offline use).
  • Updates: Google RTDN, App Store Server Notifications and web webhooks all re-fetch state from the store and recompute the entitlement, idempotently; nightly reconciliation catches missed notifications.
  • Double subscription: before showing an iOS paywall, the app checks the entitlement and says “You already have Pro through Google Play”, with a link to manage it there. If the user buys anyway, both records are kept; support can help cancel one, since each store manages its own billing.
  • Account linking: each store’s purchase carries your account id (obfuscatedAccountId, appAccountToken, checkout metadata), so purchases never get attached to the wrong user.
Exerciseeasy

Map states to access

For each subscription state, say whether the user has Pro and what the app should show: ACTIVE, IN_GRACE_PERIOD, ON_HOLD, PAUSED, CANCELED (period not over), EXPIRED.

›

Canceling stops the next renewal; it doesn’t end the current period.

SolutionTry it yourself first
StatePro?Show
ACTIVEYesNothing special
IN_GRACE_PERIODYes“Payment problem: update your payment method” with a link to Play
ON_HOLDNo“Pro is on hold until your payment is fixed” with the same link
PAUSEDNo“Pro is paused until (date)”, with an option to resume
CANCELED (not expired)Yes“Pro ends on (date)” and maybe a reason to stay
EXPIREDNoThe normal free experience and the paywall
  • Server verifies tokens with purchases.subscriptionsv2.get; checks package, product, state, expiry and obfuscatedExternalAccountId; binds token → user (unique); acknowledges.
  • RTDN via Cloud Pub/Sub: dedupe, re-fetch state, apply idempotently; out-of-order safe.
  • Access: ACTIVE, IN_GRACE_PERIOD (prompt), CANCELED until expiry → yes; ON_HOLD, PAUSED, EXPIRED, REVOKED → no.
  • Voided Purchases API for one-time refunds and chargebacks; deep link to Play’s subscription center.
  • Cross-store: per-store records, one server entitlement, reconciliation.

Check this part

  1. How does the server learn about renewals and cancellations?

  2. A user cancels today. When do they lose Pro?

  3. Why bind each purchase token to one account on the server?

  4. What should an RTDN handler do with the notification type?

The server is the source of truth: it verifies purchase tokens with the Play Developer API (purchases.subscriptionsv2), links them to accounts (obfuscatedAccountId) and refuses tokens already bound to another user, acknowledges them, and follows the lifecycle through Real-time Developer Notifications delivered via Cloud Pub/Sub. States include active, in grace period, on hold, paused, canceled (access until expiry), expired and revoked; voided purchases are reported separately.

Key takeaways

  • Load products and offers from Google Play; show their localized prices.
  • Grant access only for PURCHASED, verified purchases; wait on PENDING.
  • Acknowledge every purchase within three days, or it’s refunded.
  • Check current purchases on every start; the server follows the lifecycle through RTDN.
  • Server-side verification, acknowledgment and account binding for every token.
  • Re-fetch state on every notification; process idempotently; map states to access deliberately.
  • Handle replacements (linkedPurchaseToken) and voided purchases.
  • Keep one entitlement across stores, with reconciliation.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.