Unity IAP
In-App Purchases
Receipt Validation
Mobile Game Monetization
Game Engineering
iOS & Android

Unity IAP 5 Setup Guide: In-App Purchases in C#

37 min read
Eshan Naithani

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:

MERMAID
sequenceDiagram
    autonumber
    actor Player as Player (Device)
    participant Game as Unity C# Client
    participant Store as Native App Store (Apple/Google)
    participant Server as Game Backend / Validator

    Game->>Store: 1. FetchProducts(catalogIds)
    Store-->>Game: Return localized prices & availability
    Player->>Game: 2. Tap "Buy 100 Gems" -> PurchaseProduct()
    Game->>Store: Initiate native billing request
    Store->>Player: 3. Render OS payment sheet & process payment
    Store-->>Game: 4. Fire OnPurchasePending(PendingOrder with Receipt)
    Game->>Server: 5. Verify Receipt (JWS on iOS / PurchaseToken on Android)
    Server-->>Game: Receipt Validated -> Grant 100 Gems
    Game->>Store: 6. ConfirmPurchase(pendingOrder)
  1. 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).
  2. Purchase Initiation: When the player taps a buy button, the C# client calls storeController.PurchaseProduct(), passing the unique product identifier.
  3. 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.
  4. Pending Transaction & Receipt Delivery: Once the transaction completes, the store delivers an encrypted receipt and unique transaction ID to Unity, firing OnPurchasePending(PendingOrder).
  5. 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.purchasing v5.0+). Unity IAP 5 introduces a major architectural redesign compared to Unity IAP 4.x. Code written for older IAP 4 tutorials using IDetailedStoreListener, ConfigurationBuilder, and ProcessPurchase(PurchaseEventArgs) cannot be copied directly into a Unity IAP 5 project without migration.

Key Architectural Changes: Unity IAP 4 vs. Unity IAP 5

Lifecycle StepLegacy Unity IAP 4.x (Old)Modern Unity IAP 5.x (New)
Controller AccessIStoreController & IExtensionProvider supplied via OnInitializedStoreController obtained directly via UnityIAPServices.StoreController()
Callback ModelMonolithic IDetailedStoreListener interfaceGranular C# Action events on StoreController
Store StartupConfigurationBuilder + UnityPurchasing.Initialize(this, builder)await storeController.Connect() followed by storeController.FetchProducts(...)
Fetching Existing PurchasesImplicit during Initialize()Explicit storeController.FetchPurchases() -> OnPurchasesFetched(Orders)
Processing New PurchasesSynchronous ProcessPurchase(PurchaseEventArgs) returning PurchaseProcessingResultEvent-driven OnPurchasePending(PendingOrder)
Finalizing / ConfirmingReturn PurchaseProcessingResult.Complete or call ConfirmPendingPurchase(Product)Call storeController.ConfirmPurchase(PendingOrder) -> OnPurchaseConfirmed(Order)
Restoring Transactionsextensions.GetExtension<IAppleExtensions>().RestoreTransactions(...)Built directly into storeController.RestoreTransactions(...)
Receipt & Transaction Dataproduct.receipt and product.transactionIDorder.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:

  1. 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).
  2. 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).
  3. Secure Transaction Verification: Validating Google Play purchase tokens and Apple StoreKit 2 signed JWS transactions on a backend server before granting content.
  4. Idempotent Fulfillment & Confirmation: Recording transaction IDs to prevent duplicate rewards, persisting player entitlements, and acknowledging orders with ConfirmPurchase(PendingOrder).
  5. Cross-Device Restoration & Testing: Restoring purchases with FetchPurchases() and RestoreTransactions(), and testing every edge case in Google Play and App Store sandboxes.

Table of Contents

  1. What Is Unity IAP?
  2. Unity IAP 4 vs IAP 5
  3. Requirements and Installation
  4. Configuring Products in App Store Connect and Google Play
  5. Initializing Unity IAP 5
  6. Complete C# StoreController Example
  7. Purchasing Consumables
  8. Implementing Remove Ads
  9. Handling Subscriptions
  10. Secure Transaction Verification
  11. Confirming Purchases and Preventing Duplicates
  12. Restoring Purchases
  13. Testing on Android and iOS
  14. Troubleshooting Common Errors
  15. Frequently Asked Questions
  16. 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 EnumOwnership LifecycleExample in a Mobile Game
