Kotlin Multiplatform In-App Purchases: A Shared Billing Migration Guide
Billing is usually the last layer a Kotlin Multiplatform team shares, because Android and iOS model a purchase in incompatible ways. Android gives you a long-lived BillingClient connection and an asynchronous PurchasesUpdatedListener; iOS gives you StoreKit transactions that must be verified and finished by hand. Behind both sit separate validation paths that must agree on what “subscribed” means. This guide walks through replacing those two purchase state machines with one commonMain integration, while keeping the customers who already paid through your native code.
Why billing resists code sharing
The two stores do not merely use different class names. They model the purchase lifecycle differently at every stage, so no type lines up cleanly.
On Android you own a connection: build a BillingClient, register a PurchasesUpdatedListener, connect, and handle reconnection when the service drops. The purchase result arrives on the listener rather than as a return value. After the buyer confirms, the work is not finished: you verify the purchase token against the Google Play Developer API, grant the entitlement, then acknowledge the purchase. Failing to acknowledge within three days lets Google Play refund the user and revoke the purchase.
On iOS there is no long-lived connection, but there is a verification step you cannot skip and a transaction you finish by hand. You call product.purchase(), switch on the result, validate the signed JWS, grant the entitlement, and call transaction.finish().
Reading current access is two unrelated APIs as well. Android queries owned purchases and you map tokens to entitlements yourself; iOS iterates Transaction.currentEntitlements and verifies each one. Neither SDK contains a field that says “this user has premium” — you compute it. And because each store validates its own receipt format against its own servers, your subscription logic ends up with a separate copy per platform, and those copies tend to fall out of sync over time.
What happens at the platform boundary
The shared API is not a black box. Native types are converted to KMP types at an explicit boundary you can inspect in the SDK’s mappings module, so nothing about the translation is concealed.
StoreProduct illustrates the contrast well, since Google’s ProductDetails and StoreKit’s product type share no common shape. The Android mapping wraps the native object and reads its Kotlin properties directly. The iOS mapping implements the same StoreProduct interface, but reaches the native value through Objective-C bridged method calls instead of properties.
Two design decisions make one interface work on both stores. First, access is wrapped.id on Android but wrapped.productIdentifier() on iOS, because the Android side wraps the native Android model while the iOS side wraps a StoreKit-backed value reached through Kotlin/Native interop. Second, fields that exist on only one platform get safe defaults on the other: subscriptionOptions is a Play Store concept, so it is null on iOS; discounts is an App Store concept, so it is emptyList() on Android. Your common code reads a single StoreProduct and never branches on the platform.
That translation layer is what the rest of this guide builds on: each step below swaps a native call for a call into the shared model.
Step 1: Add the SDK and drop the native billing dependencies
Add the SDK to your shared module’s commonMain source set. The core artifact carries the platform bindings inside it, so there is no separate androidMain dependency on Play Billing and no iOS pod. An optional Compose Multiplatform paywall component is available as a separate artifact.
If you are coming from the 2.x line, the iOS side changed in a way that matters here. In 2.x you pinned a PurchasesHybridCommon pod and kept its version in sync with the SDK. As of 3.0.0 the iOS native dependency is pulled through Gradle as a Swift Package Manager build of purchases-ios, so a consumer app has no Podfile, no PurchasesHybridCommon, and nothing to pin. The Kotlin framework your shared module produces already contains the SDK symbols. The same release raises the Android floor to API 23 (Android 6.0) because it ships on Play Billing Library 8.3.0, so set minSdk = 23 if you are lower.
Keep the native billing code in place for now. The plan is to route around it one step at a time, confirm the shared path behaves the same, and only then remove it.
Step 2: Replace two initializers with one
Native initialization splits into two distinct jobs. Android requires you to build and connect a BillingClient and track its connection state. iOS requires registering a StoreKit transaction observer early in the app lifecycle so updates are not missed. Neither has a shared form, so they live in androidMain and Swift respectively.
With the SDK, configuration is one call in commonMain that runs once at startup. The configure(apiKey) { } form is a small builder: inside the trailing lambda you can set appUserId, purchasesAreCompletedBy, and the other options on PurchasesConfiguration.Builder. The API key is the one value that differs per platform, so inject it with expect/actual or a tool like BuildKonfig, using your Android key on the Android target and your iOS key on the iOS targets.
Two pieces of lifecycle management disappear. You no longer open or reconnect a connection, because the SDK manages the BillingClient lifecycle on Android and the StoreKit transaction listener on iOS. You also no longer thread a Context through on Android, since the SDK captures the Application through an androidx.startup initializer. On iOS, your Swift code imports nothing from the SDK. The same configure call covers both platforms.
Step 3: Replace product loading
Loading products natively means describing each product to the store SDK and parsing back a platform-specific response. On Android, you build a QueryProductDetailsParams, set a product type, and parse the QueryProductDetailsResult that the Play Billing 8 callback returns, reading subscriptionOfferDetails and pricing phases off each ProductDetails. On iOS, you call Product.products(for:) with a set of identifiers. The two responses share no type.
The shared replacement reads the offering you configured in the dashboard. Offerings.current is the offering marked as current in the dashboard. Offering exposes named accessors for common cadences such as monthly, annual, and lifetime, plus availablePackages if you build a custom plan picker. Because the product list comes from the dashboard, you can change which products an app version sells without shipping a build, and the prices arrive already localized for the user’s storefront.
If you are not using offerings yet and want a direct lookup that mirrors your old queryProductDetailsAsync call, awaitGetProducts(productIds) takes a list of identifiers and returns List<StoreProduct>. Both methods are suspend functions, so they replace the listener and async callback with a straight-line call.
Decision checklist — offerings vs direct lookup:
- Use awaitOfferings when you want dashboard-controlled product selection, localized prices, and named cadences.
- Use awaitGetProducts when you are mirroring an existing identifier-based query and have not adopted offerings yet.
- Do not hardcode product lists in the app if you want to change what an app version sells without a release.
Step 4: Replace the purchase flow
This step removes the most code. Natively, a purchase is a multi-stage process you orchestrate by hand. On Android, you build BillingFlowParams, call launchBillingFlow, wait for the result on onPurchasesUpdated, check PurchaseState, verify the token on your server, grant the entitlement, and acknowledge within three days. On iOS you call product.purchase(), switch on the result, verify the signed transaction, grant the entitlement, and call transaction.finish().
The shared replacement is one suspend call. awaitPurchase opens the native purchase dialog, validates the receipt on the backend, finishes the transaction on the store, and returns a SuccessfulPurchase. Read the result through its properties, purchase.storeTransaction and purchase.customerInfo, since it is a plain class rather than a destructurable data class. By the time the call resumes, the receipt is validated and the user’s CustomerInfo already reflects the new entitlement, so anything bound to your customer info state updates on its own.
The SDK now takes over two behaviors your native flow handled. Acknowledgement and finishing occur inside the SDK, so the three-day Google Play refund window is closed by default. A cancellation comes back as a PurchasesTransactionException with userCancelled set to true, letting one catch block separate a buyer who backed out from a real failure.
Failure distinction — what each outcome means:
- userCancelled = true: the buyer dismissed the dialog. Treat as a no-op, not an error.
- userCancelled = false: surface e.error and decide whether to retry or show a message.
- Pending purchase (for example a deferred cash payment): it resolves to an active entitlement later; do not treat the initial pending state as a failure.
One nuance matters if you sell consumables. Play Billing Library 8 removed the ability to query already-consumed one-time products, the APIs the SDK previously relied on to restore them, so a consumable that was consumed cannot be reconstructed on the client. Grant those entitlements server-side, through your backend or a grant API, rather than relying on a client restore. Subscriptions and non-consumable products are not affected.
Step 5: Replace entitlement checks
Natively, “is this user subscribed” is a computation. On Android you call queryPurchasesAsync, walk the returned purchases, and map each token to one of your entitlements. On iOS you iterate Transaction.currentEntitlements, verify each transaction, and map product identifiers to entitlements. Both produce your own boolean.
The shared form is a property read. CustomerInfo.entitlements is an EntitlementInfos wrapper, and its indexing operator returns a nullable EntitlementInfo, which is why the null-safe ?.isActive == true is the correct check. The "premium" key is the entitlement identifier you set up in the dashboard, not a product id.
When you need more than a boolean, EntitlementInfo carries the fields you previously reconstructed yourself:
- isActive: the only field most access decisions need.
- willRenew: whether the subscription is set to renew, which you cannot reliably derive from a purchase token.
- store: where the entitlement was unlocked, such as PLAY_STORE or APP_STORE.
- periodType: distinguishes a TRIAL or INTRO period from a NORMAL one.
- expirationDate: the entitlement’s expiry, or null for lifetime access.
The entitlement reads as active whether the subscription came through Google Play, the App Store, or a promotional grant issued by your support team. That is what allows you to remove the per-store mapping code on both platforms.
Step 6: Bring your existing purchasers with you
A migration is not a fresh install. Your existing customers already paid through the old native code, and the shared backend has no record of those purchases yet. Leave this step out and a migration can quietly lock out paying users, so plan it as part of the cutover rather than a follow-up.
For users whose purchases live on the store account, call syncPurchases once after configuring. Its KDoc spells out the intent: it sends all the purchases to the backend and should be called when migrating existing users or in observer mode. The call uploads the store receipts already present on the device, and the backend rebuilds the customer’s entitlement state from them. Treat it as a migration and observer-mode tool, not a routine call on every launch.
To lower the risk of the cutover, start the SDK in observer mode by setting purchasesAreCompletedBy to MyApp. Your existing billing code continues to complete purchases while the shared layer watches and assembles its own view of your customers, so you can check its entitlement data against your current source of truth before switching over.
The same configuration carries a trade-off: with purchasesAreCompletedBy set to MyApp on Android, acknowledging purchases remains your job, and missing the three-day window lets Google Play refund the user and revoke the purchase. Observer mode is a staging step toward letting the shared layer complete purchases, not a permanent setup.
Cutover sequence:
- Configure in observer mode and keep native billing completing purchases.
- Compare observed entitlement data against your current source of truth.
- Call syncPurchases once for users whose purchases live on the store account.
- Flip to shared purchase completion and re-verify the parity checklist.
Step 7: Keep user identity stable
Identity is the last piece to get right, and it is the second common way a migration loses entitlements. If appUserId stays null, the SDK creates an anonymous identity and keeps it on the device. Once your own account system can associate a purchase with a person, call logIn with that identifier so entitlements remain attached to the user through device changes and reinstalls. The call returns a SuccessfulLogin containing the merged customerInfo and a created flag. The backend keeps a link between the anonymous identity and the identified one, which is how purchases recorded before login end up on the account. Calling awaitLogOut removes the stored identifier and leaves the app on a new anonymous user. Restore and login serve different purposes. awaitRestore sends the purchases held by the current store account to the current user, and it is the right call behind Apple's required restore control. That control must be visible whether or not you run your own accounts, so it stays even when logIn already handles continuity. Where you do have accounts, continuity does not depend on restore: passing the same appUserID the customer used at first purchase is what reconnects them. In practice, use logIn for account-based continuity and keep restore for recovery through the store account.
Verify parity before you delete anything
Do not remove the native implementation until the shared path has been shown to behave the same way. Work through the following checks with a sandbox account on Android and iOS before deleting any BillingClient or StoreKit code. - awaitOfferings returns the expected products on both platforms, with prices localized for each storefront. - A full purchase through awaitPurchase activates the entitlement, and it does so without the old acknowledgement or finish routines being invoked. - Plan changes on Android, both upgrades and downgrades, succeed with the correct oldProductId and replacement mode; this is the area most prone to breaking once the native BillingFlowParams code is gone. - A pending purchase, such as a deferred cash payment, eventually becomes an active entitlement, which is the same outcome the native enablePendingPurchases handling produced. - A buyer who cancels produces a PurchasesTransactionException with userCancelled set to true rather than an error. - Trial and introductory periods display correctly from periodType, keeping in mind that eligibility checks themselves exist only on iOS. - Customers who bought before the migration can see their entitlements after syncPurchases or restore, and this holds after a reinstall. - Identity linking works: a purchase made while anonymous shows up on the account once logIn is called. When all of these pass, remove the BillingClient setup, the PurchasesUpdatedListener, the acknowledgement logic, the StoreKit purchase and verification code, and the com.android.billingclient:billing dependency. If observer mode was part of your rollout, you can also shut down the receipt validation server components that the shared backend now handles, or leave them running alongside until you are satisfied.
What still needs platform awareness
The shared model covers the common path, but a few capabilities remain tied to one store. It is better to know which than to assume the abstraction hides everything:
- Introductory and trial eligibility are iOS-specific. awaitTrialOrIntroPriceEligibility returns a real status on iOS and UNKNOWN on Android, where Google computes eligibility itself.
- Win-back offers require iOS 18 and StoreKit 2, and the related calls throw on other configurations.
- Personalized price and replacement mode for upgrades are Play Store-only parameters on awaitPurchase, ignored on iOS.
- Amazon Appstore support is opt-in through a separate purchases-store-amazon dependency on the Android source set.
These stay as small, well-marked branches in otherwise shared code, rather than the two full billing implementations you started with.
Conclusion
Migrating to a shared in-app purchases layer is mostly subtraction. You replace two initializers with one configure, two product queries with awaitOfferings, two purchase pipelines with awaitPurchase, and two entitlement computations with one entitlements["premium"].isActive check, then bring your existing customers across with syncPurchases and logIn before deleting the native code. What remains is one purchase flow to reason about instead of two.
| Native Android / iOS | Shared commonMain call |
|---|---|
| BillingClient.startConnection / StoreKit listener setup | Purchases.configure(apiKey) { } |
| queryProductDetailsAsync / Product.products(for:) | awaitOfferings() or awaitGetProducts(ids) |
| launchBillingFlow + onPurchasesUpdated / product.purchase() | awaitPurchase(package) |
| acknowledge / transaction.finish() | handled by the SDK |
| server side receipt validation | handled by the shared backend |
| queryPurchasesAsync / Transaction.currentEntitlements | awaitCustomerInfo() |
| restore button / AppStore.sync() | awaitRestore() |
| importing existing purchasers | awaitSyncPurchases() |
Correspondence table from the original guide; verify current SDK method names and behavior against the version you install.
Frequently asked questions
How do I tell a cancelled purchase apart from a real error?
awaitPurchase throws a PurchasesTransactionException. Check its userCancelled flag: true means the buyer dismissed the dialog and you should treat it as a no-op; false means surface e.error. A pending purchase is a separate case — it resolves to an active entitlement later and should not be treated as a failure.
Can I still restore consumable purchases on the client?
No. Play Billing Library 8 removed the ability to query already-consumed one-time products, the APIs the SDK previously relied on to restore them, so a consumable that was consumed cannot be reconstructed on the client. Grant those entitlements server-side, through your backend or a grant API. Subscriptions and non-consumable products are not affected.
Do I still need a restore button if I have my own account system?
Yes. Apple mandates a visible restore control regardless of whether you have your own account system. Use awaitRestore for store-account-based recovery, and rely on logIn for account-based continuity — restoration is simply your app passing the same appUserID the customer used when they first purchased.
Is observer mode a safe permanent configuration?
No. Treat observer mode as a temporary bridge, not a destination. If purchasesAreCompletedBy is set to MyApp on Android, your app still has to acknowledge each purchase; when acknowledgement does not happen within three days, Google Play refunds the buyer and cancels the purchase. The point of running this way is to compare the observed entitlement data with your existing source of truth before you hand purchase completion over to the shared integration.
How do I supply the API key across platforms?
The API key is the one value that differs per platform. Inject it with expect/actual or a tool like BuildKonfig, using your Android key on the Android target and your iOS key on the iOS targets. The configure call itself lives in commonMain.