Skip to content
Mai Trinh
  • Android App
  • 12 min read

When Google Play refunds your customers on its own: lessons from a forgotten consume

Customers paid, got their content, and three days later Google refunded them without anyone asking. No crash, no error on screen. The cause was four small decisions around the consume step, each one reasonable on its own.

Mai Trinh

Software Engineer

On this page

Part 1 of a series on Google Play Billing on Android. The case: users paid, received their content, and three days later Google refunded them automatically, though nobody had asked for a refund.

At a glance

  • Problem: a group of orders was refunded by Google exactly 3 days after purchase, even though the backend had recorded them and users had their content. Nothing crashed, nothing showed an error; it only surfaced during revenue reconciliation.
  • Cause: consume was called fire-and-forget, the token was deleted before Google confirmed, and the recovery flow skipped orders that were already "verified". The orders were never acknowledged, so Google refunded them.
  • Fix: a new VERIFIED_PENDING_CONSUME state, pending orders stored per purchaseToken, a consume that reports its result, and a reconciler that runs every time billing connects. An order now leaves the app only once Google confirms the consume.

Symptoms

One day, support received an unusual email from a customer:

"I bought a content pack and I'm enjoying it, but Google Play just refunded me and I never asked for it. What should I do?"

Digging further, the team found a group of orders with the same pattern:

  • Bought on day N, refunded by Google on day N + 3.
  • No refund request from the user.
  • The backend had recorded the transaction and the user had been granted access to the content; some had already used up the credits they bought.
  • It happened to both product types: single purchases and credit packs.

In short, the business delivered the goods but Google gave the money back to the customer. The bug didn't crash anything, showed no error, and only came to light when someone reconciled revenue.

Background: where do the "3 days" come from?

Google Play Billing has a rule that is easy to miss:

Every purchase must be acknowledged within 3 days. Otherwise Google automatically refunds it and revokes the purchase.
  • Non-consumable / subscription

    How to acknowledge
    acknowledgePurchase()
  • Consumable (can be bought repeatedly)

    How to acknowledge
    consumeAsync(): acknowledges and also "releases" the SKU so it can be bought again

The app in this case sells consumables: each price point is a fixed SKU, and a user can buy it many times. So consume plays two roles:

  1. It tells Google "delivered, don't refund".
  2. It releases the SKU. Until it is consumed, the next purchase at the same price gets ITEM_ALREADY_OWNED.

The correct flow for a purchase:

Google Play charge ──► app receives Purchase ──► send receipt to backend to verify
                                                   │
                                          backend OK, grant access
                                                   │
                                          consume() ──► Google confirms
                                                   │
                                          delete pending data

consume is the last step and the easiest one to underrate, because by then the user already sees the content unlocked and everything looks done.

Root cause: four small mistakes stacked together

No single line was obviously wrong. The bug came from four small decisions, each reasonable on its own, that together lost orders. Function and class names below differ from the real project, but the logic is unchanged.

3.1 Fire-and-forget consume

// BEFORE
public void consumeItem(String token) {
    if (!isReady()) return;                       // (a) client not ready → silently exit

    ConsumeParams params = ConsumeParams.newBuilder()
            .setPurchaseToken(token).build();
    billingClient.consumeAsync(params, (billingResult, outToken) -> {});  // (b) result ignored
}
  • (a): BillingClient is often just disconnected right after the user closes the Google Play bottom sheet. That is exactly when consume is usually called, so it was skipped a lot.
  • (b): even when the call went through, its result was ignored. If the consume failed, nobody knew.

3.2 Deleting the token before the consume was confirmed

// BEFORE — after the backend verifies successfully
localDb.markVerified(productId, orderId, token);   // 1. record "verified"
billingManager.consumeItem(token);                 // 2. fire-and-forget
PendingReceiptPrefs.clear();                       // 3. delete the token from the cache

After step 3, the app no longer has the token anywhere. If step 2 failed, the purchase only exists on Google Play, as "paid but not acknowledged".

