Skip to content

In-app purchases from scratch: StoreKit 2, Play Billing and server-side validation

The store charges, your server unlocks. The full in-app purchase path on iOS and Android: StoreKit 2, Play Billing 9, receipt validation, server notifications and Google's 3-day acknowledge.

Ramon Gomes 16 min read Level: Intermediate

Also available in: Español, Français, Português

Charging inside an app looks simple until the first renewal fails. The "Subscribe" button is the easy part: the store handles the payment screen, the card and the tax. The real work is what happens next. Who makes sure the receipt is genuine? Who removes access when someone asks for a refund? And when the card gets declined next month, with the app closed?

This article walks the whole path, from the tap on the button to the unlocked feature, on both stores, with the APIsContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON. that apply today (checked on November 28, 2026). I'm building this path in Relatizo, a photo report app that will have a Pro plan sold through the stores, and the decisions here come from it.

The Path of a Purchase

Animated infographic in three panels: on the device, the Subscribe button opens the store's payment sheet; at the store, a signed receipt comes out (jwsRepresentation on iOS, purchaseToken on Android); on the server, the signature is checked, the database stores the Pro plan until Dec 28 and the app unlocks the feature and calls finish or acknowledge
The store charges. Your server unlocks.

Google's own docs describe the cycle in five steps, and it holds for both stores:

  1. Show what's for sale by fetching the products registered in the store (price and name come from there, already in the user's language and currency).
  2. Open the store's purchase flow.
  3. Verify the purchase on your server.
  4. Deliver what was bought.
  5. Close the purchase: acknowledge it or, if it's a consumable, consume it.
iOS (StoreKit 2) Android (Play Billing 9)
Fetch products Product.products(for:) queryProductDetailsAsync()
Buy product.purchase() launchBillingFlow()
Result PurchaseResult (.success, .pending, cancelled) onPurchasesUpdated()
Proof of purchase for the server jwsRepresentation (JWS signed by Apple) purchaseToken
Purchases made outside the app Transaction.updates queryPurchasesAsync() + notifications
Close transaction.finish() acknowledgePurchase() or consumeAsync()

The Three Product Types

Animated infographic with three product types: consumable, a bag of 100 coins that gets spent and bought again; non-consumable, a padlock that stays open after reinstalling the app; subscription, a calendar that renews month after month
Coins run out, lifetime features stay, subscriptions renew.
  • Consumable: coins, lives, AI credits. Use it, it's gone, buy again. On Android, consuming (consume) already closes the purchase and allows buying it again.
  • Non-consumable: a one-time purchase that lasts forever, like "remove ads" or "theme pack". It has to come back when the user reinstalls the app or switches devices.
  • Auto-renewable subscription: the monthly or yearly plan. Apple also has the non-renewing subscription (a season pass, for example), where you control when it expires.

In StoreKit 2 the types show up as consumable, nonConsumable, nonRenewable and autoRenewable. On Google Play, one-time products all look the same in the store: the app decides whether to consume or just acknowledge.

iOS: StoreKit 2 in a Few Lines

StoreKit 2 has been around since iOS 15 and uses async/await. The whole purchase fits in one block:

swift
let products = try await Product.products(for: ["app.relatizo.pro.mensal"])
guard let pro = products.first else { return }

switch try await pro.purchase() {
case .success(let result):
    // JWS signed by Apple: this is what goes to the server
    if case .verified(let transaction) = result {
        try await sendToServer(result.jwsRepresentation)
        await transaction.finish()
    }
case .pending:
    break // Ask to Buy or pending action: arrives later via Transaction.updates
default:
    break // the user cancelled
}