ProductType.ConsumablePurchased, fulfilled, and consumed so the player can buy it again.100 Gems pack in an RPG, energy refills, or extra revive tokens.
ProductType.NonConsumablePurchased once per store account and permanently owned across reinstalls.Remove Ads upgrade in an idle game, permanent character unlock, or expansion pack.
ProductType.SubscriptionAuto-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:

  1. Decoupled Steps (Connect → FetchProducts → FetchPurchases): In IAP 4, a single UnityPurchasing.Initialize() call connected to the store, queried product metadata, and triggered ProcessPurchase for 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).
  2. Explicit Order Hierarchy: Instead of passing a generic Product with a mutable .receipt property into ProcessPurchase, IAP 5 models transactions as strongly typed Order objects:
    • PendingOrder: A newly authorized or unconfirmed purchase waiting for fulfillment and ConfirmPurchase(pendingOrder).
    • ConfirmedOrder: A finalized transaction returned in OnPurchaseConfirmed or OnPurchasesFetched.
    • 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: Contains FailureReason (PurchaseFailureReason) and native diagnostic Details.
  3. Cart-Aware Order Payloads: Each Order exposes order.CartOrdered.Items() and order.Info (containing order.Info.TransactionID, order.Info.Receipt on Google Play, order.Info.Apple.jwsRepresentation on iOS StoreKit 2, and order.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

  1. Open your Unity project and navigate to Window > Package Manager.
  2. Select Packages: Unity Registry from the top-left dropdown.
  3. Search for In-App Purchasing (com.unity.purchasing).
  4. Select version 5.0.0 or the latest stable 5.x release and click Install (or Update).
  5. If your project uses Unity Gaming Services (UGS), ensure com.unity.services.core is also installed so you can initialize UnityServices.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

  1. Upload at least one signed .aab (Android App Bundle) that includes the com.unity.purchasing billing permission (com.android.vending.BILLING) to an Internal Testing or Closed Testing track.
  2. Navigate to Monetize with Play > Products > In-app products to create com.yourstudio.game.gems100 and com.yourstudio.game.removeads, and set their status to Active.
  3. 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

  1. 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).
  2. Under your app record, open Monetization > In-App Purchases and create com.yourstudio.game.gems100 (Consumable) and com.yourstudio.game.removeads (Non-Consumable).
  3. 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:

CSHARP
using System.Collections.Generic;
using UnityEngine.Purchasing;

public static class IAPCatalogBuilder
{
    public static List<ProductDefinition> BuildWithStoreOverrides()
    {
        var catalog = new CatalogProvider();

        var gemsStoreIds = new StoreSpecificIds();
        gemsStoreIds.Add("com.yourstudio.game.gems100.android", GooglePlay.Name);
        gemsStoreIds.Add("com.yourstudio.game.gems100.ios", AppleAppStore.Name);

        catalog.AddProduct(
            "com.yourstudio.game.gems100",
            ProductType.Consumable,
            gemsStoreIds
        );

        catalog.AddProduct("com.yourstudio.game.removeads", ProductType.NonConsumable);
        catalog.AddProduct("com.yourstudio.game.vipmonthly", ProductType.Subscription);

        return new List<ProductDefinition>(catalog.GetProducts());
    }
}

5. Initializing Unity IAP 5

Initialization in Unity IAP 5 follows a strict sequence so no events are missed:

  1. Obtain StoreController: Call UnityIAPServices.StoreController().
  2. Subscribe to Events Before Connecting: Register your handlers for OnStoreDisconnected, OnProductsFetched, OnProductsFetchFailed, OnPurchasesFetched, OnPurchasesFetchFailed, OnPurchasePending, OnPurchaseConfirmed, OnPurchaseFailed, and OnCheckEntitlement.

    Important: You must subscribe to both OnPurchaseConfirmed and OnPurchaseFailed whenever your code calls ConfirmPurchase(pendingOrder). Unity IAP 5 enforces this so asynchronous confirmation failures are never silently ignored.

  3. Connect Asynchronously: Call await storeController.Connect().
  4. Fetch Products: Pass your List<ProductDefinition> to storeController.FetchProducts(definitions).
  5. Fetch Existing Purchases: Inside OnProductsFetched(List<Product> products), call storeController.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, and OnPurchaseFailed
  • 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.purchasing v5.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.

CSHARP
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Purchasing;

public class UnityIAP5Manager : MonoBehaviour
{
    public static UnityIAP5Manager Instance { get; private set; }

    // Cross-platform Product IDs (must match Google Play Console & App Store Connect)
    public const string ProductGems100 = "com.yourstudio.game.gems100";
    public const string ProductRemoveAds = "com.yourstudio.game.removeads";
    public const string ProductVipMonthly = "com.yourstudio.game.vipmonthly";

    [Header("Development & Testing ONLY")]
    [Tooltip("Keep FALSE in production builds. Only enable in Editor Fake Store when testing local UI flows without a backend.")]
    [SerializeField] private bool allowLocalEditorTestFulfillment = false;

    private StoreController storeController;
    private readonly Dictionary<string, Product> fetchedProducts = new Dictionary<string, Product>();
    private readonly HashSet<string> productsInPurchaseFlow = new HashSet<string>();
    private readonly HashSet<string> processedTransactionIds = new HashSet<string>();
    private readonly Dictionary<string, PendingOrder> unconfirmedPendingOrders = new Dictionary<string, PendingOrder>();

    private bool isConnecting;
    private bool isConnected;
    private bool areEventsSubscribed;

    private Action<bool, string> pendingRestoreCallback;
    private bool isRestoreAwaitingPurchasesFetch;
    private int pendingRestoreEntitlementChecks;

    public bool IsStoreReady => isConnected && fetchedProducts.Count > 0;
    public bool HasRemoveAdsEntitlement { get; private set; }
    public bool HasActiveVipSubscription { get; private set; }