3.3 Recovery skipped exactly the orders that needed it

The app had a recovery mechanism: on launch, call queryPurchasesAsync() to find unconsumed purchases. But:

// BEFORE — recovery flow
for (Purchase p : unconsumedPurchases) {
    if (localDb.isVerified(p.getPurchaseToken(), p.getOrderId())) {
        continue;   // "already verified, skip"
    }
    sendReceiptToBackend(p);
}

Recovery was written on the assumption that verified = done. So the exact group of broken orders (verified but not consumed) was the group recovery skipped. The function even had OrConsume in its name, yet never consumed anything.

The code had no state for "verified, waiting to be consumed". There were only two: not verified and verified.

3.4 One receipt cache for every product type, plus a stuck lock

  • All three purchase flows (single, credit pack, combo) wrote to the same three keys in SharedPreferences (token, data, signature). If a credit-pack order was still pending and the user bought a single item, the earlier order was overwritten. One flow could also clear the other's cache.
  • The isSendingReceipt flag (to stop duplicate receipt sends) was persisted to disk but never reset on app start. If the app was killed mid-send, tryLock(token) returned false forever after, and that order was never retried.

The chain of events that leads to a refund

User buys → Google charges successfully
         → app sends receipt → backend verifies OK → user gets content ✅
         → consumeItem(): client just disconnected → silent return ❌
         → cache cleared: token is gone
         → next launch: recovery sees "isVerified == true" → skip
         → 3 days pass...
         → Google: "not acknowledged" → AUTOMATIC REFUND 💸

The fix

The principle: an order may only leave the app once Google Play confirms it was consumed. Until then, it must always be stored, and there must always be a way to process it again.

4.1 consume must report its result

// AFTER
public interface ConsumeCallback {
    void onConsumeFinished(boolean success, String token);
}

public void consumeItem(String token, @Nullable ConsumeCallback callback) {
    if (token == null || token.isEmpty()) {
        if (callback != null) callback.onConsumeFinished(false, token);
        return;
    }
    if (!isReady()) {
        log.e("[CONSUME] deferred, billing not ready");
        startConnection();                          // reconnect proactively
        if (callback != null) callback.onConsumeFinished(false, token);
        return;
    }

    ConsumeParams params = ConsumeParams.newBuilder().setPurchaseToken(token).build();
    billingClient.consumeAsync(params, (billingResult, outToken) -> {
        int code = billingResult.getResponseCode();
        // ITEM_NOT_OWNED = already consumed earlier → treat as success (idempotent)
        boolean success = code == BillingResponseCode.OK
                       || code == BillingResponseCode.ITEM_NOT_OWNED;
        if (!success) crashReporter.log("consume failed code=" + code);
        if (callback != null) callback.onConsumeFinished(success, token);
    });
}

Watch out for ITEM_NOT_OWNED. When retrying a consume, this code means the previous attempt actually succeeded, so it must count as success. Treat it as an error and the app retries forever.

4.2 A state machine for orders: PendingPurchaseStore

The three shared keys are replaced by a store keyed by purchaseToken. Each entry carries enough information to describe itself:

data class PendingPurchase(
    val token: String,
    val orderId: String,
    val receipt: String,
    val signature: String,
    val productId: String,
    val kind: String,          // SINGLE / CREDIT_PACK / COMBO
    val targetId: String,
    val state: String,         // PENDING_VERIFY | VERIFIED_PENDING_CONSUME
    val attempts: Int,
    val createdAt: Long,
    val updatedAt: Long,
)

An entry's lifecycle:

onPurchasesUpdated   ──► upsert(PENDING_VERIFY)
backend returns OK   ──► markVerifiedPendingConsume()
consume returns OK   ──► remove()

VERIFIED_PENDING_CONSUME is the missing state from section 3.3. With it, "verified" no longer gets read as "done".

Because this data is money, the store writes with commit() (synchronous) rather than apply(), so it is on disk before the process can be killed.

4.3 The new order of operations after a successful verify