Three details that catch beginners:

  • Listen to Transaction.updates from app launch. Purchases approved later (Ask to Buy, where a parent approves a child's purchase), redeemed offer codes and purchases made on another device arrive there, not through purchase().
  • Transaction.currentEntitlements lists what the user is entitled to right now: every non-consumable and the latest transaction of each subscription that's active or in a grace period. Refunded items and consumables don't show up.
  • The "Restore purchases" button calls AppStore.sync(). The docs ask you to call it only in response to a tap, because it opens the App Store sign-in. In normal use you don't even need it: after a reinstall, the transactions are already there.

VerificationResult tells you whether StoreKit could validate the signature on the device itself. It's a good first barrier, but Apple recommends sending the JWS to the server "for more control and security".

Android: Play Billing Library 9

The current version is 9.1.0, from June 2026. Google gives each version two years: on November 28, 2026, v7 is already past even its extension deadline (November 1, 2026), so any update on Play needs at least v8, accepted until August 31, 2027.

kotlin
val client = BillingClient.newBuilder(context)
    .setListener { result, purchases -> handle(result, purchases) }
    .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())
    .enableAutoServiceReconnection()
    .build()

// after queryProductDetailsAsync()
val params = BillingFlowParams.newBuilder()
    .setProductDetailsParamsList(listOf(proDetails))
    .setObfuscatedAccountId(userHash) // ties the purchase to your account
    .build()
client.launchBillingFlow(activity, params)
  • Pending purchases are mandatory. In Brazil this really happens: people choose to pay cash at a physical store with a code, or a family member has to approve. Only unlock when the state moves from PENDING to PURCHASED.
  • setObfuscatedAccountId stores an identifier of yours (never the plain-text email) on the purchase. It comes back in the API and in the notifications, and it's how the server knows who owns that purchaseToken.
  • Switching plans creates a new token, with linkedPurchaseToken pointing to the old one. Invalidate the old one, or the same person counts twice.
A bakery cashier's hand holding a banknote up to the window light to check the watermark, with an old cash register and change on the counter
Nobody hands over the bread because the customer says the bill is real. The app's receipt gets checked too.

Why Verify on the Server

The app runs on the user's device, and the device can be tampered with. There are tools that intercept the store's response and fake a purchase that never happened. If the "Pro or not" decision lives only in the app, anyone who wants to cheat can.

With the server in the middle:

  • The receipt is checked against the store. On iOS, the server verifies the JWS signature with the App Store Server Library, official and available in Swift, Java, Python and Node (verifyAndDecodeTransaction). On Android, it calls purchases.subscriptionsv2.get (or purchases.products.get) with the purchaseToken.
  • The entitlement lives in one place. The row user 42 · pro · until Dec 28 in your database is the source of truth. The app asks the server, and the same account works on iPhone, Android and the web.
  • You see what happened outside the app: renewal, billing failure, refund.

If the server rejects a purchase on Android, don't call acknowledge: revoke and refund right away (subscriptionsv2.revoke or orders.refund with revoke=true).

Two traps for anyone migrating old code:

  • Apple's verifyReceipt is deprecated. The endpoint itself responds with the header deprecation: Mon, 5 Jun 2023. It still works, with no shutdown date announced, but it gets nothing new. The current path is the JWS and the App Store Server API, authenticated with a JWT signed by your in-app purchase key. The .p8 key can only be downloaded once: put it in your secrets vault right away.
  • Google's purchases.subscriptions.get (v1) is deprecated since May 2025 and shuts down on August 31, 2027. subscriptionsv2 no longer has paymentState: the state comes from subscriptionState (ACTIVE, IN_GRACE_PERIOD, ON_HOLD, PENDING...).

To look inside a JWS while developing, jwt.io decodes the header and payload. Just don't paste production receipts into third-party sites.

A Subscription Lives Far from the App

Animated infographic of a subscription's life with two notification lanes, App Store and Google Play: subscribed, renewed, card declined with a grace period and access kept, billing recovered or subscription expired, and a refund that revokes access; Apple sends the signed state, and Google notifies through Pub/Sub so the server queries the API
The app may be closed. The store tells your server.

Next month's renewal happens between the store and the user's bank. Your app never finds out unless the store tells your server. The two stores do it differently:

App Store Server Notifications V2 Google Play RTDN
How it arrives POST to your endpoint, with signedPayload (JWS) Cloud Pub/Sub message (push to a URL or pull)
What it carries The event type and the signed transaction Just the type and the token: you must call the API afterwards
Example events SUBSCRIBED, DID_RENEW, DID_FAIL_TO_RENEW, GRACE_PERIOD_EXPIRED, EXPIRED, REFUND, REVOKE PURCHASED, RENEWED, IN_GRACE_PERIOD, ON_HOLD, RECOVERED, CANCELED, EXPIRED, REVOKED
If your server fails Retries 5 times: 1, 12, 24, 48 and 72 hours later (none in sandbox) Pub/Sub keeps the message and redelivers it
Recovering what was missed Get Notification History (180 days) and Get All Subscription Statuses subscriptionsv2.get with the token

