Security logo

Security

Organization
RevenueCat
security

Use this skill when hardening a Google Play Billing integration against fraud. Covers server side receipt verification, replay attack protection, device fingerprinting, velocity checks, and the most common billing fraud patterns.

Overview

PublisherRevenueCat
Repositoryplay-billing-skills
Skill namesecurity
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 Security 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/security
  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/security .claude/skills/security
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Security 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 Security 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 Security 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.

Securing Google Play Billing

Anything running on the user device can be tampered with. If your trust model lives in the client, you have already lost. This skill shows you how to move trust to your backend and defend against the attack patterns you will actually see in production.

Phase 1: Assess

Before you write a line of defensive code, answer these questions about your current integration:

  • Where does purchase verification happen today? Client, backend, or both?
  • Does your database enforce a unique constraint on purchaseToken?
  • Do you set obfuscatedAccountId and obfuscatedProfileId on every purchase flow?
  • Do you poll the Voided Purchases API on a schedule?
  • Do any access decisions rely on System.currentTimeMillis() from the device?

Any "no" answer maps to a layer you are missing below.

Phase 2: Plan the Layered Defense

Fraud prevention is not a single check. It is a stack of controls where each layer catches a different attack class. Plan all of them, even if you ship them incrementally.

LayerPurposeWhere it runs
1. Backend receipt verificationConfirm the purchase exists in Google's recordsYour server, via purchases.products.get / purchases.subscriptionsv2.get
2. Response field validationCatch product swaps and cross app token reuseYour server (check productId and purchaseState; the package is bound by the request path)
3. Purchase state checkReject PENDING and expired purchasesYour server
4. Replay protectionBlock reuse of valid tokensUnique constraint on purchase token column; for subscriptions, once a new token is verified as purchased (not while it is SUBSCRIPTION_STATE_PENDING), revoke the entitlement on its linkedPurchaseToken
5. Token to user bindingDetect token sharing across accountsYour server (store and compare userId on duplicates)
6. AcknowledgementPrevent auto refund at 3 day markYour server, after entitlement grant
7. Voided purchase syncRevoke access on refunds and chargebacksvoidedPurchaseNotification RTDN in real time, plus a daily purchases.voidedpurchases.list backfill with type=1 (includes subscriptions; key by orderId) over the last 30 days
8. Device and profile signalsGive Google and yourself correlation dataClient sets obfuscatedAccountId / obfuscatedProfileId before launching the flow
9. Integrity and pinningRaise the cost of modified APKsPlay Integrity API plus TLS certificate pinning
10. Server time of recordDefeat timezone manipulationAll time decisions use server clock

Decide the order based on risk. For most apps: layers 1 through 6 are non negotiable for launch. Layer 7 follows within the first week. Layers 8 through 10 harden against the targeted attacks you will see later.

Phase 3: Execute

Step 1: Send the token from client to backend

Keep the client thin. Its only job is to hand the token to your server along with the current user identifier.

kotlin
override fun onPurchasesUpdated(
    result: BillingResult,
    purchases: List<Purchase>?
) {
    if (result.responseCode != BillingResponseCode.OK) return
    purchases?.forEach { p ->
        if (p.purchaseState == PurchaseState.PURCHASED) {
            api.verify(p.purchaseToken, p.products, currentUserId)
        }
    }
}

Send over HTTPS. Pin the server certificate if you can. Include your own auth token so the server knows which user is claiming the purchase.

Step 2: Verify on the backend and bind the token to the user

The server is the only place that decides whether a purchase is real. Call the Google Play Developer API, validate the response, then atomically insert the entitlement under a unique constraint on purchase_token. That constraint is your replay defense.

python
def grant_entitlement(token, claimed_product, user_id):
    # The package is bound by the request path: Google rejects a token from another app.
    record = play_api.get_purchase(PACKAGE, claimed_product, token)
    if record.get("productId", claimed_product) != claimed_product:
        raise PurchaseRejected("product mismatch")
    state = record["purchaseState"]
    if state == 2:  # PENDING (includes pre orders): not a rejection, do not refund; grant after ONE_TIME_PRODUCT_PURCHASED
        raise PurchasePending("pending")  # a separate exception from PurchaseRejected
    if state != 0:  # 1 = CANCELED
        raise PurchaseRejected("not purchased")
    existing = db.entitlements.find_by_token(token)
    if existing:
        if existing.user_id != user_id:
            security_log.flag("token_reuse", token, user_id)
        return existing
    db.entitlements.insert_unique(token, user_id, record.get("orderId"))  # promo code purchases have no orderId
    play_api.acknowledge(PACKAGE, claimed_product, token)