    public event Action OnCatalogReady;
    public event Action<int> OnGemsGranted;
    public event Action<bool> OnRemoveAdsEntitlementChanged;
    public event Action<bool> OnVipSubscriptionStateChanged;
    public event Action<string, string> OnPurchaseErrorUI;

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
        DontDestroyOnLoad(gameObject);
        LoadLocalDemoProcessedTransactions();
    }

    private async void Start()
    {
        await InitializeStoreAsync();
    }

    // =========================================================================
    // A. STORE INITIALIZATION & PRODUCT FETCHING
    // =========================================================================

    public async Task InitializeStoreAsync()
    {
        if (isConnected || isConnecting)
        {
            return;
        }

        isConnecting = true;

        try
        {
            if (storeController == null)
            {
                storeController = UnityIAPServices.StoreController();
            }

            SubscribeStoreEvents();

            Debug.Log("[UnityIAP5] Connecting to store service...");
            await storeController.Connect();

            isConnected = true;
            isConnecting = false;

            Debug.Log("[UnityIAP5] Store connected. Fetching product catalog...");
            FetchProductCatalog();
        }
        catch (Exception ex)
        {
            isConnecting = false;
            isConnected = false;
            Debug.LogError($"[UnityIAP5] Failed to connect to store: {ex.Message}");
        }
    }

    private void SubscribeStoreEvents()
    {
        if (storeController == null || areEventsSubscribed)
        {
            return;
        }

        storeController.OnStoreDisconnected += HandleStoreDisconnected;
        storeController.OnProductsFetched += HandleProductsFetched;
        storeController.OnProductsFetchFailed += HandleProductsFetchFailed;
        storeController.OnPurchasesFetched += HandlePurchasesFetched;
        storeController.OnPurchasesFetchFailed += HandlePurchasesFetchFailed;
        storeController.OnPurchasePending += HandlePurchasePending;
        storeController.OnPurchaseConfirmed += HandlePurchaseConfirmed;
        storeController.OnPurchaseFailed += HandlePurchaseFailed;
        storeController.OnCheckEntitlement += HandleCheckEntitlement;

        areEventsSubscribed = true;
    }

    private void UnsubscribeStoreEvents()
    {
        if (storeController == null || !areEventsSubscribed)
        {
            return;
        }

        storeController.OnStoreDisconnected -= HandleStoreDisconnected;
        storeController.OnProductsFetched -= HandleProductsFetched;
        storeController.OnProductsFetchFailed -= HandleProductsFetchFailed;
        storeController.OnPurchasesFetched -= HandlePurchasesFetched;
        storeController.OnPurchasesFetchFailed -= HandlePurchasesFetchFailed;
        storeController.OnPurchasePending -= HandlePurchasePending;
        storeController.OnPurchaseConfirmed -= HandlePurchaseConfirmed;
        storeController.OnPurchaseFailed -= HandlePurchaseFailed;
        storeController.OnCheckEntitlement -= HandleCheckEntitlement;

        areEventsSubscribed = false;
    }

    private void FetchProductCatalog()
    {
        var definitions = new List<ProductDefinition>
        {
            new ProductDefinition(ProductGems100, ProductType.Consumable),
            new ProductDefinition(ProductRemoveAds, ProductType.NonConsumable),
            new ProductDefinition(ProductVipMonthly, ProductType.Subscription)
        };

        storeController.FetchProducts(definitions);
    }

    private void HandleStoreDisconnected(StoreConnectionFailureDescription failure)
    {
        isConnected = false;
        isConnecting = false;
        Debug.LogWarning($"[UnityIAP5] Store disconnected: {failure?.Message}");
    }

    private void HandleProductsFetched(List<Product> products)
    {
        fetchedProducts.Clear();

        if (products != null)
        {
            foreach (Product product in products)
            {
                if (product?.definition != null)
                {
                    fetchedProducts[product.definition.id] = product;
                    Debug.Log($"[UnityIAP5] Loaded Product: {product.definition.id} | Price: {product.metadata?.localizedPriceString} | Available: {product.availableToPurchase}");
                }
            }
        }

        OnCatalogReady?.Invoke();

        // Once products are loaded in the catalog, fetch existing purchases and entitlements
        storeController.FetchPurchases();
        RefreshEntitlementChecks();
    }

    private void HandleProductsFetchFailed(ProductFetchFailed failure)
    {
        Debug.LogError($"[UnityIAP5] Product fetch failed: {failure?.FailureReason}");
    }

    // =========================================================================
    // B. DISPLAYING LOCALIZED PRICES & STARTING PURCHASES
    // =========================================================================

    public string GetLocalizedPrice(string productId, string fallbackText = "--")
    {
        if (fetchedProducts.TryGetValue(productId, out Product product) &&
            product?.metadata != null &&
            !string.IsNullOrEmpty(product.metadata.localizedPriceString))
        {
            return product.metadata.localizedPriceString;
        }

        return fallbackText;
    }

    public void BuyProduct(string productId)
    {
        if (!isConnected || storeController == null)
        {
            Debug.LogWarning("[UnityIAP5] Cannot start purchase: Store is not connected.");
            OnPurchaseErrorUI?.Invoke(productId, "Store is currently offline. Please check your connection.");
            return;
        }

        if (productsInPurchaseFlow.Contains(productId))
        {
            Debug.LogWarning($"[UnityIAP5] Purchase already in progress for '{productId}'. Ignoring duplicate tap.");
            return;
        }

        if (!fetchedProducts.TryGetValue(productId, out Product product) || product == null || !product.availableToPurchase)
        {
            Debug.LogError($"[UnityIAP5] Product '{productId}' is not available for purchase.");
            OnPurchaseErrorUI?.Invoke(productId, "This item is currently unavailable in your store region.");
            return;
        }

        productsInPurchaseFlow.Add(productId);
        Debug.Log($"[UnityIAP5] Starting purchase for: {productId}");
        storeController.PurchaseProduct(product);
    }

    // =========================================================================
    // C. PURCHASE LIFECYCLE & CONFIRMATION
    // =========================================================================

    private async void HandlePurchasePending(PendingOrder pendingOrder)
    {
        if (pendingOrder?.Info == null)
        {
            return;
        }

        string transactionId = pendingOrder.Info.TransactionID;
        string verificationPayload = ExtractVerificationPayload(pendingOrder);

        if (!string.IsNullOrEmpty(transactionId))
        {
            unconfirmedPendingOrders[transactionId] = pendingOrder;
        }

        foreach (var cartItem in pendingOrder.CartOrdered.Items())
        {
            string productId = cartItem.Product?.definition?.id;
            if (!string.IsNullOrEmpty(productId))
            {
                productsInPurchaseFlow.Remove(productId);
            }
        }

        // 1. Verify the order cryptographically with your backend server before granting
        OrderVerificationStatus verificationStatus = await VerifyOrderWithBackendAsync(pendingOrder, verificationPayload);

        if (verificationStatus == OrderVerificationStatus.RetryableNetworkError)
        {
            // Keep the order pending; do NOT call ConfirmPurchase so it can be retried
            Debug.LogWarning($"[UnityIAP5] Verification network error for transaction '{transactionId}'. Leaving order pending for retry.");
            return;
        }

        if (verificationStatus == OrderVerificationStatus.InvalidTransaction)
        {
            Debug.LogError($"[UnityIAP5] Transaction '{transactionId}' failed cryptographic verification. Refusing fulfillment.");
            return;
        }

        // 2. Fulfill each item idempotently and persist the result before confirming
        bool allItemsFulfilled = true;
        foreach (var cartItem in pendingOrder.CartOrdered.Items())
        {
            string productId = cartItem.Product?.definition?.id;
            if (string.IsNullOrEmpty(productId))
            {
                continue;
            }

            bool fulfilled = FulfillProductIdempotently(productId, transactionId);
            if (!fulfilled)
            {
                allItemsFulfilled = false;
            }
        }

        // 3. Confirm the pending purchase ONLY after fulfillment and persistence succeed
        if (allItemsFulfilled)
        {
            Debug.Log($"[UnityIAP5] Confirming PendingOrder for transaction '{transactionId}'.");
            storeController.ConfirmPurchase(pendingOrder);
        }
    }

    private void HandlePurchaseConfirmed(Order order)
    {
        switch (order)
        {
            case ConfirmedOrder confirmedOrder:
                string txId = confirmedOrder.Info?.TransactionID;
                if (!string.IsNullOrEmpty(txId))
                {
                    unconfirmedPendingOrders.Remove(txId);
                }
                Debug.Log($"[UnityIAP5] Order confirmation completed with store. Transaction: {txId}");
                break;

            case FailedOrder failedConfirmation:
                // Never pass a FailedOrder back to ConfirmPurchase; keep original PendingOrder for retry
                Debug.LogError($"[UnityIAP5] Order confirmation failed. Reason: {failedConfirmation.FailureReason}, Details: {failedConfirmation.Details}");
                break;
        }
    }

    private void HandlePurchaseFailed(FailedOrder failedOrder)
    {
        if (failedOrder?.CartFailed != null)
        {
            foreach (var item in failedOrder.CartFailed.Items())
            {
                string prodId = item.Product?.definition?.id;
                if (!string.IsNullOrEmpty(prodId))
                {
                    productsInPurchaseFlow.Remove(prodId);
                }
            }
        }

        if (failedOrder != null && failedOrder.FailureReason == PurchaseFailureReason.UserCancelled)
        {
            Debug.Log("[UnityIAP5] Player cancelled the purchase dialog.");
            return;
        }

        Debug.LogError($"[UnityIAP5] Purchase failed. Reason: {failedOrder?.FailureReason}, Details: {failedOrder?.Details}");
        OnPurchaseErrorUI?.Invoke(string.Empty, $"Purchase could not be completed ({failedOrder?.FailureReason}).");
    }

    // =========================================================================
    // D. FETCHING EXISTING PURCHASES & RESTORING ENTITLEMENTS
    // =========================================================================

    private async void HandlePurchasesFetched(Orders orders)
    {
        await ProcessFetchedOrdersAsync(orders);
    }

    private async Task ProcessFetchedOrdersAsync(Orders orders)
    {
        try
        {
            if (orders?.ConfirmedOrders == null)
            {
                return;
            }

            // Verify each restored ConfirmedOrder with your backend before granting entitlements
            foreach (ConfirmedOrder confirmedOrder in orders.ConfirmedOrders)
            {
                if (confirmedOrder == null)
                {
                    continue;
                }

                string verificationPayload = ExtractVerificationPayload(confirmedOrder);
                OrderVerificationStatus verificationStatus = await VerifyOrderWithBackendAsync(confirmedOrder, verificationPayload);

                if (verificationStatus != OrderVerificationStatus.Verified)
                {
                    Debug.LogWarning($"[UnityIAP5] Skipping unverified restored order '{confirmedOrder.Info?.TransactionID}' (Status: {verificationStatus}).");
                    continue;
                }

                foreach (var item in confirmedOrder.CartOrdered.Items())
                {
                    string productId = item.Product?.definition?.id;
                    if (productId == ProductRemoveAds)
                    {
                        ApplyRemoveAdsEntitlement(true);
                    }
                    else if (productId == ProductVipMonthly)
                    {
                        ApplyVipSubscriptionState(true);
                    }
                }
            }
        }
        finally
        {
            if (isRestoreAwaitingPurchasesFetch)
            {
                isRestoreAwaitingPurchasesFetch = false;
                TryCompletePendingRestoreIfReady();
            }
        }
    }

    private void HandlePurchasesFetchFailed(PurchasesFetchFailureDescription failure)
    {
        string message = failure?.Message ?? "Failed to fetch existing purchases.";
        Debug.LogWarning($"[UnityIAP5] Failed to fetch existing purchases: {message}");

        if (isRestoreAwaitingPurchasesFetch || pendingRestoreCallback != null)
        {
            isRestoreAwaitingPurchasesFetch = false;
            pendingRestoreEntitlementChecks = 0;
            CompletePendingRestore(false, message);
        }
    }

    public int RefreshEntitlementChecks(bool trackForRestore = false)
    {
        if (!isConnected || storeController == null)
        {
            return 0;
        }

        int checksStarted = 0;

        if (fetchedProducts.TryGetValue(ProductRemoveAds, out Product removeAdsProduct))
        {
            if (trackForRestore)
            {
                pendingRestoreEntitlementChecks++;
            }
            checksStarted++;
            storeController.CheckEntitlement(removeAdsProduct);
        }

        if (fetchedProducts.TryGetValue(ProductVipMonthly, out Product vipProduct))
        {
            if (trackForRestore)
            {
                pendingRestoreEntitlementChecks++;
            }
            checksStarted++;
            storeController.CheckEntitlement(vipProduct);
        }

        return checksStarted;
    }

    private async void HandleCheckEntitlement(Entitlement entitlement)
    {
        await ProcessEntitlementCheckAsync(entitlement);
    }

    private async Task ProcessEntitlementCheckAsync(Entitlement entitlement)
    {
        try
        {
            string productId = entitlement?.Product?.definition?.id;
            if (string.IsNullOrEmpty(productId))
            {
                return;
            }

            bool isStoreEntitled = entitlement.Status == EntitlementStatus.FullyEntitled ||
                                   entitlement.Status == EntitlementStatus.EntitledUntilConsumed;

            if (!isStoreEntitled)
            {
                if (productId == ProductRemoveAds)
                {
                    ApplyRemoveAdsEntitlement(false);
                }
                else if (productId == ProductVipMonthly)
                {
                    ApplyVipSubscriptionState(false);
                }
                return;
            }

            // When the store reports an active entitlement, verify the underlying Order before granting
            string verificationPayload = ExtractVerificationPayload(entitlement.Order);
            OrderVerificationStatus verificationStatus = await VerifyOrderWithBackendAsync(entitlement.Order, verificationPayload);
            bool verifiedEntitled = verificationStatus == OrderVerificationStatus.Verified;

            if (!verifiedEntitled)
            {
                Debug.LogWarning($"[UnityIAP5] Entitlement order for '{productId}' did not pass backend verification ({verificationStatus}).");
                return;
            }

            if (productId == ProductRemoveAds)
            {
                ApplyRemoveAdsEntitlement(true);
            }
            else if (productId == ProductVipMonthly)
            {
                ApplyVipSubscriptionState(true);
            }
        }
        finally
        {
            if (pendingRestoreEntitlementChecks > 0)
            {
                pendingRestoreEntitlementChecks--;
                TryCompletePendingRestoreIfReady();
            }
        }
    }

    public void RestorePurchasesFromUIButton(Action<bool, string> onRestoreFinished = null)
    {
        if (!isConnected || storeController == null)
        {
            onRestoreFinished?.Invoke(false, "Store is not connected.");
            return;
        }

        if (pendingRestoreCallback != null)
        {
            Debug.LogWarning("[UnityIAP5] A restore operation is already in progress.");
            return;
        }

        pendingRestoreCallback = onRestoreFinished;
        Debug.Log("[UnityIAP5] Requesting store transaction restoration...");

        storeController.RestoreTransactions((bool success, string error) =>
        {
            if (!success)
            {
                Debug.LogWarning($"[UnityIAP5] RestoreTransactions failed: {error}");
                CompletePendingRestore(false, error);
                return;
            }

            Debug.Log("[UnityIAP5] RestoreTransactions call succeeded. Waiting for asynchronous purchase fetch and entitlement verification...");
            isRestoreAwaitingPurchasesFetch = true;
            RefreshEntitlementChecks(trackForRestore: true);
            storeController.FetchPurchases();
            TryCompletePendingRestoreIfReady();
        });
    }

    private void TryCompletePendingRestoreIfReady()
    {
        if (pendingRestoreCallback == null)
        {
            return;
        }

        if (!isRestoreAwaitingPurchasesFetch && pendingRestoreEntitlementChecks <= 0)
        {
            CompletePendingRestore(true, null);
        }
    }

    private void CompletePendingRestore(bool success, string error)
    {
        Action<bool, string> callback = pendingRestoreCallback;
        pendingRestoreCallback = null;
        isRestoreAwaitingPurchasesFetch = false;
        pendingRestoreEntitlementChecks = 0;
        callback?.Invoke(success, error);
    }

    // =========================================================================
    // E. IDEMPOTENT FULFILLMENT & BACKEND VERIFICATION HOOK
    // =========================================================================

    private enum OrderVerificationStatus
    {
        Verified,
        InvalidTransaction,
        RetryableNetworkError
    }

    private string ExtractVerificationPayload(Order order)
    {
        if (order?.Info == null)
        {
            return null;
        }

#if UNITY_IOS
        // On iOS (StoreKit 2), Unity IAP 5 exposes the cryptographically signed JWS transaction string on Order.Info.Apple.jwsRepresentation
        return order.Info.Apple?.jwsRepresentation;
#elif UNITY_ANDROID
        // On Android (Google Play), Order.Info.Receipt contains the receipt JSON wrapper with the purchaseToken
        return order.Info.Receipt;
#else
        return order.Info.Apple?.jwsRepresentation ?? order.Info.Receipt;
#endif
    }

    private async Task<OrderVerificationStatus> VerifyOrderWithBackendAsync(Order order, string verificationPayload)
    {
        if (order?.Info == null || string.IsNullOrEmpty(verificationPayload))
        {
            return OrderVerificationStatus.InvalidTransaction;
        }

#if UNITY_EDITOR
        if (allowLocalEditorTestFulfillment)
        {
            await Task.Yield();
            Debug.LogWarning("[UnityIAP5] Using Editor-only local test fulfillment bypass. Never enable in production builds.");
            return OrderVerificationStatus.Verified;
        }
#endif

        // Production Requirement: Send verificationPayload (order.Info.Apple.jwsRepresentation on iOS StoreKit 2,
        // or order.Info.Receipt on Google Play) and order.Info.TransactionID to your backend verification service
        // (Google Play Developer API / Apple App Store Server API).
        // Never auto-approve unverified purchases in production client code.
        await Task.Yield();
        Debug.LogError("[UnityIAP5] Backend receipt verification endpoint is not configured. Refusing unverified fulfillment.");
        return OrderVerificationStatus.RetryableNetworkError;
    }

    private bool FulfillProductIdempotently(string productId, string transactionId)
    {
        if (!string.IsNullOrEmpty(transactionId) && processedTransactionIds.Contains(transactionId))
        {
            Debug.Log($"[UnityIAP5] Transaction '{transactionId}' was already fulfilled. Skipping duplicate grant and confirming order.");
            return true;
        }

        switch (productId)
        {
            case ProductGems100:
                GrantConsumableGems(100);
                break;

            case ProductRemoveAds:
                ApplyRemoveAdsEntitlement(true);
                break;

            case ProductVipMonthly:
                ApplyVipSubscriptionState(true);
                break;

            default:
                Debug.LogWarning($"[UnityIAP5] Unrecognized Product ID '{productId}'.");
                return false;
        }

        if (!string.IsNullOrEmpty(transactionId))
        {
            RecordProcessedTransaction(transactionId);
        }

        return true;
    }

    private void GrantConsumableGems(int amount)
    {
        // Local demonstration state only: in production, persist currency on your backend or encrypted save system
        int updatedTotal = PlayerPrefs.GetInt("Demo_UserGems", 0) + amount;
        PlayerPrefs.SetInt("Demo_UserGems", updatedTotal);
        PlayerPrefs.Save();

        Debug.Log($"[UnityIAP5] Granted +{amount} Gems (Demo local total: {updatedTotal}).");
        OnGemsGranted?.Invoke(amount);
    }

    private void ApplyRemoveAdsEntitlement(bool entitled)
    {
        HasRemoveAdsEntitlement = entitled;
        OnRemoveAdsEntitlementChanged?.Invoke(entitled);
        Debug.Log($"[UnityIAP5] Remove Ads entitlement state updated: {entitled}");
    }

    private void ApplyVipSubscriptionState(bool active)
    {
        HasActiveVipSubscription = active;
        OnVipSubscriptionStateChanged?.Invoke(active);
        Debug.Log($"[UnityIAP5] Monthly VIP subscription state updated: {active}");
    }

    private void LoadLocalDemoProcessedTransactions()
    {
        // Local demonstration ledger only: use a server-side database in production
        string saved = PlayerPrefs.GetString("Demo_ProcessedTxIds", string.Empty);
        if (string.IsNullOrEmpty(saved))
        {
            return;
        }

        foreach (string id in saved.Split('|'))
        {
            if (!string.IsNullOrEmpty(id))
            {
                processedTransactionIds.Add(id);
            }
        }
    }

    private void RecordProcessedTransaction(string transactionId)
    {
        processedTransactionIds.Add(transactionId);
        PlayerPrefs.SetString("Demo_ProcessedTxIds", string.Join("|", processedTransactionIds));
        PlayerPrefs.Save();
    }

    private void OnDestroy()
    {
        if (Instance == this)
        {
            Instance = null;
        }

        UnsubscribeStoreEvents();
    }
}

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:

  1. Receive OnPurchasePending(PendingOrder): Extract pendingOrder.Info.TransactionID along with pendingOrder.Info.Receipt (on Google Play) or pendingOrder.Info.Apple.jwsRepresentation (on iOS StoreKit 2).
  2. Validate the Transaction: Send the verification payload and transaction ID to your backend verification endpoint.
  3. Check Idempotency by Transaction ID: Before adding 100 Gems, check whether transactionId already exists in your fulfilled transactions ledger. If the app crashed after granting the gems yesterday but before ConfirmPurchase() finished, OnPurchasePending will fire again on the next launch with the same TransactionID. Checking the ledger prevents granting 200 Gems for a single payment.
  4. Grant and Persist: Credit the 100 Gems and flush the save state to disk (or commit the database transaction on your server).
  5. Call ConfirmPurchase(pendingOrder): Acknowledge and consume the order with the store only after step 4 completes.