In practice, treat the notification as a "something changed" signal and always re-read the state at the source before touching the entitlement. It can arrive twice, out of order, or at the same time as the app reporting the same purchase. It's the same care as any webhook: reply fast with 200, process in a queue and store the ID so you don't apply the same event twice, as I show in the article on idempotency in APIs.

The grace period deserves attention: the card was declined, but the user keeps access while the store retries the charge. Cut access at that moment and you lose a subscriber who just switched cards.

A person seen from behind, wearing a backpack, tapping a card on a gym turnstile reader, with the green light on
The turnstile doesn't ask whether you paid in January. It asks whether your plan is active today.

Acknowledge: Google's 3-day Deadline

Animated infographic with two Google Play purchase lanes: in the first, the server verifies and calls acknowledge, and the purchase stays; in the second, without acknowledge, a clock runs for 3 days and the purchase is refunded automatically with access revoked
No acknowledge in 3 days, and Google refunds the money and removes access.

On Google Play, every purchase must be acknowledged within 3 days. If it isn't, Google refunds the user and revokes the entitlement on its own. It's a silent bug: the app works, the sale shows up, and days later the money is gone.

Acknowledge can be done by the app (acknowledgePurchase()) or by the server (Google Play Developer API). Prefer the server, right after verifying the purchase: that way it only happens for valid purchases, and an app closed halfway through doesn't leave the sale hanging. Consumables don't need a separate acknowledge, because consuming already acknowledges.

On iOS the equivalent is finish(). An unfinished transaction shows up again in Transaction.updates every time the app opens, but there's no automatic refund.

How to Test Without Spending Money

Apple Google
Environment Sandbox, with an App Store Connect test account License testers in Play Console
Without the store's server StoreKit Testing in Xcode (.storekit file) Play Billing Lab (app) to change country and state
A 1-month subscription lasts 5 minutes (configurable) 5 minutes
Renewals in testing up to 12 up to 6
Detail Ask to Buy in sandbox requires iOS 27.2 or later The app must be published on some track (internal testing works) for billing to turn on

Xcode also has Editor > Subscription Renewal Rate to renew every 30 seconds, plus an option to simulate an interrupted purchase. On Google, testers get test cards that always approve, always decline or take a few minutes, which is the easiest way to watch a grace period happen. To test your notification endpoint before you have a server, Webhook.site shows exactly what arrived.

One inconsistency worth knowing: in testing, a purchase without acknowledge is refunded within minutes, and Google's own page says 3 minutes in the text and 5 in the table. Don't count on either; acknowledge right away.

Your Own Server or a Third-party SDK

Your own server RevenueCat Adapty Qonversion
Cost infrastructure and your time free up to $2,500 monthly revenue; then 1% of the total free up to $5,000; then 1% free up to $7,000; then 0.8%
Validates and stores the entitlement you write it built in built in built in
Notifications from both stores you integrate built in, becomes a single webhook built in built in
Paywall and A/B tests you build included included included
Data stays with you them (exportable) them (exportable) them (exportable)

Note the RevenueCat detail: once you reach $2,500, it charges 1% on the total, not just on what's over the limit (their own page gives the example: $2,500 in revenue, $25 charged). Glassfy, which shows up in older lists, has shut down.

In React Native and Expo there's a middle ground: expo-iap (6.7) and react-native-iap (17.6), now maintained together under the OpenIAP project, give direct access to StoreKit and Play Billing with no middleman, and the same project offers a free hosted validation service with a usage limit. None of them run in Expo Go: real purchases need a development build. For choosing the app's technology itself, I compared the options in React Native vs Flutter.

Your own server, when:

  • you already have a backend with users and want the entitlement in the same database;
  • the subscription unlocks something on the server (storage, AI, API) and the server needs to decide on its own;
  • you don't want to pay a share of revenue in the long run.