Two things do the real work here. First, the unique insert on token means a replayed token from any account is a database conflict, not a second grant. Second, comparing the claiming user_id against the original owner on every lookup surfaces token sharing and account abuse patterns that a naive "already processed, return success" path would hide.

If a purchase fails validation or abuse checks (for example a product mismatch; a PENDING purchase is not a failure), do not grant it and do not leave it to expire unacknowledged: call orders.refund with revoke=true for its orderId so Google records that you rejected it.

Step 3: Add device and profile signals before the purchase

Set both obfuscated identifiers on every purchase flow. They cost nothing and give Google, and you, a way to correlate across sessions and Google accounts.

kotlin
val params = BillingFlowParams.newBuilder()
    .setProductDetailsParamsList(listOf(productParams))
    .setObfuscatedAccountId(sha256(currentUser.id))
    .setObfuscatedProfileId(sha256(currentUser.activeProfileId))
    .build()
billingClient.launchBillingFlow(activity, params)

Both values come back in the purchase record, so your backend can reconcile them with your user database even if the user switches Google accounts.

Fraud Pattern to Mitigation Reference

Fraud patternPrimary mitigationBackstop
Modified APK removes client checksBackend receipt verificationPlay Integrity API, R8 obfuscation
Fabricated purchase tokenspurchases.products.get returns error, server rejectsPackage name and product ID checks
Stolen token from another appThe API call scoped to your packageName rejects foreign tokensToken to user binding
Product swap (cheap token, expensive claim)productId validation against client claimPrice recorded from API response, not client
Replayed token on same accountUnique constraint on purchase_tokenIdempotent grant returns existing record
Replayed token across accountsToken to user binding with alert on mismatchDevice fingerprint correlation
Pending payment treated as paidReject purchaseState == 2, wait for RTDNAcknowledge only after state becomes PURCHASED
Missed acknowledgement triggers auto refundServer side acknowledge after grant with retryMonitor acknowledgement failures as high priority
Refund abuse and chargebacksvoidedPurchaseNotification RTDN plus daily voidedpurchases.list?type=1 backfillGraduated enforcement (warn, restrict, ban)
Consumable refund after spendDeduct refunded amount from user balanceRestrict access until balance is non negative
Account sharing across many devicesConcurrent device limit, device fingerprintingFlag high distinct device count per token
Timezone and clock manipulationServer clock is the only clock for access decisionsSystemClock.elapsedRealtime() for offline grace
Ban evasion via new accountStore device and account identifiers of banned usersApply restrictions on first matching signal
Double entitlement after upgrade or resubscribeRevoke the linkedPurchaseToken entitlement once the new purchase is completedAlert when the linked token belongs to another user

Common Pitfalls

  • Acknowledging from the client. If the client acknowledges before your server grants entitlement, a failure leaves the user charged with no access. Acknowledge on the server, after the grant.
  • Returning 200 on duplicate tokens without checking the original owner. You miss token sharing entirely.
  • Bundling premium assets in assets/ or res/. Any APK extractor pulls them out. Host premium content on your server and gate downloads on verified entitlement.
  • Waiting for a daily batch to revoke a voided purchase. Revoke as soon as the voidedPurchaseNotification or SUBSCRIPTION_REVOKED RTDN arrives, and apply graduated enforcement (warn, restrict, ban) to the account, not delayed revocation.
  • Using System.currentTimeMillis() for trial eligibility or offer windows. The device clock is user controlled.

References

Frequently asked questions

What does the Security AI skill do?

Use this skill when hardening a Google Play Billing integration against fraud. Covers server side receipt verification, replay attack protection, device fingerprinting, velocity checks, and the most common billing fraud patterns.

Why use Security on TypingMind?

Because you install it once and use it with any model. Security 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 Security in TypingMind?

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

Which AI models can use Security?

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 Security?

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

Is the Security 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 👇