Purchase Flow logo

Purchase Flow

Organization
RevenueCat
purchase-flow

Use this skill when implementing the Play Billing purchase flow end to end. Covers building BillingFlowParams, launching launchBillingFlow(), receiving results in PurchasesUpdatedListener, handling every BillingResult outcome, and posting to your backend.

Overview

PublisherRevenueCat
Repositoryplay-billing-skills
Skill namepurchase-flow
Stars
58
Forks
0
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by RevenueCat on GitHub. Read the source before you install it.

Installation

Install the Purchase Flow AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/purchase-flow
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/RevenueCat/play-billing-skills.git /tmp/play-billing-skills
mkdir -p .claude/skills
cp -r /tmp/play-billing-skills/google-play/purchase-flow .claude/skills/purchase-flow
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Purchase Flow in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Purchase Flow on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Purchase Flow is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Purchase Flow

Implements the full client side purchase sequence: build BillingFlowParams, launch launchBillingFlow(), receive callbacks in PurchasesUpdatedListener, handle every response code, then verify, acknowledge, and grant access.

Phase 0: Intent

Use this skill when you need to:

  • Launch a purchase from a "Buy" tap for a one time product or a subscription.
  • Wire a PurchasesUpdatedListener and handle every BillingResponseCode.
  • Decide where to verify, where to acknowledge, and how to grant entitlements idempotently.
  • Support pending transactions (cash at convenience store, carrier billing, slow card auth).
  • Sell subscriptions with add ons (several subscription items in one transaction).

Out of scope: connecting BillingClient, querying ProductDetails, subscription upgrades or downgrades, and retry or error taxonomy beyond the launch results listed below.

Phase 1: Discovery

Confirm the preconditions before you build params.

CheckHowWhy
BillingClient connectedbillingClient.isReady == trueCalls fail without a live connection.
ProductDetails cachedHeld from a prior queryProductDetailsAsyncRequired input to ProductDetailsParams.
Pending purchases enabledBillingClient.Builder.enablePendingPurchases(...) was calledUsers with delayed payment cannot buy otherwise.
Existing ownership knownRan queryPurchasesAsync() recentlyPrevents ITEM_ALREADY_OWNED surprises.
Offer token resolvedSubs: from subscriptionOfferDetails. One time: from oneTimePurchaseOfferDetailsList when the product has several purchase options or offersA missing subs token returns DEVELOPER_ERROR; a missing one time token silently buys the default purchase option.

Record the product type (INAPP vs SUBS), the selected basePlanId, and the chosen offerToken before moving on.

Phase 2: Plan

Decide the following before you call newBuilder().

Account identifiers

  • obfuscatedAccountId: attach a one way hash of your internal user id. Never pass raw email or plain text. Helps Google Play detect fraud across devices.
  • obfuscatedProfileId: attach only if your app has multiple profiles under one account (family streaming, kid profiles).

Offer personalization

  • Set setIsOfferPersonalized(true) only if the price was chosen by automated decision making for this user. EU regulation requires a disclosure, which Google Play renders for you.
  • Default is false. Do not set true for uniform promotional pricing.

Offer token selection (subscriptions)

Group offers by base plan, then pick the best eligible offer. Google already filters offers the user cannot redeem.

kotlin
val offersByPlan = productDetails
    .subscriptionOfferDetails
    ?.groupBy { it.basePlanId }
    ?: emptyMap()

val chosenOffer = offersByPlan[selectedBasePlanId]
    ?.firstOrNull() ?: return

Whatever the user tapped in your UI must map to the exact offerToken you pass. Show the first pricingPhases entry (free trial, intro price) in the UI and the recurring phase after it.

Backend contract

Decide whether acknowledge and grant happen server side (primary) or client side (fallback). Server side keeps verify, grant, and acknowledge in one transaction. Keep client side as a fallback when the server is unreachable.

Phase 3: Execute

Build params for a one time product

kotlin
val productDetailsParams = BillingFlowParams.ProductDetailsParams
    .newBuilder()
    .setProductDetails(productDetails)
    // offerToken is nullable on OneTimePurchaseOfferDetails. selectedOffer is the entry the user chose from
    // productDetails.oneTimePurchaseOfferDetailsList; fail fast rather than silently buying the default purchase option.
    .setOfferToken(requireNotNull(selectedOffer.offerToken))
    .build()

val flowParams = BillingFlowParams.newBuilder()
    .setProductDetailsParamsList(listOf(productDetailsParams))
    .setObfuscatedAccountId(hashUserId(currentUser.id))
    .build()

Build params for a subscription

kotlin
val productDetailsParams = BillingFlowParams.ProductDetailsParams
    .newBuilder()
    .setProductDetails(productDetails)
    .setOfferToken(chosenOffer.offerToken)
    .build()

val flowParams = BillingFlowParams.newBuilder()
    .setProductDetailsParamsList(listOf(productDetailsParams))
    .build()

Launch the flow

kotlin
val result = billingClient.launchBillingFlow(activity, flowParams)
if (result.responseCode != BillingResponseCode.OK) {
    handleLaunchError(result)
}

You must pass the current Activity. OK here means the dialog was shown, not that payment succeeded. The real result arrives in PurchasesUpdatedListener.

Handle launch response codes

CodeMeaningAction
OKDialog shownWait for listener callback.
ITEM_ALREADY_OWNEDUser owns product or has unacknowledged purchaseRefresh via queryPurchasesAsync() and process it.
DEVELOPER_ERRORBad params, missing offer token, wrong package nameFix params, check Console listing.
FEATURE_NOT_SUPPORTEDDevice or Play Store does not support the product typeHide the buy button on this device.
BILLING_UNAVAILABLEBilling unavailable for this user or device: outdated Play Store, unsupported country, purchases disabled by an admin, payment method cannot be charged, or (PBL 9+) Play Store blocked by the system such as kids modeDo not auto retry. Show a generic message with a Try again button.
ITEM_UNAVAILABLENot available in region or deactivatedCheck Console availability.
NETWORK_ERRORCannot reach Play serversRetry after delay, do not loop aggressively.

Receive purchase results

kotlin
val listener = PurchasesUpdatedListener { result, purchases ->
    when (result.responseCode) {
        BillingResponseCode.OK ->
            purchases?.forEach { handlePurchase(it) }
        BillingResponseCode.USER_CANCELED -> Unit
        BillingResponseCode.ITEM_ALREADY_OWNED ->
            refreshPurchases()
        else -> handleError(result)
    }
}

Process a successful purchase (5 steps)

  1. Verify server side. Post purchase.purchaseToken to your backend. Backend calls purchases.products.get (one time) or purchases.subscriptionsv2.get (subs). For one time products check purchaseState == 0 (Purchased), productId, and that orderId was not seen before. For subscriptions check subscriptionState (SUBSCRIPTION_STATE_ACTIVE for a completed new purchase), each lineItems[].productId, and lineItems[].expiryTime (RFC 3339).

  2. Check purchase.purchaseState. Grant only on PURCHASED. Show pending UI on PENDING. Log on UNSPECIFIED_STATE.

  3. Grant entitlement idempotently. Use purchaseToken as a unique key. A retry, an RTDN, and a second device query must not stack grants.

  4. Acknowledge or consume within 3 days.

    kotlin
    // Non consumable and subscriptions
    val ackParams = AcknowledgePurchaseParams.newBuilder()
        .setPurchaseToken(purchase.purchaseToken)
        .build()
    billingClient.acknowledgePurchase(ackParams) { r -> /* check OK */ }
    kotlin
    // Consumable
    val consumeParams = ConsumeParams.newBuilder()
        .setPurchaseToken(purchase.purchaseToken)
        .build()
    billingClient.consumeAsync(consumeParams) { r, t -> /* check OK */ }

    Prefer server side acknowledgement. Fall back to client side only after retries fail.

  5. Notify the user. Show specific confirmation ("You now have Premium") immediately from the client. For subs, show next billing date and a link to https://play.google.com/store/account/subscriptions. Return the user to the content they were trying to unlock.

Handle pending transactions

kotlin
fun handlePurchase(purchase: Purchase) {
    when (purchase.purchaseState) {
        Purchase.PurchaseState.PENDING -> {
            showPendingMessage(purchase)
            return
        }
        Purchase.PurchaseState.PURCHASED -> {
            verifyAndGrantAccess(purchase) // idempotent, keyed by purchaseToken
            if (!purchase.isAcknowledged) acknowledge(purchase)
        }
    }
}

Transitions arrive via a later PurchasesUpdatedListener fire, an RTDN on your server, or a fresh queryPurchasesAsync().

Call queryPurchasesAsync at the right moments

  • On connect: right after startConnection() succeeds. Catches cross device purchases and reinstalls.
  • On app launch: keeps local entitlement cache honest against refunds and expirations.
  • On foreground resume: catches cancellations in Play Store and pending purchases that completed in the background.

Subscriptions with add ons

Add several subscription ProductDetailsParams (each with an offer token); the first is the base item. All items must be auto renewing base plans with the same billing period and unique product IDs, at most 50 items (not available in KR). One purchase token covers the bundle: acknowledge once, then iterate purchase.products to grant every item.

Phase 4: Verify

Prove the flow works before calling it done.

  • launchBillingFlow() returns OK for a real product in an internal test track.
  • PurchasesUpdatedListener fires with OK and a non null purchases list on success, and with USER_CANCELED when the user dismisses the dialog.
  • Every branch in the response code table above has a code path and a log line.
  • Server side verification runs before grantEntitlement. Granting twice with the same token produces the same result (idempotency test).
  • Every PURCHASED purchase is acknowledged or consumed within 3 days. Monitor unacknowledged count.
  • A test with a delayed payment method (use the tester card or a convenience store flow in a test region) surfaces a pending state and does not grant access.
  • A subscription purchase without setOfferToken returns DEVELOPER_ERROR (negative test) and your code surfaces it cleanly.
  • queryPurchasesAsync() is wired to connect, app launch, and onResume.
  • For multi line bundles, purchase.products yields every product id and each gets an entitlement.

References

Frequently asked questions

What does the Purchase Flow AI skill do?

Use this skill when implementing the Play Billing purchase flow end to end. Covers building BillingFlowParams, launching launchBillingFlow(), receiving results in PurchasesUpdatedListener, handling every BillingResult outcome, and posting to your backend.

Why use Purchase Flow on TypingMind?

Because you install it once and use it with any model. Purchase Flow is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Purchase Flow in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/purchase-flow. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Purchase Flow?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Purchase Flow?

As many as you like. As long as a model supports skills, you can use Purchase Flow with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Purchase Flow AI skill free?

Yes. It is published on GitHub by RevenueCat under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