A third-party SDK, when:

  • the app is small, just starting and fits in the free tier;
  • you want paywall, price testing and a metrics dashboard ready to go;
  • the team is one person and time is worth more than 1% of revenue.

For Relatizo I picked RevenueCat for launch: the app already has a server, but revenue starts at zero, and the time to write validation for both stores, notifications and edge cases is better spent on the product. If the percentage ever starts to hurt, its webhookHTTP call a system makes to your address when something happens, like an approved payment, notifying you right away instead of you polling for changes. writes the same entitlement to my database, so switching stays possible. The sales screen itself is the topic of the app paywall article.

Quick check

1. Where should the decision that a user is a Pro subscriber live?
Show answer

Answer: On your server, after verifying the receipt with the store

The app can be tampered with. The server checks the JWS or the purchaseToken and stores the entitlement.

2. What happens to a Google Play purchase without acknowledge?
Show answer

Answer: Within 3 days Google refunds it and revokes access

Acknowledge right after verifying on the server. Consuming a consumable already counts as acknowledging.

3. Does Google's RTDN notification carry the full subscription state?
Show answer

Answer: No, it signals that something changed and the server has to query the API

The docs themselves say you must call the Google Play Developer API after receiving the notification.

Frequently Asked Questions

Can I sell subscriptions in an app without a server?

You can: StoreKit 2 verifies the JWS on the device, and libraries like expo-iap work without a backend. The cost is having no source of truth outside the device, not knowing about renewals or refunds while the app is closed, and more exposure to fraud. To start without your own server, an SDK like RevenueCat fills that role.

What is Apple's JWS?

It's the transaction's proof of purchase in JSON Web Signature format: a JSON signed by Apple with its certificate chain. Any change breaks the signature. The same format comes from the device (jwsRepresentation), from the App Store Server API and from notifications, so the server verifies all of them the same way.

Does verifyReceipt still work?

It does, but it's deprecated: the endpoint responds with a deprecation header dated June 5, 2023, and Apple hasn't announced a shutdown date. New projects should use the JWS and the App Store Server API; old code can migrate with the App Store Server Library, which extracts the transaction ID from the old receipt.

Which Play Billing Library version should I use?

9.1.0 is the current one (June 2026). As of November 28, 2026, the minimum accepted to publish an update is v8, valid until August 31, 2027. Each version lives two years, so plan the upgrade once a year.

How does the grace period work?

When the renewal charge fails, the store can keep access for a few days while it retries. Apple signals it with DID_FAIL_TO_RENEW (subtype GRACE_PERIOD) and Google with IN_GRACE_PERIOD. Keep access on and show a prompt to update the payment method.

Is RevenueCat free?

It's free while tracked monthly revenue stays below $2,500. Above that it charges 1% of the month's total revenue. Adapty (free up to $5,000, then 1%) and Qonversion (up to $7,000, then 0.8%) have higher tiers.

Can I test purchases in Expo Go?

No. Both RevenueCat and expo-iap need a development build for real purchases; in Expo Go, RevenueCat runs in a preview mode that only simulates responses.

How much does the store keep from each sale?

If you earn up to $1 million a year, 15% on Apple (Small Business Program) and 15% on Google Play for the first million. Above that, 30% as the general rule. Subscriptions on Google Play are 15%.

References

Checked on November 28, 2026:

Source: https://ramongomessilva.com.br/blog/in-app-purchases-storekit-2-play-billing · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. In-app purchases from scratch: StoreKit 2, Play Billing and server-side validation. Ramon Gomes, 28 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/in-app-purchases-storekit-2-play-billing. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 28). In-app purchases from scratch: StoreKit 2, Play Billing and server-side validation. Ramon Gomes. https://ramongomessilva.com.br/blog/in-app-purchases-storekit-2-play-billing

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026inapppurchases,
  author = {Gomes, Ramon},
  title = {{In-app purchases from scratch: StoreKit 2, Play Billing and server-side validation}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-28},
  url = {https://ramongomessilva.com.br/blog/in-app-purchases-storekit-2-play-billing},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles