Terminal
Terminal/Skill
Guide to building a backend that verifies Google Play purchase tokens with the Developer API, stores subscription state, and acknowledges purchases.
By RevenueCat
Works with
npx skills add revenuecat/play-billing-skills --skill backend-architectureThe client is not trustworthy. Signatures can be forged, APKs can be modified, and local purchase data can be faked. Your backend must treat the purchase token as an opaque value to verify with Google. This skill walks you through the verification pipeline, from receiving a token to persisting entitlement state.
Confirm the following before you write code.
purchaseToken as the primary key.If any of these are missing, stop and resolve before continuing.
Do these steps once per project.
play-billing-backend). No Cloud IAM roles are required.For containerized deployments on Google Cloud, prefer Workload Identity Federation over JSON key files. GoogleCredentials.getApplicationDefault() picks up the attached service account automatically.
Every purchase follows the same pipeline. Plan each step in code before wiring them.
Use purchaseToken as the primary key for purchase records.
| Identifier | Use it as key? | Reason |
|---|---|---|
purchaseToken | Yes | What the Developer API accepts. Stable across subscription renewals. |
orderId | No (store only) | Changes every renewal (appended ..0, ..1). Useful for support and reconciliation. |
linkedPurchaseToken | No (foreign key) | Points to the previous token in an upgrade or downgrade chain. |
Initialize once at startup. The client is thread safe and caches access tokens internally.
fun createPublisherClient(): AndroidPublisher {
val credentials = GoogleCredentials
.getApplicationDefault()
.createScoped(listOf(AndroidPublisherScopes.ANDROIDPUBLISHER))
val transport = GoogleNetHttpTransport.newTrustedTransport()
return AndroidPublisher.Builder(
transport,
GsonFactory.getDefaultInstance(),
HttpCredentialsAdapter(credentials),
).setApplicationName("your-app-backend").build()
}
The client posts the purchase token, product ID, and user ID. Your endpoint runs the full pipeline and returns a final entitlement decision.
@PostMapping("/purchases/verify")
fun verify(@RequestBody req: VerifyRequest): VerifyResponse {
val sub = publisher.purchases().subscriptionsv2()
.get(packageName, req.purchaseToken).execute()
validateOrThrow(sub, req.productId)
requireActive(sub.subscriptionState)
return processPurchase(req.userId, req.purchaseToken, sub)
}
purchases.subscriptionsv2.get is the source of truth for subscription state.
fun getSubscription(packageName: String, token: String): SubscriptionPurchaseV2 =
publisher.purchases().subscriptionsv2().get(packageName, token).execute()
Fields to read from the response:
| Field | Purpose |
|---|---|
subscriptionState | Active, canceled, in grace period, on hold, paused, expired, or pending. |
lineItems[].productId | Product sold. Must match what the client claimed. |
lineItems[].expiryTime | Current period end. |
linkedPurchaseToken | Previous token in upgrade or downgrade chain. |
acknowledgementState | Whether you have acknowledged yet. |
externalAccountIdentifiers | Obfuscated account and profile IDs from the purchase flow. |
Grant the entitlement only when subscriptionState == SUBSCRIPTION_STATE_ACTIVE.
purchases.products.get requires the product ID in the path.
fun getProduct(packageName: String, productId: String, token: String): ProductPurchase =
publisher.purchases().products().get(packageName, productId, token).execute()
| Field | Meaning |
|---|---|
purchaseState | 0 purchased, 1 canceled, 2 pending. Grant only on 0. |
consumptionState | 0 not consumed, 1 consumed. |
acknowledgementState | 0 not acknowledged, 1 acknowledged. |
orderId | Store for support and reconciliation. |
Use the purchase token as the primary key. Check for duplicates before granting.
data class PurchaseRecord(
val purchaseToken: String,
val userId: String,
val productId: String,
val orderId: String?,
val purchaseState: String,
val linkedPurchaseToken: String?,
val acknowledgedAt: Instant?,
val grantedAt: Instant,
)
fun processPurchase(userId: String, token: String, sub: SubscriptionPurchaseV2) {
sub.linkedPurchaseToken?.let { purchaseRepository.deactivate(it) }
if (purchaseRepository.findByToken(token) != null) return
purchaseRepository.save(recordFrom(userId, token, sub))
entitlementService.activate(userId, sub.lineItems.first().productId)
}
Deactivating the linked token prevents two active entitlements after an upgrade or downgrade.
Acknowledge from the backend after the entitlement is granted. If acknowledgement fails, retry with backoff.
fun acknowledgeSubscription(packageName: String, productId: String, token: String) {
publisher.purchases().subscriptions()
.acknowledge(packageName, productId, token, SubscriptionPurchasesAcknowledgeRequest())
.execute()
}
For one time products, pick the call that matches the product type.
| Product type | API call | Notes |
|---|---|---|
| Non consumable | purchases.products.acknowledge | Grants permanent ownership. |
| Consumable | purchases.products.consume | Also acknowledges. Do not call both. |
| Subscription | purchases.subscriptions.acknowledge | Renewals are already acknowledged. |
Back off on 429 and 503. Respect Retry-After when present.
fun <T> executeWithRetry(maxAttempts: Int = 3, block: () -> T): T {
repeat(maxAttempts) { attempt ->
try { return block() } catch (e: GoogleJsonResponseException) {
if (e.statusCode !in listOf(429, 503)) throw e
Thread.sleep((1L shl attempt) * 1000L)
}
}
throw RuntimeException("Retries exhausted")
}
The default quota is 200,000 queries per day across subscriptionsv2.get and products.get. Apply all four practices.
Before you call the backend done, confirm:
linkedPurchaseToken deactivates the old entitlement.purchaseState == 2 is stored but not granted until it transitions to 0.externalAccountIdentifiers, not through a token chain, because Google does not always set linkedPurchaseToken on resubscribe.