// AFTER
String token = resolveCurrentToken();   // not just the instance field

if (token == null || token.isEmpty()) {
    // Can't identify the order → KEEP the cache for the reconciler, do NOT clear it
    log.e("[CONSUME] verified but no token — caches kept");
    return;
}

PendingPurchaseStore.markVerifiedPendingConsume(token);
billingManager.consumeItem(token, (success, t) -> {
    if (success) PendingPurchaseStore.remove(t);
    else         PendingPurchaseStore.incrementAttempt(t);   // reconciler retries it
});

A side bug was fixed at the same time: the token used to live in a Fragment field. When the Fragment was recreated (rotation, process death) or the billing callback went to another screen, that field was null. The old code then skipped the consume but still cleared the cache, and the order was lost. The new code looks for the token in several places, and if it still can't find one, it keeps the cache.

4.4 PurchaseConsumeReconciler: cleaning up stuck orders

An object with exactly one job: find orders that are verified but not consumed, and consume them.

object PurchaseConsumeReconciler {
    @Volatile private var isRunning = false

    fun reconcile(context: Context) {
        if (isRunning) return                       // no overlapping runs
        val billing = BillingManager.getInstance(context)
        if (!billing.isReady) { billing.startConnection(); return }

        isRunning = true
        billing.queryUnconsumedPurchases { result, purchases ->
            try {
                if (result.responseCode != OK) return@queryUnconsumedPurchases
                // In the store but no longer reported by Google → consumed elsewhere → prune
                PendingPurchaseStore.pruneMissing(purchases.orEmpty().map { it.purchaseToken })
                purchases?.forEach { reconcileOne(billing, it) }
            } finally { isRunning = false }
        }
    }

    private fun reconcileOne(billing: BillingManager, p: Purchase) {
        if (p.purchaseState != Purchase.PurchaseState.PURCHASED) return
        val entry = PendingPurchaseStore.get(p.purchaseToken)
        val verified = localDb.isVerified(p.purchaseToken, p.orderId)

        if (!verified && entry?.isAwaitingConsume() != true) {
            // Not verified → sending the receipt belongs to the purchase flow; just make sure it's recorded
            if (entry == null) PendingPurchaseStore.record(p)
            return
        }
        // Verified but not consumed → consume now
        billing.consumeItem(p.purchaseToken) { ok, t ->
            if (ok) PendingPurchaseStore.remove(t) else PendingPurchaseStore.incrementAttempt(t)
        }
    }
}

Where to call the reconciler? In onBillingSetupFinished() when the result is OK. Not right after startConnection(), because isReady() is still false at that point and the reconciler would do nothing.

The reconciler only consumes. It deliberately does not send receipts to the backend, since that belongs to each purchase flow. Splitting the responsibility this way keeps two places from sending the same receipt.

4.5 Backend errors handled in one place: PurchaseErrorPolicy

Each purchase flow used to handle backend errors on its own, and for the same HTTP 400 the flows did opposite things. The fix moves this into a single classifier:

enum class ReceiptFailureAction {
    WAIT_FOR_NETWORK,            // offline → keep it, resend when back online
    CONSUME_ALREADY_PROCESSED,   // backend: "receipt already processed" → user has it → MUST consume
    KEEP_WITHOUT_CONSUME,        // genuinely rejected → do NOT consume, so Google refunds the user
    KEEP_FOR_RETRY,              // temporary server error → keep it, retry later
}

Telling "already processed" (must consume) from "rejected" (must not consume) is the hardest part:

  • Consume a genuinely rejected order by mistake and the user loses their money, gets nothing, and can no longer be auto-refunded by Google. This is the worst case.
  • Fail to consume an already-processed order and Google refunds an order that was delivered. That is the original bug.

So the classifier prefers a machine-readable error_code, and only falls back to message text when there is none. Each pattern must be at least two words (e.g. "already processed"), never a single word like "already", to avoid false matches.