Important Note on PlayerPrefs: In UnityIAP5Manager.cs, PlayerPrefs is used strictly to illustrate local demonstration state. On rooted Android devices or unencrypted local backups, PlayerPrefs XML/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:

  1. Query and verify ownership on startup via storeController.FetchPurchases() and storeController.CheckEntitlement(removeAdsProduct).
  2. Subscribe your ad bridge to OnRemoveAdsEntitlementChanged and pass the verified entitlement state to your ad manager (such as Unity LevelPlay or standalone Unity Ads):
CSHARP
using System;
using UnityEngine;

public class AdEntitlementBridge : MonoBehaviour
{
    private void OnEnable()
    {
        if (UnityIAP5Manager.Instance != null)
        {
            UnityIAP5Manager.Instance.OnRemoveAdsEntitlementChanged += HandleRemoveAdsChanged;
            HandleRemoveAdsChanged(UnityIAP5Manager.Instance.HasRemoveAdsEntitlement);
        }
    }

    private void OnDisable()
    {
        if (UnityIAP5Manager.Instance != null)
        {
            UnityIAP5Manager.Instance.OnRemoveAdsEntitlementChanged -= HandleRemoveAdsChanged;
        }
    }

    private void HandleRemoveAdsChanged(bool hasRemoveAds)
    {
        if (LevelPlayAdManager.Instance != null)
        {
            // Update the ad manager's entitlement state to destroy active ads AND guard future ad requests
            LevelPlayAdManager.Instance.SetAdsRemoved(hasRemoveAds);
        }
    }
}
  1. Inside your ad manager (LevelPlayAdManager), maintain an areAdsRemoved flag that immediately tears down active banner/interstitial instances when enabled and guards all future LoadBannerAd(), ShowBannerAd(), LoadInterstitialAd(), and ShowInterstitialAd() operations:
