Unity IAP 5 Setup Guide: In-App Purchases in C#
Implementing in-app purchases in a mobile game requires more than opening a native payment sheet. A production store integration must fetch localized pricing, survive app crashes mid-transaction, verify purchase authenticity before granting rewards, restore non-consumable entitlements across devices, and synchronize cleanly with your ad monetization and economy systems.
With the release of Unity In-App Purchasing (IAP) 5 (com.unity.purchasing v5.x), Unity replaced the legacy IStoreListener and ConfigurationBuilder workflow with an asynchronous, event-driven StoreController architecture. In this guide, you will learn how to set up Unity IAP 5 in C# for Android and iOS—covering consumables (100 Gems), non-consumables (Remove Ads), auto-renewable subscriptions (Monthly VIP), server-side receipt verification, purchase confirmation, restoration, and troubleshooting.
How Does Unity IAP Work? (Under the Hood Architecture)
At an architectural level, Unity In-App Purchasing (IAP) functions as an abstraction layer between your C# gameplay code and the native platform billing systems—specifically Google Play Billing on Android and Apple StoreKit on iOS.
Instead of writing platform-specific Java/Kotlin or Objective-C/Swift bridge code, Unity IAP coordinates the 5-stage purchase lifecycle:
- Catalog Definition & Localized Price Fetching: Your game connects to the platform store (
Connect()) and queries active product SKUs (FetchProducts()). The store returns localized currency codes and formatted price strings (e.g.\$0.99,€1.09,¥150). - Purchase Initiation: When the player taps a buy button, the C# client calls
storeController.PurchaseProduct(), passing the unique product identifier. - Native OS Payment Sheet: Unity IAP instructs the underlying OS subsystem to present Apple's FaceID/TouchID prompt or Google Play's 1-Tap bottom sheet. The app store processes credit card or wallet billing independently of your game code.
- Pending Transaction & Receipt Delivery: Once the transaction completes, the store delivers an encrypted receipt and unique transaction ID to Unity, firing
OnPurchasePending(PendingOrder). - Fulfillment & Confirmation: Your C# client (or your backend server) validates the receipt signature, unlocks the digital goods in the player's account, and explicitly calls
storeController.ConfirmPurchase(pendingOrder)to close the transaction with the store and prevent automatic chargebacks.
Important Unity IAP 5 Update
2026 Version Notice — Unity IAP 5 Architecture: This tutorial targets Unity IAP 5 (
com.unity.purchasingv5.0+). Unity IAP 5 introduces a major architectural redesign compared to Unity IAP 4.x. Code written for older IAP 4 tutorials usingIDetailedStoreListener,ConfigurationBuilder, andProcessPurchase(PurchaseEventArgs)cannot be copied directly into a Unity IAP 5 project without migration.
Key Architectural Changes: Unity IAP 4 vs. Unity IAP 5
| Lifecycle Step | Legacy Unity IAP 4.x (Old) | Modern Unity IAP 5.x (New) |
|---|---|---|
| Controller Access | IStoreController & IExtensionProvider supplied via OnInitialized | StoreController obtained directly via UnityIAPServices.StoreController() |
| Callback Model | Monolithic IDetailedStoreListener interface | Granular C# Action events on StoreController |
| Store Startup | ConfigurationBuilder + UnityPurchasing.Initialize(this, builder) | await storeController.Connect() followed by storeController.FetchProducts(...) |
| Fetching Existing Purchases | Implicit during Initialize() | Explicit storeController.FetchPurchases() -> OnPurchasesFetched(Orders) |
| Processing New Purchases | Synchronous ProcessPurchase(PurchaseEventArgs) returning PurchaseProcessingResult | Event-driven OnPurchasePending(PendingOrder) |
| Finalizing / Confirming | Return PurchaseProcessingResult.Complete or call ConfirmPendingPurchase(Product) | Call storeController.ConfirmPurchase(PendingOrder) -> OnPurchaseConfirmed(Order) |
| Restoring Transactions | extensions.GetExtension<IAppleExtensions>().RestoreTransactions(...) | Built directly into storeController.RestoreTransactions(...) |
| Receipt & Transaction Data | product.receipt and product.transactionID | order.Info.Receipt (Android), order.Info.Apple.jwsRepresentation (iOS StoreKit 2), and order.Info.TransactionID |
Official migration reference: Upgrade to Unity IAP v5 Documentation
Quick Start
By following this guide, you will build a complete Unity IAP 5 integration covering:
- Store Connection & Product Fetching: Connecting to Google Play Billing and Apple StoreKit via
UnityIAPServices.StoreController(), registering C# lifecycle events before connecting, and fetching product metadata (FetchProducts). - Three Core Product Types: Configuring a repeatable Consumable (
com.yourstudio.game.gems100), a permanent Non-Consumable (com.yourstudio.game.removeads), and a recurring Subscription (com.yourstudio.game.vipmonthly). - Secure Transaction Verification: Validating Google Play purchase tokens and Apple StoreKit 2 signed JWS transactions on a backend server before granting content.
- Idempotent Fulfillment & Confirmation: Recording transaction IDs to prevent duplicate rewards, persisting player entitlements, and acknowledging orders with
ConfirmPurchase(PendingOrder). - Cross-Device Restoration & Testing: Restoring purchases with
FetchPurchases()andRestoreTransactions(), and testing every edge case in Google Play and App Store sandboxes.
Table of Contents
- What Is Unity IAP?
- Unity IAP 4 vs IAP 5
- Requirements and Installation
- Configuring Products in App Store Connect and Google Play
- Initializing Unity IAP 5
- Complete C# StoreController Example
- Purchasing Consumables
- Implementing Remove Ads
- Handling Subscriptions
- Secure Transaction Verification
- Confirming Purchases and Preventing Duplicates
- Restoring Purchases
- Testing on Android and iOS
- Troubleshooting Common Errors
- Frequently Asked Questions
- Final Checklist and Next Steps
1. What Is Unity IAP?
Unity In-App Purchasing (com.unity.purchasing) is Unity's official cross-platform billing abstraction package. Instead of writing separate Java/Kotlin wrappers for Google Play Billing Library and Objective-C/Swift wrappers for Apple StoreKit, you interact with a unified C# API in the UnityEngine.Purchasing namespace.
Product Categories Supported by Unity IAP
| ProductType Enum | Ownership Lifecycle | Example in a Mobile Game |
|---|---|---|
ProductType.Consumable | Purchased, fulfilled, and consumed so the player can buy it again. | 100 Gems pack in an RPG, energy refills, or extra revive tokens. |
ProductType.NonConsumable | Purchased once per store account and permanently owned across reinstalls. | Remove Ads upgrade in an idle game, permanent character unlock, or expansion pack. |
ProductType.Subscription | Auto-renewing recurring access managed by the user's app store account. | Monthly VIP Pass granting daily bonus gems and exclusive dungeon access while active. |
Note on App Store Fees and Policies: App store commission rates, small-business program tiers, regional alternative billing rules, and subscription terms depend on your developer program enrollment, user region, product category, and current store policies. Always review the official Apple App Store Small Business Program / Commission documentation and Google Play service fee documentation rather than assuming a single universal fee schedule.
2. Unity IAP 4 vs IAP 5
Understanding why Unity IAP 5 changed its architecture helps you avoid subtle bugs when building your store manager:
- Decoupled Steps (
Connect→FetchProducts→FetchPurchases): In IAP 4, a singleUnityPurchasing.Initialize()call connected to the store, queried product metadata, and triggeredProcessPurchasefor pending items all at once. In IAP 5, you explicitly control when to connect (await storeController.Connect()), when to fetch your product definitions (FetchProducts), and when to query existing purchases (FetchPurchases). - Explicit
OrderHierarchy: Instead of passing a genericProductwith a mutable.receiptproperty intoProcessPurchase, IAP 5 models transactions as strongly typedOrderobjects:PendingOrder: A newly authorized or unconfirmed purchase waiting for fulfillment andConfirmPurchase(pendingOrder).ConfirmedOrder: A finalized transaction returned inOnPurchaseConfirmedorOnPurchasesFetched.DeferredOrder: A transaction awaiting external payment completion (such as parental approval via Apple Ask to Buy or pending offline cash payment on Google Play).FailedOrder: ContainsFailureReason(PurchaseFailureReason) and native diagnosticDetails.
- Cart-Aware Order Payloads: Each
Orderexposesorder.CartOrdered.Items()andorder.Info(containingorder.Info.TransactionID,order.Info.Receipton Google Play,order.Info.Apple.jwsRepresentationon iOS StoreKit 2, andorder.Info.PurchasedProductInfo).
3. Requirements and Installation
Prerequisites
- Unity Editor: Unity 2022.3 LTS or Unity 6 (6000.x) with Android and/or iOS Build Support installed.
- Target Package Version: Unity In-App Purchasing v5.0+ (
com.unity.purchasing), compatible with current Google Play Billing Library and Apple StoreKit requirements. - Store Developer Accounts: An active Google Play Console account (with merchant payment profile configured) and/or Apple Developer Program account (with Paid Apps Agreement active in App Store Connect).
Installing com.unity.purchasing via Package Manager
- Open your Unity project and navigate to Window > Package Manager.
- Select Packages: Unity Registry from the top-left dropdown.
- Search for In-App Purchasing (
com.unity.purchasing). - Select version 5.0.0 or the latest stable 5.x release and click Install (or Update).
- If your project uses Unity Gaming Services (UGS), ensure
com.unity.services.coreis also installed so you can initializeUnityServices.InitializeAsync()before connecting the store if needed by your UGS setup.
4. Configuring Products in App Store Connect and Google Play
Before Unity IAP 5 can fetch product metadata on a device, your products must exist and be active in the respective store consoles:
1. Define Consistent Product IDs
In this tutorial, we use three placeholder Product IDs:
- Consumable (100 Gems):
com.yourstudio.game.gems100 - Non-Consumable (Remove Ads):
com.yourstudio.game.removeads - Subscription (Monthly VIP):
com.yourstudio.game.vipmonthly
2. Google Play Console Setup
- Upload at least one signed
.aab(Android App Bundle) that includes thecom.unity.purchasingbilling permission (com.android.vending.BILLING) to an Internal Testing or Closed Testing track. - Navigate to Monetize with Play > Products > In-app products to create
com.yourstudio.game.gems100andcom.yourstudio.game.removeads, and set their status to Active. - Navigate to Monetize with Play > Products > Subscriptions to create
com.yourstudio.game.vipmonthly, configure a base plan, and activate it.
3. App Store Connect Setup
- Confirm your Paid Apps Agreement, tax forms, and banking details are active under Business in App Store Connect (iOS sandbox product queries return empty lists if agreements are unsigned).
- Under your app record, open Monetization > In-App Purchases and create
com.yourstudio.game.gems100(Consumable) andcom.yourstudio.game.removeads(Non-Consumable). - Open Monetization > Subscriptions, create a Subscription Group, and add
com.yourstudio.game.vipmonthly.
4. Mapping Store-Specific Product IDs (When Store IDs Differ)
Ideally, use the exact same product ID string on both Google Play and App Store Connect. If an existing live game uses different IDs per store, use Unity IAP 5's CatalogProvider and StoreSpecificIds to map a single cross-platform catalog ID to each store's native ID:
5. Initializing Unity IAP 5
Initialization in Unity IAP 5 follows a strict sequence so no events are missed:
- Obtain
StoreController: CallUnityIAPServices.StoreController(). - Subscribe to Events Before Connecting: Register your handlers for
OnStoreDisconnected,OnProductsFetched,OnProductsFetchFailed,OnPurchasesFetched,OnPurchasesFetchFailed,OnPurchasePending,OnPurchaseConfirmed,OnPurchaseFailed, andOnCheckEntitlement.Important: You must subscribe to both
OnPurchaseConfirmedandOnPurchaseFailedwhenever your code callsConfirmPurchase(pendingOrder). Unity IAP 5 enforces this so asynchronous confirmation failures are never silently ignored. - Connect Asynchronously: Call
await storeController.Connect(). - Fetch Products: Pass your
List<ProductDefinition>tostoreController.FetchProducts(definitions). - Fetch Existing Purchases: Inside
OnProductsFetched(List<Product> products), callstoreController.FetchPurchases()to synchronize existing non-consumables, active subscriptions, and any unconfirmed pending orders from a prior session.
Official reference: Manage Purchases in Unity IAP v5 Documentation
6. Complete C# StoreController Example
Below is a complete, modular C# implementation (UnityIAP5Manager.cs) built for Unity IAP 5 (com.unity.purchasing v5.0+). It demonstrates:
- Asynchronous store connection with duplicate-init guards
- Fetching catalog metadata and localized store price strings
- Initiating purchases with duplicate-click protection
- Handling
OnPurchasePending,OnPurchasesFetched,OnPurchaseConfirmed, andOnPurchaseFailed - A pluggable asynchronous verification hook (
VerifyOrderWithBackendAsync) that never auto-approves unverified receipts in production - Idempotent fulfillment and
ConfirmPurchase(PendingOrder)handling - Proper event unsubscription in
OnDestroy()
Verification Note: This script is written against the official Unity IAP 5 (
com.unity.purchasingv5.x) API specification (UnityEngine.Purchasing). It has not been compiled inside a Unity Editor project in this web repository environment—verify method signatures against your installed minor 5.x package version and connect your backend verification endpoint before shipping.
7. Purchasing Consumables
A Consumable product—such as com.yourstudio.game.gems100 (100 Gems in an RPG)—can be purchased repeatedly. Because the store clears its pending record as soon as your client calls storeController.ConfirmPurchase(pendingOrder), safe consumable fulfillment requires strict ordering:
- Receive
OnPurchasePending(PendingOrder): ExtractpendingOrder.Info.TransactionIDalong withpendingOrder.Info.Receipt(on Google Play) orpendingOrder.Info.Apple.jwsRepresentation(on iOS StoreKit 2). - Validate the Transaction: Send the verification payload and transaction ID to your backend verification endpoint.
- Check Idempotency by Transaction ID: Before adding 100 Gems, check whether
transactionIdalready exists in your fulfilled transactions ledger. If the app crashed after granting the gems yesterday but beforeConfirmPurchase()finished,OnPurchasePendingwill fire again on the next launch with the sameTransactionID. Checking the ledger prevents granting 200 Gems for a single payment. - Grant and Persist: Credit the 100 Gems and flush the save state to disk (or commit the database transaction on your server).
- Call
ConfirmPurchase(pendingOrder): Acknowledge and consume the order with the store only after step 4 completes.
Important Note on
PlayerPrefs: InUnityIAP5Manager.cs,PlayerPrefsis used strictly to illustrate local demonstration state. On rooted Android devices or unencrypted local backups,PlayerPrefsXML/plist files can be edited by users. Production games should store currency balances and transaction ledgers on a backend server or in an authenticated, encrypted local storage layer.
8. Implementing Remove Ads
In casual and idle mobile games, a Remove Ads upgrade (com.yourstudio.game.removeads, configured as ProductType.NonConsumable) is one of the highest-converting store items. It permanently disables forced banner and interstitial ads while allowing players to continue watching voluntary rewarded video ads for bonus multipliers.
Connecting Remove Ads to Your Ad Manager
Do not rely on a permanent PlayerPrefs flag as the sole source of truth for Remove Ads, and do not stop at calling DestroyBannerAd() once. If your ad manager only destroys the currently visible banner without guarding future load and display calls, the next scene transition or level-complete trigger will load and display another banner or interstitial ad.
Instead:
- Query and verify ownership on startup via
storeController.FetchPurchases()andstoreController.CheckEntitlement(removeAdsProduct). - Subscribe your ad bridge to
OnRemoveAdsEntitlementChangedand pass the verified entitlement state to your ad manager (such as Unity LevelPlay or standalone Unity Ads):
- Inside your ad manager (
LevelPlayAdManager), maintain anareAdsRemovedflag that immediately tears down active banner/interstitial instances when enabled and guards all futureLoadBannerAd(),ShowBannerAd(),LoadInterstitialAd(), andShowInterstitialAd()operations:
9. Handling Subscriptions
Auto-renewable subscriptions (com.yourstudio.game.vipmonthly, configured as ProductType.Subscription) grant time-limited benefits—such as a daily gem stipend or an idle offline-earnings boost—for as long as the player's billing cycle remains active.
Critical Rules for Subscription Entitlements
- Never Set a Permanent Boolean in
PlayerPrefs: A common mistake in legacy tutorials is writingPlayerPrefs.SetInt("VIPActive", 1)when a subscription is purchased and never revoking it. If the user cancels their subscription or their card expires next month, a permanent local boolean will grant VIP access forever for free. - Evaluate Current Entitlement on Every Session:
- When
OnProductsFetchedcompletes, callstoreController.FetchPurchases()andstoreController.CheckEntitlement(vipProduct). - In
HandleCheckEntitlement(Entitlement entitlement), check whetherentitlement.Status == EntitlementStatus.FullyEntitled. If the subscription has expired (EntitlementStatus.NotEntitled), revoke the in-game VIP perks.
- When
- Handle Renewals, Grace Periods, and Cancellations on Your Backend: For cross-platform accounts or server-authoritative VIP rewards, configure Google Play Real-Time Developer Notifications (RTDN) and Apple App Store Server Notifications V2 on your backend so subscription renewals, billing retry grace periods, and expirations update the player's server profile automatically.
10. Secure Transaction Verification
A client-side helper that merely checks !string.IsNullOrEmpty(receiptPayload) and returns true is not receipt verification. Local memory and C# return values on a client device can be tampered with using memory editors or modified APK packages.
To protect your game economy, verify transactions cryptographically on a backend server (such as a Firebase Cloud Function, AWS Lambda, Unity Cloud Code, or custom Node.js/.NET backend) before granting entitlements.
1. Google Play Verification (Android)
When a purchase completes on Google Play:
pendingOrder.Info.Receiptcontains a JSON wrapper withStore("GooglePlay"),TransactionID, and aPayloadcontaining the signed purchase JSON andpurchaseToken.- Your Unity client sends the
productIdandpurchaseTokenover HTTPS to your backend verification endpoint. - Your backend authenticates with a Google Cloud Service Account and queries the Google Play Developer API:
- For consumables and non-consumables:
purchases.products.get - For subscriptions:
purchases.subscriptionsv2.get
- For consumables and non-consumables:
- The backend verifies that
purchaseStateis purchased (0), confirms thepurchaseTokenhas not already been redeemed by another user ID in your database, credits the user's account, and returns a signed success response to the Unity client.
2. Apple App Store Verification (iOS)
Modern Apple in-app purchases use StoreKit 2 and the App Store Server API:
- Avoid Apple's Deprecated
verifyReceiptEndpoint: Apple deprecated the legacybuy.itunes.apple.com/verifyReceiptendpoint. Do not build new verification services aroundverifyReceipt. - Use StoreKit 2 JWS (
Order.Info.Apple.jwsRepresentation) & App Store Server API: StoreKit 2 transactions are cryptographically signed by Apple using JWS (JSON Web Signature). In Unity IAP 5, your client extracts the signed JWS string fromorder.Info.Apple.jwsRepresentationand sends it to your backend server. Your backend (or Apple's App Store Server APIGet Transaction Info/Get All Subscription Statusesendpoints authenticated with your App Store Connect API key) verifies the JWS signature chain against Apple's root certificates using Apple's official App Store Server Library, checks thatbundleId,productId, andenvironment(Sandboxvs.Production) match, and confirms thetransactionIdhas not been replayed.
3. Conceptual Unity Client ↔ Backend Verification Contract
Below is an example of the JSON payload your Unity client sends to your backend verification endpoint and the structured response it expects back:
If your backend returns HTTP 400 / "verified": false, the client logs the rejection and refuses to grant the item. If the request fails due to a transient 503 or offline network timeout, the client leaves the PendingOrder unconfirmed so Unity IAP 5 redelivers it on the next session.
11. Confirming Purchases and Preventing Duplicates
Why Unconfirmed Orders Are Redelivered or Refunded
In Unity IAP 5, payment authorization and order confirmation are separated:
- If a player pays for
100 Gemsand the game crashes beforestoreController.ConfirmPurchase(pendingOrder)is called, the transaction remains in the pending state. - On the next app launch, calling
storeController.FetchPurchases()will re-emit the unconfirmed order throughOnPurchasePending. - Furthermore, on Google Play, any purchase that is not acknowledged/confirmed within 3 days is automatically refunded and revoked by Google Play. Calling
ConfirmPurchase(pendingOrder)promptly after fulfillment acknowledges the purchase with the store so the revenue is captured.
Designing Idempotent Fulfillment
Because network drops, app restarts, or store resynchronizations can cause OnPurchasePending or OnPurchasesFetched to deliver the same transaction more than once:
- Key every consumable grant by
pendingOrder.Info.TransactionID(and on Android, thepurchaseToken). - If the transaction ID is already marked as fulfilled in your database, do not grant the currency a second time, but do call
storeController.ConfirmPurchase(pendingOrder)so the store clears the pending queue. - If
ConfirmPurchase(pendingOrder)fails asynchronously and triggersOnPurchaseConfirmedwith aFailedOrder, never pass thatFailedOrderback intoConfirmPurchase. Retain the originalPendingOrderreference (as shown inunconfirmedPendingOrdersinUnityIAP5Manager.cs) if you need to retry confirmation when connectivity returns.
12. Restoring Purchases
Players who buy a non-consumable (Remove Ads) or an active subscription (Monthly VIP) expect their entitlements to carry over when they buy a new phone or reinstall the game.
How Restoration Works on Android vs. iOS
- Google Play (Android): Calling
storeController.FetchPurchases()afterOnProductsFetchedautomatically queries Google Play Billing for all non-consumed purchases and active subscriptions associated with the user's Google account and delivers them toOnPurchasesFetched(Orders). - Apple App Store (iOS): Apple App Store Review Guidelines require any iOS app selling non-consumables or auto-renewable subscriptions to include a visible, user-accessible "Restore Purchases" button in the UI (typically in the Settings menu or Shop screen).
Using StoreController.RestoreTransactions in Unity IAP 5
In Unity IAP 5, you no longer need IExtensionProvider or IAppleExtensions. Call RestoreTransactions directly on StoreController, and wait for the asynchronous FetchPurchases() (OnPurchasesFetched), CheckEntitlement (OnCheckEntitlement), and backend verification tasks to finish before invoking your UI completion callback:
Important Distinction: When
RestoreTransactions((bool success, string error) => ...)returnssuccess == true, it only indicates that the initial restore call with the store succeeded—not that asynchronous purchase fetching (OnPurchasesFetched), entitlement checks (OnCheckEntitlement), or backend verification have finished, nor that the user owned any historical purchases. As shown inUnityIAP5Manager.RestorePurchasesFromUIButton, always wait forOnPurchasesFetchedandOnCheckEntitlement(plus backend verification) to complete before inspecting entitlement state and updating your UI.
13. Testing on Android and iOS
Testing in-app purchases thoroughly requires testing both inside the Unity Editor and on physical devices connected to each store's sandbox environment.
1. Unity Editor Fake Store vs. Real Device Sandbox
- Unity IAP Fake Store (Editor): When running in Play Mode inside the Unity Editor, Unity IAP presents a simulated Fake Store dialog (
UIFakeStoreWindow) that lets you test UI button wiring and simulate success or failure responses. However, the Fake Store does not test real Google Play Billing configurations, Apple StoreKit JWS payloads, or store account permissions. - Google Play License Testing (Android):
- Upload a signed build to an Internal Testing track in Google Play Console.
- Add your testers' Gmail addresses under Setup > License testing in Google Play Console.
- Install the build on a physical Android device signed into that Gmail account. Google Play will display a "Test card, always approves" (or "Test card, always declines") payment instrument so you can test real billing flows without real money charges.
- Apple StoreKit & Sandbox Testing (iOS):
- In App Store Connect, go to Users and Access > Sandbox > Testers and create a Sandbox Apple Account.
- Build your Unity project to Xcode and deploy it to a physical iOS device (you can also use a local StoreKit Configuration file in Xcode for rapid iteration before testing against App Store Connect Sandbox).
- Trigger a purchase in the app and sign in with your Sandbox account when prompted by StoreKit.
2. Required Test Scenarios Before Release
Verify each of the following cases on real Android and iOS builds before launching:
- Successful Product Delivery: Purchase
100 Gemsand verify the balance increments once andOnPurchaseConfirmedfires. - Purchase Cancellation: Open the store payment sheet and tap Cancel/Back. Confirm
PurchaseFailureReason.UserCancelledis handled silently without showing an error modal, and the Buy button becomes clickable again. - Failed Payment: Select the "Test card, always declines" option on Android (or enable simulated billing failure in StoreKit) and verify the UI handles
OnPurchaseFailedcleanly. - Pending / Deferred Transactions: Test a slow/deferred payment instrument on Google Play or Apple Ask to Buy and confirm the item is not granted until
OnPurchasePendingfires after approval. - Crash Recovery & Duplicate Callback Handling: Comment out
storeController.ConfirmPurchase(pendingOrder)temporarily, complete a test purchase, force-close and relaunch the app, re-enableConfirmPurchase, and confirm your idempotency check prevents granting the reward twice. - Reinstall and Restore: Purchase
Remove Ads, uninstall and reinstall the app, and verify that automaticFetchPurchases()(and the Restore Purchases button on iOS) restores the ad-free state. - Subscription Renewal & Expiration: In sandbox environments, monthly subscriptions renew on an accelerated schedule (for example, every few minutes). Verify that your game grants VIP access while active and revokes it once the sandbox subscription expires.
14. Troubleshooting Common Errors
| Problem / Symptom | Possible Cause | Recommended Solution |
|---|---|---|
Store connection failure (OnStoreDisconnected fires) | Device is offline, Google Play Services is outdated/missing on the device, or Connect() was called on an unsupported platform. | Verify network connectivity, confirm the device has an active Google Play / App Store account signed in, and retry await storeController.Connect() when connectivity returns. |
Products not appearing (OnProductsFetched returns 0 items) | Product IDs are still in Draft/Inactive state, or App Store Connect Paid Apps Agreement / tax / banking forms are incomplete. | Activate all products in Google Play Console and App Store Connect, and verify that all legal, tax, and banking agreements show Active status. |
| Incorrect Product IDs | Mismatch between the string in new ProductDefinition(...) and the store console (e.g., uppercase vs. lowercase or missing bundle prefix). | Copy the exact case-sensitive Product IDs from Google Play Console and App Store Connect, or map platform differences with StoreSpecificIds. |
Product availableToPurchase is false | The product is restricted in the user's storefront country, or a subscription base plan has no regional price configured. | Enable regional pricing availability across all target countries in Google Play Console and App Store Connect. |
| Store sandbox configuration problems ("Item not available for purchase" on Android) | Sideloading an unsigned or local debug APK whose versionCode / signing key does not match the build uploaded to Google Play Internal Testing. | Sign your APK/AAB with your upload keystore, ensure the versionCode matches the uploaded track, and install via the Google Play Internal Testing opt-in link using a registered License Tester email. |
| Purchase cancelled triggers an error popup | Treating PurchaseFailureReason.UserCancelled the same as payment failures in OnPurchaseFailed. | Check if (failedOrder.FailureReason == PurchaseFailureReason.UserCancelled) and return early after unlocking the UI button. |
| Purchase remains pending (auto-refunded after 3 days on Android) | storeController.ConfirmPurchase(pendingOrder) was never called after granting the item, or backend verification timed out without retry. | Ensure ConfirmPurchase(pendingOrder) is called after every successful fulfillment, and call FetchPurchases() on startup to process any unconfirmed orders. |
| Duplicate purchase callbacks grant 2x currency | OnPurchasePending fired again after a crash or reconnect before confirmation completed, and fulfillment was not idempotent. | Record pendingOrder.Info.TransactionID in your persistent ledger before granting content, and skip re-granting if the transaction ID was already processed. |
Purchase confirmation failure (FailedOrder in OnPurchaseConfirmed) | Network dropped while ConfirmPurchase was communicating with the store, or a FailedOrder was mistakenly passed back into ConfirmPurchase. | Subscribe to OnPurchaseConfirmed and OnPurchaseFailed, inspect failedOrder.Details, and only pass the original PendingOrder when retrying confirmation. |
| Remove Ads not restored after reinstall | Relying solely on local PlayerPrefs instead of processing OnPurchasesFetched(Orders) and CheckEntitlement. | Call storeController.FetchPurchases() after OnProductsFetched, iterate orders.ConfirmedOrders, and wire a Restore Purchases button to storeController.RestoreTransactions(...). |
| Subscription appears expired or never expires | Using a permanent local flag instead of checking EntitlementStatus or server-side subscription expiry timestamps. | Use storeController.CheckEntitlement(vipProduct) and backend subscription status validation on each session launch. |
| Android billing library conflict during Gradle build | Duplicate billing.aar libraries from legacy plugins conflicting with com.unity.purchasing. | Remove outdated manual .aar files in Assets/Plugins/Android and resolve dependencies cleanly via Unity Package Manager and Mobile Dependency Resolver. |
| iOS StoreKit testing fails in simulator or device | Testing App Store Connect products without signing into a Sandbox Apple Account or without enabling a StoreKit Configuration file in Xcode. | For local Xcode testing, enable a .storekit configuration file in the Xcode scheme; for App Store Connect sandbox testing, test on a physical iOS device with a Sandbox tester account. |
| Missing transaction verification | Approving purchases on the client without verifying order.Info.Receipt (Google Play) or order.Info.Apple.jwsRepresentation (iOS StoreKit 2) against store servers. | Implement a backend verification endpoint using the Google Play Developer API and Apple App Store Server API / StoreKit 2 JWS validation before granting content or calling ConfirmPurchase. |
15. Frequently Asked Questions
What changed in Unity IAP 5?
Unity IAP 5 replaces the legacy interface-driven architecture (IDetailedStoreListener, IStoreController, IExtensionProvider, ConfigurationBuilder, and ProcessPurchase) with an asynchronous, event-driven service model centered around StoreController (obtained via UnityIAPServices.StoreController()). You now connect asynchronously with Connect(), fetch catalog items with FetchProducts(), handle pending orders via OnPurchasePending(PendingOrder), and explicitly finalize transactions with ConfirmPurchase(PendingOrder).
How do I initialize Unity IAP 5?
Retrieve the controller instance using UnityIAPServices.StoreController(), subscribe to its lifecycle events (OnStoreDisconnected, OnProductsFetched, OnProductsFetchFailed, OnPurchasesFetched, OnPurchasePending, OnPurchaseConfirmed, and OnPurchaseFailed) before connecting, await storeController.Connect(), and then pass your ProductDefinition list into storeController.FetchProducts().
Why aren't my Unity IAP products loading?
Products typically fail to load when product IDs in C# do not exactly match the active product IDs in Google Play Console or App Store Connect, when in-app products are still in Draft/Inactive state, when required tax and banking forms are incomplete in the store portal, or when testing an Android build that has not been uploaded to a Google Play testing track with a licensed test account.
How do I verify purchases securely?
Never trust client-only string checks for high-value items. On Android (Google Play), extract order.Info.Receipt (containing the purchaseToken) and order.Info.TransactionID; on iOS (StoreKit 2), extract the cryptographically signed JWS string from order.Info.Apple.jwsRepresentation. Send the payload over HTTPS to your backend server, and validate it against the Google Play Developer API or Apple's StoreKit 2 JWS signature / App Store Server API before granting the item and calling ConfirmPurchase(pendingOrder).
How do I implement Remove Ads?
Create a NonConsumable product (for example, com.yourstudio.game.removeads). When confirmed or restored via OnPurchasesFetched / CheckEntitlement, update your persistent entitlement state and instruct your ad manager (such as Unity LevelPlay or Unity Ads) to destroy active banner views and bypass interstitial show calls while keeping optional rewarded video ads available.
How do I restore purchases on iOS?
Provide a visible Restore Purchases button in your settings or shop UI and call storeController.RestoreTransactions((success, error) => { ... }). A successful callback indicates the restore request completed with the App Store; actual restored non-consumables and active subscriptions are delivered through OnPurchasesFetched(Orders) and can be verified per item with CheckEntitlement(product).
Can I use Unity IAP with Android and iOS?
Yes. The com.unity.purchasing package provides a unified C# API across Google Play Billing on Android and Apple StoreKit on iOS. If your product identifiers match on both stores, you can use a single ProductDefinition list; if they differ, map platform-specific IDs using CatalogProvider and StoreSpecificIds.
How do I prevent duplicate purchase rewards?
Treat every purchase callback as potentially repeatable. Record each fulfilled transaction ID (pendingOrder.Info.TransactionID) in your backend database or persistent save system before granting rewards, check that ledger before fulfilling any order in OnPurchasePending or OnPurchasesFetched, and call storeController.ConfirmPurchase(pendingOrder) only after fulfillment succeeds.
16. Final Checklist and Next Steps
Before shipping your Unity IAP 5 integration to production on Google Play and the Apple App Store, run through this final engineering checklist:
- Store Agreements Active: Paid Apps Agreement, tax forms, and banking profiles are marked Active in both App Store Connect and Google Play Console.
- Exact Product IDs: All
ProductDefinitionIDs in C# match the active product IDs and product types (Consumable,NonConsumable,Subscription) in both store portals. - Event Subscriptions Before
Connect(): AllStoreControllerevents (including bothOnPurchaseConfirmedandOnPurchaseFailed) are registered prior to callingConnect(). - Editor Test Bypass Disabled:
allowLocalEditorTestFulfillmentisfalse, and all production purchases are verified against your backend server before fulfillment. - Idempotent Ledger &
ConfirmPurchase: Every fulfilled transaction ID is recorded before granting rewards, andConfirmPurchase(pendingOrder)is called promptly so Google Play orders are never auto-refunded after 3 days. - iOS Restore Purchases Button: A visible Restore Purchases button is present in your UI and wired to
storeController.RestoreTransactions(...).
Related Unity Monetization & Engineering Guides
To build a complete hybrid monetization and live-ops architecture around your in-app store, explore these related guides:
- Unity LevelPlay SDK Setup Guide (Part 1): Interstitial & Banner Ads →
- Unity Ads SDK Setup Guide: Rewarded Video Integration in C# →
- GameAnalytics Unity SDK Setup Guide: Cohort & Purchase Telemetry →
- Unity Mobile Game Optimization Guide: Memory & Frame Rate →
- Mobile Game Development Services | Unity Game Development Services
Get Practical Unity Development Insights
Technical guides on Unity performance, AI gameplay systems, mobile monetization, and game development.
Unsubscribe at any time. Your data is never shared.
Recommended Reading
More articles in Game Monetization
Unity Ads SDK Setup Guide: Rewarded Video Integration in C#
Learn to install and initialize Unity Ads in Unity, implement rewarded video ads in C#, handle callbacks, test on Android and iOS, and avoid common SDK errors.
Unity LevelPlay SDK Setup Guide: Interstitial & Banner Ads (2026)
Learn how to install Unity LevelPlay, initialize the SDK, and integrate interstitial and banner ads using modern Unity C# APIs, with testing and troubleshooting tips.
Updating Unity Mobile Games Without Store Submissions: Architecture & AssetBundle Fundamentals (Part 1)
Part 1 of the 3-part LiveOps masterclass. Learn how to dynamically update Unity mobile game content, levels, and assets over-the-air without submitting new binary builds to Apple & Google Play.