One more detail: with fixed per-price SKUs, an unconsumed order blocks the user from buying at that price again for 3 days. That gets in the way during testing, so the app has a "consume every unrecognised 400" flag, but it is tied to BuildConfig.DEBUG:

// Debug: on, so testers don't get locked out of a price point for 3 days.
// Release: off, so a genuine rejection always keeps the user's refund path.
val CONSUME_UNRECOGNISED_400_ON_FIXED_SKUS: Boolean = BuildConfig.DEBUG

Tying the flag to the build type instead of a hand-edited constant means a release can't ship with it on by accident. The price is that debug and release builds behave differently in the payment flow, so QA must test at least once on a release build.

4.6 Resetting the stuck lock on startup

isSendingReceipt now comes with sendingReceiptToken, is released on app start, and is cleared together with the receipt cache. An app killed mid-send no longer locks an order forever.

4.7 Per-stage logging you can trace

The whole payment flow uses its own logger, with a prefix per stage: [BILLING], [CONSUME], [RECOVER], [POLICY]. Every place that used to return silently (client not ready, no listener, listener taken over by another screen...) now leaves a log line, and serious failures go to the crash reporter as breadcrumbs. For a bug that never crashes and never shows an error, logs are the only way to know what happened.

Before and after

  • consume result

    Before
    Ignored
    After
    success/fail callback, log + crash breadcrumb
  • Client not ready

    Before
    Silent return
    After
    Reconnect + report failure so it is retried
  • Pending order storage

    Before
    3 shared keys, overwriting each other
    After
    Store keyed by token, each entry self-describing
  • States

    Before
    Not verified / Verified
    After
    PENDING_VERIFY → VERIFIED_PENDING_CONSUME → removed
  • When an order is deleted

    Before
    Right after calling consume
    After
    Only when Google confirms the consume
  • "Verified but not consumed" orders

    Before
    Skipped by recovery → refunded
    After
    Consumed by the reconciler every time billing connects
  • HTTP 400 from backend

    Before
    Each flow handles it differently
    After
    One shared policy, four clear actions
  • Receipt-send lock

    Before
    Could stay stuck forever
    After
    Reset on startup

Lessons learned

  1. "The user got the goods" doesn't mean "the transaction is done". On Google Play, it's done only once acknowledged/consumed. Treat that as its own step, with its own state.
  2. No fire-and-forget on the payment path. Every async call that changes money state needs a callback, a log, and a retry path.
  3. Only delete data once the other side has confirmed. Deleting the token before Google confirmed the consume is what directly lost the orders.
  4. Re-check the assumptions in recovery code. A harmless-looking if (verified) continue; skipped exactly the orders that needed handling.
  5. Store pending data per transaction, not in shared keys. With several purchase flows, sooner or later they run at the same time.
  6. Tell "already processed" from "rejected" by error code, not by message. Consume wrongly and the user loses money; fail to consume and the business does.
  7. Be careful with state persisted to disk. Any lock, flag or cache that survives a restart needs a way to be reset on startup.
  8. Keep transaction state somewhere that outlives the UI. A Fragment can be recreated at any moment; the transaction still has to be finished.

A checklist for your own billing flow

  • Do you check the result of consumeAsync / acknowledgePurchase?
  • What happens if BillingClient disconnects right when you consume?
  • Is the token deleted before the consume succeeds?
  • Is there a "verified, waiting to consume" state?
  • Does recovery handle orders that are verified but not consumed?
  • Do you reconcile every time billing reconnects?
  • Is ITEM_NOT_OWNED on consume treated as success?
  • Can two product types bought in parallel overwrite each other's pending data?
  • If the app is killed mid receipt-send, is it retried next time?
  • Have you tested: go offline after paying, wait, then reopen the app?
  • Have you tested on a release build (if debug and release behave differently)?

This bug never crashed and never showed an error in the UI. It was only found when someone reconciled revenue against refunded orders. If your app has in-app purchases, go look at your consume step and check whether its result is being ignored.

  • Google Play Billing
  • In-app purchase
  • Consume
  • State machine
  • Reconciler

Keep reading

All posts