CSHARP
// Inside LevelPlayAdManager.cs: guarding banner and interstitial operations when Remove Ads is active
public bool AreAdsRemoved { get; private set; }

public void SetAdsRemoved(bool removed)
{
    AreAdsRemoved = removed;

    if (AreAdsRemoved)
    {
        // Immediately destroy any active banner or preloaded interstitial ad objects
        DestroyBannerAd();
        DestroyInterstitialAd();
    }
}

public void LoadBannerAd()
{
    if (AreAdsRemoved)
    {
        return;
    }

    // Proceed with banner creation and loading...
}

public void ShowBannerAd()
{
    if (AreAdsRemoved)
    {
        return;
    }

    bannerAd?.ShowAd();
}

public void LoadInterstitialAd()
{
    if (AreAdsRemoved)
    {
        return;
    }

    interstitialAd?.LoadAd();
}

public void ShowInterstitialAd(string placementName = null, Action onComplete = null)
{
    if (AreAdsRemoved)
    {
        // Invoke the completion callback immediately so level transitions continue without showing an ad
        onComplete?.Invoke();
        return;
    }

    // Proceed with normal interstitial readiness check and display...
}

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 writing PlayerPrefs.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 OnProductsFetched completes, call storeController.FetchPurchases() and storeController.CheckEntitlement(vipProduct).
    • In HandleCheckEntitlement(Entitlement entitlement), check whether entitlement.Status == EntitlementStatus.FullyEntitled. If the subscription has expired (EntitlementStatus.NotEntitled), revoke the in-game VIP perks.
  • 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.Receipt contains a JSON wrapper with Store ("GooglePlay"), TransactionID, and a Payload containing the signed purchase JSON and purchaseToken.
  • Your Unity client sends the productId and purchaseToken over 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
  • The backend verifies that purchaseState is purchased (0), confirms the purchaseToken has 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 verifyReceipt Endpoint: Apple deprecated the legacy buy.itunes.apple.com/verifyReceipt endpoint. Do not build new verification services around verifyReceipt.
  • 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 from order.Info.Apple.jwsRepresentation and sends it to your backend server. Your backend (or Apple's App Store Server API Get Transaction Info / Get All Subscription Statuses endpoints 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 that bundleId, productId, and environment (Sandbox vs. Production) match, and confirms the transactionId has 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:

JSON
// POST /api/v1/iap/verify-order (Request from Unity Client to Your Backend)
{
  "playerId": "player_948102",
  "store": "GooglePlay",
  "productId": "com.yourstudio.game.gems100",
  "transactionId": "GPA.3312-4910-8821-10294",
  "verificationPayload": "<order.Info.Receipt on GooglePlay, or order.Info.Apple.jwsRepresentation on iOS StoreKit 2>"
}

// 200 OK (Response from Your Backend after querying Google Play / Apple APIs)
{
  "verified": true,
  "alreadyProcessed": false,
  "grantedProductId": "com.yourstudio.game.gems100",
  "serverTimestamp": 1761840000
}

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 Gems and the game crashes before storeController.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 through OnPurchasePending.
  • 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:

  1. Key every consumable grant by pendingOrder.Info.TransactionID (and on Android, the purchaseToken).
  2. 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.
  3. If ConfirmPurchase(pendingOrder) fails asynchronously and triggers OnPurchaseConfirmed with a FailedOrder, never pass that FailedOrder back into ConfirmPurchase. Retain the original PendingOrder reference (as shown in unconfirmedPendingOrders in UnityIAP5Manager.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() after OnProductsFetched automatically queries Google Play Billing for all non-consumed purchases and active subscriptions associated with the user's Google account and delivers them to OnPurchasesFetched(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:

CSHARP
public void OnRestorePurchasesButtonClicked()
{
    if (UnityIAP5Manager.Instance == null)
    {
        return;
    }

    UnityIAP5Manager.Instance.RestorePurchasesFromUIButton((bool requestSucceeded, string error) =>
    {
        if (!requestSucceeded)
        {
            Debug.LogWarning($"Restore request could not be completed: {error}");
            return;
        }

        // RestorePurchasesFromUIButton invokes this callback only after RestoreTransactions,
        // FetchPurchases (OnPurchasesFetched), CheckEntitlement, and backend verification complete.
        bool anyEntitlementActive =
            UnityIAP5Manager.Instance.HasRemoveAdsEntitlement ||
            UnityIAP5Manager.Instance.HasActiveVipSubscription;

        if (anyEntitlementActive)
        {
            Debug.Log("Previous purchases restored and verified successfully.");
        }
        else
        {
            Debug.Log("Restore completed: No previously purchased items were found for this account.");
        }
    });
}

Important Distinction: When RestoreTransactions((bool success, string error) => ...) returns success == 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 in UnityIAP5Manager.RestorePurchasesFromUIButton, always wait for OnPurchasesFetched and OnCheckEntitlement (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):
    1. Upload a signed build to an Internal Testing track in Google Play Console.
    2. Add your testers' Gmail addresses under Setup > License testing in Google Play Console.
    3. 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):
    1. In App Store Connect, go to Users and Access > Sandbox > Testers and create a Sandbox Apple Account.
    2. 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).
    3. 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 Gems and verify the balance increments once and OnPurchaseConfirmed fires.
  • Purchase Cancellation: Open the store payment sheet and tap Cancel/Back. Confirm PurchaseFailureReason.UserCancelled is 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 OnPurchaseFailed cleanly.
  • 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 OnPurchasePending fires after approval.
  • Crash Recovery & Duplicate Callback Handling: Comment out storeController.ConfirmPurchase(pendingOrder) temporarily, complete a test purchase, force-close and relaunch the app, re-enable ConfirmPurchase, and confirm your idempotency check prevents granting the reward twice.
  • Reinstall and Restore: Purchase Remove Ads, uninstall and reinstall the app, and verify that automatic FetchPurchases() (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 / SymptomPossible CauseRecommended 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 IDsMismatch 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 falseThe 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 popupTreating 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 currencyOnPurchasePending 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 reinstallRelying 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 expiresUsing 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 buildDuplicate 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 deviceTesting 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 verificationApproving 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 ProductDefinition IDs in C# match the active product IDs and product types (Consumable, NonConsumable, Subscription) in both store portals.
  • Event Subscriptions Before Connect(): All StoreController events (including both OnPurchaseConfirmed and OnPurchaseFailed) are registered prior to calling Connect().
  • Editor Test Bypass Disabled: allowLocalEditorTestFulfillment is false, and all production purchases are verified against your backend server before fulfillment.
  • Idempotent Ledger & ConfirmPurchase: Every fulfilled transaction ID is recorded before granting rewards, and ConfirmPurchase(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(...).

To build a complete hybrid monetization and live-ops architecture around your in-app store, explore these related guides:

Need help implementing Unity IAP, Remove Ads, subscriptions, or secure purchase validation? I help game studios build reliable monetization systems in Unity.

Share this article

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