Bhargav Naidu Gedela

Writing

Selling credit with Google Play Billing, checked on the server

Merge Clouds charges for copies in bytes of credit. Every account gets 5 GiB once; after that you buy packs. Credit is sold through Google Play Billing, as Play’s payments policy requires for digital goods; it went in on 27–28 November.

The rule I set myself: the app never decides that someone paid. It opens Google’s sheet and passes along what Google hands back. The server checks every purchase with Google before a single byte is credited.

The flow

app    asks the server for the packs        server notes: hash(user id) → user
app    launchBillingFlow(obfuscatedAccountId = hash)
Play   → purchase token to the app
app    sends {productId, purchaseToken} to the server
server Google Play Developer API: look up the token
       check product, account hash, state → insert grant → add credit → consume
Play   → Pub/Sub push → the server   (completed purchases, refunds)

On the app side it’s Play Billing Library 8 with one-time consumable products. The app never consumes or acknowledges a purchase. That’s the server’s job, so there’s exactly one place where a purchase becomes credit.

Tying a purchase to an account

Every purchase carries an obfuscatedAccountId. The app sets it to the lowercase hex SHA-256 of the user’s server id. The server works out the same hash and compares it with what Google says the purchase carries. If they differ, the answer is a 409: “This purchase was made from another Merge Clouds account.” That stops someone replaying a purchase token they got from another account.

A hash only goes one way, which caused a small problem. When a notification arrives from Google with no app involved (more on that below), all the server has is the hash. So it keeps its own lookup from hash to user, and records it when the app lists the packs, before any purchase:

// The app lists the packs before any purchase; remember whose account hash the purchase will carry
if (userDetails != null) {
    playPurchaseService.rememberAccount(userService.userExists(userDetails.getUsername()).getId());
}

Crediting exactly once

The app can report the same purchase more than once. It reports it right after the sheet closes, again when Home or Credits opens and Play still holds an unconsumed purchase, and Google may also report it through a notification. All of these end in the same method, verifyAndGrant.

The guarantee comes from MongoDB, not from my code being careful. play_purchases has a unique index on purchaseToken. The grant is an insert. A second insert for the same token fails, and that call credits nothing:

try {
    mongoTemplate.insert(grant);   // sets grant's id
} catch (DuplicateKeyException race) {
    // Another call for this token won the insert and credits it; this one adds nothing
    PlayPurchase winner = findByToken(token);
    if (winner == null) throw unavailable("Couldn't record the purchase. Try again in a moment.");
    return alreadyGranted(user, pid, winner);
}
creditService.addCredits(user.getId(), bytes);

Auto index creation is off in this backend, so the service creates the index at startup. Until it exists, the server refuses to grant anything rather than grant without the guard.

Before the insert, the server checks with Google: the token must be known, the line item must be the pack the app named, the account hash must match, and the state must be PURCHASED. A PENDING purchase (a payment that settles later) gets a “pending” answer and no credit.

Consuming

A consumable has to be consumed before the same pack can be bought again. Google also refunds a purchase that isn’t acknowledged within three days, and consuming counts as acknowledging. So the server consumes right after the grant. If that call fails, the grant stays and the failure is recorded on the purchase. A scheduled job retries every 30 minutes for purchases still inside that three-day window. A failed consume never undoes a credit.

Notifications from Google

Play’s real-time developer notifications arrive as Pub/Sub pushes to an endpoint on the server. Google isn’t a signed-in user, so the usual session check can’t apply, and the controller checks the push itself. The Authorization header must carry a Google-signed OIDC token whose audience is this endpoint’s URL, issued by Google, for the push subscription’s service account, with a verified email:

JsonWebSignature.Payload claims = verifier.verify(authorizationHeader.substring(7).trim());
if (claims == null || !ISSUERS.contains(claims.getIssuer())) return false;
Object email = claims.get("email");
Object verified = claims.get("email_verified");
boolean ok = pushServiceAccount.equalsIgnoreCase(String.valueOf(email))
        && (Boolean.TRUE.equals(verified) || "true".equals(String.valueOf(verified)));

The status codes matter, because Pub/Sub retries anything that isn’t a success. 204 means handled or deliberately ignored, so it stops. 401 means not a real push. 503 means “try again”, for when Google’s API or the database can’t be reached. Messages for another package, subscription notifications and unreadable bodies are all ignored with a 204, so they don’t come back forever.

Two notifications do real work:

  • A one-time purchase completed. The server credits it through the same verifyAndGrant path, as if the app had reported it. This covers a pending payment that cleared after the app was closed, or a report that never reached the server.
  • A voided purchase (refund, chargeback, cancellation). The credit is taken back.

Because every action goes through the unique token or a conditional update, a notification delivered twice changes nothing the second time.

Refunds

Taking credit back is one conditional update that moves the purchase from GRANTED to REVOKED. Only one caller can win that, so the credit is taken back at most once. Then the server takes back up to the pack’s bytes from whatever credit is left, never below zero. The amount actually taken back is stored on the purchase, so the purchase history can show it.

Notifications can be missed, so a poll of Google’s voided purchases list runs every six hours as a backstop. It keeps a cursor, re-reads the last day each run because Google records voids with some lag, and never looks back further than Google’s 30 days. The cursor only moves when every page was handled, so a failed run simply repeats.

Edge cases I ran into

  • “Already owned.” If an earlier purchase of a pack was never consumed, Play refuses to sell it again. The app treats that response as a cue to report the waiting purchases, and the server credits them.
  • A sheet at the wrong time. The app first showed the “credit added” sheet whenever a purchase got credited, including the quiet ones reported when Home opened. Now the sheet only appears right after buying. Quiet restores just update the balance.
  • Paid but not credited yet. If the server can’t reach Google, the app says so and leaves the purchase with Play. The next restore credits it.