Unity Gaming Services tutorial series, part 9: In-app purchases

Welcome back to our Unity Gaming Services tutorial series. In this post, you’ll learn the steps for setting up real money purchases for iOS and Android.

Where to find all of the content in the Unity Gaming Services tutorial series

The UGS series consists of 10 sets of tutorials, with each set comprising a video and written tutorial.

Video tutorials

The full video tutorial series will be here. We’ll add the video tutorials to this playlist throughout October.

Written tutorials

You’ll find links to all articles in this series as they become available in Part 1, the introduction post.

Demo project and scripts

You can find the Gem Hunter Match – Cloud Edition demo project in the GitHub page.

The scripts used in the tutorials can be downloaded here:

UGSTutorialSeries_Scripts.zip (1.6 MB)

Watch the video version of this tutorial here:

The In-App Purchasing package from Unity

You should already have created a Real Money Purchase in the Unity Dashboard as shown here:

Make sure to install version 5 of the In-App Purchasing package and set up in project settings. Let’s first look at the client side first, and then in Cloud Code after.

Let’s create an IAPStoreManagerV5 script. This version includes an event-based system with a store controller. The store controller exposes events for fetching products from previous purchases and events for the purchase lifecycle.

Start with a reference to the PlayerEconomyManager – constants for real money products product IDs (k_GoldPurchase100id) same as the IDs set up in the dashboard. You’ll have a boolean for state tracking with m_IsPurchaseInProgress. You’ll also have your StoreServiceBindings for calling Cloud Code functions. Use the StoreController and you’ll also have a receipt validation component. Finally, have actions for the purchase outcome which could be displayed to the user on the UI.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Services.CloudCode;
using Unity.Services.CloudCode.GeneratedBindings;
using Unity.Services.CloudCode.GeneratedBindings.UGSTutorialCloud;
using Unity.Services.Economy;
using Unity.Services.Economy.Model;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Extension;
using UnityEngine.Purchasing.Security;

public class IAPStoreManagerV5 : MonoBehaviour
{
    [Header("Dependencies")]
    [SerializeField]
    PlayerEconomyManager m_PlayerEconomyManager;

    private const string k_GoldPurchase100Id = "GOLD_PURCHASE_100";

    private bool m_IsPurchaseInProgress;

    private StoreServiceBindings m_Bindings;

    // v5 controller (one stop for fetching, purchasing, confirming)
    private StoreController m_StoreController;

    // Optional Google validator (Apple is StoreKit2 internal in v5)
    private CrossPlatformValidator m_GoogleValidator;

    public event Action<string> SuccessfullyPurchased;
    public event Action<string> PurchaseFailed;

    private void Start()
    {
        // Wait for Economy config before wiring IAP, so products are defined from the server config.
        m_PlayerEconomyManager.EconomyConfigSynced += InitializeIAPAsync;

        m_Bindings = new StoreServiceBindings(CloudCodeService.Instance);
    }
}
private void OnDestroy()
    {
        m_PlayerEconomyManager.EconomyConfigSynced -= InitializeIAPAsync;
    }

Wait for the Economy sync to be completed. Subscribe to the event triggered by the PlayerEconomyManager script which at the same time is waiting for the SignedIn event to complete. You’ll also create an instance to the cloud binding.

When the SyncEconomyConfig finishes, initialize the system in the InitializeIAPAsync() method. Get the store controller and then attach event handlers for purchase related events (code block after). Once you connect to the store, you’ll fetch products asynchronously. Create a list of product definitions (productDefs) and then do a check in case the list is empty. Then, call FetchProducts(productDefs) with that list and InitializeReceiptValidatorsIfNeeded().

private async void InitializeIAPAsync()
    {
        // Get Controller
        m_StoreController = UnityIAPServices.StoreController();

        // Subscribe to events
        SubscribeIAPEvents();

        try
        {
            // When this call completes, you may assume that IAP has connected to your current app store.
            await m_StoreController.Connect();
            Debug.Log("[IAP] Connected to store.");

            // Build and fetch products from Economy config
            var productDefs = BuildProductDefinitionsFromEconomy();
            if (productDefs.Count == 0)
            {
                Debug.LogWarning("[IAP] No real-money products found in Economy config.");
                return;
            }

            // Requests information from the store with the product info (ids, type)
            // The store responds with current prices and localized descriptions
            // Unity IAP fires the OnProductsFetched event with the data
            m_StoreController.FetchProducts(productDefs);
        }
        catch (Exception e)
        {
            Debug.LogError($"[IAP] Connect failed: {e.Message}");
        }

        InitializeReceiptValidatorsIfNeeded();
    }

Fetch Products(productDefs) is an async operation that queries the platform store with the product IDs, and if they exist they give back information to the player like prices and details in the local currency.

Let’s look at the function BuildProductDefinitionsFromEconomy() where you prepare your production definition list.

private List<ProductDefinition> BuildProductDefinitionsFromEconomy()
    {
        var productDefinitions = new List<ProductDefinition>();
        var realMoney = EconomyService.Instance.Configuration.GetRealMoneyPurchases();
        LogRealPurchasesFromConfig(realMoney);

        foreach (var purchase in realMoney)
        {
            // If you need per-store IDs, you can branch on Application.platform or store name.
            // For simplicity, just use the Economy ID; you can add a platform-specific
            // storeSpecificId overload later if required.
            var def = new ProductDefinition(id: purchase.Id, type: ProductType.Consumable);
            productDefinitions.Add(def);
        }

        Debug.Log($"[IAP] Prepared {productDefinitions.Count} ProductDefinitions for fetch.");
        return productDefinitions;
    }

You retrieve the real money purchases from the Economy service and prepare the product definition type; in the example this is a consumable product. For simplicity’s sake you should keep the same id for all platforms stores but you could create different ones.

If you created a non-consumable product like a “remove ads” product, this should only be purchased once and is not part of the game economy. It can make sense to handle it directly from the IAP Catalog, which is another alternative independent from the Economy service.

You previously configured the products in the Unity Dashboard in the Economy section, but you can find the IAP Catalog window in the Editor via Services > In-App Purchasing > IAP Catalog.

The flow for retrieving the products from the IAP Catalog is slightly different; the below function shows how it can be done.

// Alternative: Using CatalogProvider instead of Economy configuration
    private void BuildAndFetchProductsWithCatalog()
    {
        // Load catalog from Assets/Resources/IAPProductCatalog.json
        var catalog = ProductCatalog.LoadDefaultCatalog();
        if (catalog == null || catalog.allProducts == null || catalog.allProducts.Count == 0)
        {
            Debug.LogWarning("[IAP] No products in IAPProductCatalog.json.");
            return;
        }

        var productDefinitions = new List<ProductDefinition>();
        foreach (var item in catalog.allProducts)
        {
            // Convert each catalog item into a ProductDefinition
            productDefinitions.Add(
                new ProductDefinition(
                    item.id,  // The ID from your IAP Catalog
                    item.type // Consumable / NonConsumable / Subscription
                )
            );
        }

        // Fetch products from store using Unity IAP Services
        m_StoreController.FetchProducts(productDefinitions);
    }

The last method to call is InitializeReceiptValidatorsIfNeeded(), which sets up the cross-platform validator and verifies that purchase receipts are legitimate, a process that’s crucial to protecting your game’s economy. Skip the validation while in Editor. From version 5 onwards of the In-App Purchasing package, validation is only required for Google Play.

private void InitializeReceiptValidatorsIfNeeded()
    {
#if !UNITY_EDITOR
        // In v5, Apple receipts are handled by StoreKit2. Keep validator for Google only.
        if (Application.platform == RuntimePlatform.Android)
        {
            try
            {
                // v5 sample ctor for CrossPlatformValidator on Google
                m_GoogleValidator = new CrossPlatformValidator(GooglePlayTangle.Data(), Application.identifier);
                Debug.Log("[IAP] Google receipt validator initialized.");
            }
            catch (Exception e)
            {
                Debug.LogWarning($"[IAP] Validator init skipped/failed: {e.Message}");
            }
        }
#endif
    }

Next let’s look at the event handlers. You can find information about those events in the documentation although the names are self explanatory.

private void SubscribeIAPEvents()
    {
        if (m_StoreController == null) return;

        // Product fetch lifecycle
        m_StoreController.OnProductsFetched += OnProductsFetched;
        m_StoreController.OnProductsFetchFailed += OnProductsFetchFailed;

        m_StoreController.OnPurchasesFetched += OnPurchasesFetched;
        m_StoreController.OnPurchasesFetchFailed += OnPurchasesFetchFailed;

        // Purchase lifecycle
        m_StoreController.OnPurchasePending += OnPurchasePending;       
        m_StoreController.OnPurchaseConfirmed += OnPurchaseConfirmed;   // fires after ConfirmPurchase
        m_StoreController.OnPurchaseFailed += OnPurchaseFailed;         


        // Disconnection
        m_StoreController.OnStoreDisconnected += OnStoreDisconnected;
    }

    private void UnsubscribeIAPEvents()
    {
        if (m_StoreController == null) return;

        m_StoreController.OnProductsFetched -= OnProductsFetched;
        m_StoreController.OnProductsFetchFailed -= OnProductsFetchFailed;

        m_StoreController.OnPurchasesFetched -= OnPurchasesFetched;
        m_StoreController.OnPurchasesFetchFailed -= OnPurchasesFetchFailed;

        m_StoreController.OnPurchasePending -= OnPurchasePending;
        m_StoreController.OnPurchaseConfirmed -= OnPurchaseConfirmed;
        m_StoreController.OnPurchaseFailed -= OnPurchaseFailed;

        m_StoreController.OnStoreDisconnected -= OnStoreDisconnected;
    }

Let’s look at your event handlers:

  • OnProductsFetched: Called when products are successfully retrieved from the store
  • OnPurchasesFetched: Called when existing purchases are retrieved

The log functions for each will display info about their status.

private void OnProductsFetched(List<Product> products)
    {
        m_StoreController.FetchPurchases();

        LogProductsFetched(products);
    }

    private void LogProductsFetched(List<Product> products)
    {
        Debug.Log($"[IAP] Products fetched: {products.Count}");
        foreach (var p in products)
        {
            Debug.Log($"[IAP] {p.definition.id} | {p.metadata.localizedTitle} | {p.metadata.localizedPriceString}");
        }
    }

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

    void OnPurchasesFetched(Orders orders)
    {
        // Process purchases, e.g. check for entitlements from completed orders  
    }

    private void OnPurchasesFetchFailed(PurchasesFetchFailureDescription failure)
    {
        Debug.LogError($"[IAP] Purchases fetch failed: {failure.FailureReason}");
    }

    private void OnStoreDisconnected(StoreConnectionFailureDescription desc)
    {
        Debug.LogError($"[IAP] Store disconnected: {desc.Message}");
    }

Now let’s implement your first purchase function. Check the status with your boolean first to avoid multiple purchases at the same time. Then you can purchase directly with the controller by product ID.

public void PurchaseGold()
    {
        if (m_IsPurchaseInProgress)
        {
            Debug.LogWarning("[IAP] Purchase already in progress.");
            return;
        }
        m_IsPurchaseInProgress = true;
        // In v5, you can purchase by id directly via the controller
        m_StoreController.PurchaseProduct(k_GoldPurchase100Id);
    }

Then, the event handler OnPurchasePending will be triggered when the purchase is fully paid and waiting for processing and confirmation. After a couple of checks you get the receipt pending.Info.Receipt and the transaction ID from the pending order. For Google Play, check the receipt.

Assuming all goes well, get the PlayerEconomyData back with the granted purchase. With that, you update the local economy data with m_PlayerEconomyManager.Handle EconomyUpdate(updated) and then, confirm the purchase after everything succeeds. Note that you haven’t yet written the function m_Bindings.ProcessRealMoneyPurchase; you’ll do this later.

OnPurchaseConfirmed and OnPurchaseFailed reset the purchase progress status check to false, and fire events when the purchase is confirmed or failed. Failed is a safeguard for when there might be connectivity issues, for example.

private async void OnPurchasePending(PendingOrder pending)
    {
        try
        {
            Debug.Log($"Full receipt JSON: {pending.Info.Receipt}");

            // v5: products live in the order’s cart (usually 1 item, but don’t assume)
            var firstItem = pending.CartOrdered.Items().FirstOrDefault();
            var pid = firstItem?.Product?.definition?.id;
            
            if (string.IsNullOrEmpty(pid))
            {
                Debug.LogError("[IAP] Pending order has no product id.");
                PurchaseFailed?.Invoke("No product id in pending order");
                return;
            }

            var product = m_StoreController?.GetProductById(pid);
            if (product == null)
            {
                Debug.LogError($"[IAP] Product not found in controller: {pid}");
                PurchaseFailed?.Invoke($"Product not found: {pid}");
                return;
            }

            Debug.Log($"[IAP] Pending purchase: {product.definition.id}");

            var receipt = pending.Info.Receipt;
            var transactionId = pending.Info.TransactionID;

            // Optional Google validation (Apple handled internally in v5)
            if (!ValidateIfGoogle(receipt))
            {
                Debug.LogError("[IAP] Google receipt validation failed.");
                PurchaseFailed?.Invoke("Invalid receipt for " + product.definition.id);
                return;
            }

            // Cloud Code validation + grant
            PlayerEconomyData updated = await m_Bindings.ProcessRealMoneyPurchase(
                product.definition.id,
                receipt,
                transactionId);

            if (updated == null)
            {
                Debug.LogError("[IAP] Cloud Code returned null economy data.");
                PurchaseFailed?.Invoke("Server processing failed for " + product.definition.id);
                return;
            }

            m_PlayerEconomyManager.HandleEconomyUpdate(updated);

            // Confirm the order to finalize with the store
            m_StoreController.ConfirmPurchase(pending);

            Debug.Log($"[IAP] Confirmed purchase: {product.definition.id}");
        }
        catch (Exception e)
        {
            Debug.LogError($"[IAP] Error processing pending order: {e.Message}");
            PurchaseFailed?.Invoke("Purchase failed" + e.Message);
        }
    }
private void OnPurchaseConfirmed(Order order)
    {
        m_IsPurchaseInProgress = false;
        
        // Fires after ConfirmPurchase. Good place for analytics.
        var purchasedProduct = order.CartOrdered.Items().FirstOrDefault()?.Product;

        Debug.Log($"[IAP] Purchase confirmed: {purchasedProduct?.definition.id} | Tx: {order.Info?.TransactionID}");
        SuccessfullyPurchased?.Invoke($"Purchase confirmed: { purchasedProduct?.definition.id}");
    }

    private void OnPurchaseFailed(FailedOrder failed)
    {
        m_IsPurchaseInProgress = false;

        Debug.LogError($"[IAP] Purchase failed: {failed.FailureReason.ToString()}");
        PurchaseFailed?.Invoke($"Purchase failed: {failed.FailureReason.ToString()}");
    }

If you were to test the code so far you would see this log in the project:

You can consider using the OnPurchaseDeferred event handler to handle when underage players need to send purchases for parental approval. For now, you can add an event handler to log this event.

Implementing the Cloud Code

In this section you’ll learn how to add server validation to your real money purchases. Previously, you saw how to call the Cloud Code binding m_Bindings.ProcessRealMoneyPurchase from the OnPurchasePending function. Now it’s time to process the purchase and update your player currency or inventory.

Open your Code Cloud solution and add the following code. The heavy lifting happens in the ProcessStoreReceipt task parsing the receipt to get shop type and product ID.

[CloudCodeFunction("ProcessRealMoneyPurchase")]
    public async Task<PlayerEconomyData> ProcessRealMoneyPurchase(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        string productId,
        string receipt,
        string transactionId)
    {
        try
        {
            await ProcessStoreReceipt(context, gameApiClient, productId, receipt, transactionId);
           
            return await m_PlayerEconomyService.GetPlayerEconomyData(context, gameApiClient)
                ?? throw new InvalidOperationException("Failed to get player economy data");
        }
        catch (ApiException ex)
        {
            m_Logger.LogWarning($"Economy API error processing purchase for product {productId}: {ex.Message}");
            throw;
        }
        catch (Exception e)
        {
            m_Logger.LogError($"Unexpected error processing purchase for product {productId}: {e.Message}");
            throw;
        }
    }

Parse the receipt in the following function that you add to the same service script. The receipt includes the store identifier and the actual receipt from the store in payload.

private async Task ProcessStoreReceipt(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        string productId,
        string receipt,
        string transactionId)
    {
        var receiptData = JsonConvert.DeserializeAnonymousType(receipt, new { Store = "", Payload = "" });
        var store = receiptData?.Store?.ToLower();

        switch (store)
        {
            case "fake":
                m_Logger.LogInformation("Using fake store - skipping receipt validation");
                await ApplyPurchaseRewardsFromConfiguration(context, gameApiClient, productId);
                break;

            case "googleplay":
                await RedeemGooglePlayPurchase(context, gameApiClient, productId, receipt, transactionId);
                break;

            case "apple":
                await RedeemAppleAppStorePurchase(context, gameApiClient, productId, receipt);
                break;

            default:
                throw new ArgumentException($"Unsupported store type: {store}");
        }
    }

If the store is “fake” that means that you’re testing in the Editor and from here, you can test your whole purchasing flow. Let’s look first at the Google Play and Apple App Store examples.

private async Task RedeemGooglePlayPurchase(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        string productId,
        string receipt,
        string transactionId)
    {
        var googleRequest = new PlayerPurchaseGoogleplaystoreRequest
        {
            Id = productId,
            PurchaseData = receipt,
            PurchaseDataSignature = transactionId
        };

        var purchaseResult = await gameApiClient.EconomyPurchases.RedeemGooglePlayPurchaseAsync(
            context,
            context.AccessToken,
            context.ProjectId,
            context.PlayerId!,
            googleRequest);
    }

private async Task RedeemAppleAppStorePurchase(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        string productId,
        string receipt)
    {
        var appleRequest = new PlayerPurchaseAppleappstoreRequest
        {
            Id = productId,
            Receipt = receipt
        };

        var purchaseResult = await gameApiClient.EconomyPurchases.RedeemAppleAppStorePurchaseAsync(
            context,
            context.AccessToken,
            context.ProjectId,
            context.PlayerId!,
            appleRequest);

        // Log what the player actually received
        foreach (var currency in purchaseResult.Data.Rewards.Currency)
        {
            m_Logger.LogInformation($"Granted {currency.Amount} {currency.Id}");
        }

        foreach (var item in purchaseResult.Data.Rewards.Inventory)
        {
            m_Logger.LogInformation($"Granted {item.Amount}x {item.Id}");
        }
    }

When you call RedeemGooglePlayPurchase or RedeemAppleAppStorePurchase, the Economy service handles several operations, including receipt validation with the stores. With reward distribution, the Economy service automatically grants the configured rewards based on the Economy configuration or IAP Catalog. With that, you’ll get some response data, var purchaseResult, which includes the rewards given by the store in exchange for the purchase. In this simplified example, you’re just returning the updated Economy Data to the client.

For now, log the result content, currency, or inventory by adding the following code after googleRequest and appleRequest.

// Log what the player actually received
        foreach (var currency in purchaseResult.Data.Rewards.Currency)
        {
            m_Logger.LogInformation($"Granted {currency.Amount} {currency.Id}");
        }

        foreach (var item in purchaseResult.Data.Rewards.Inventory)
        {
            m_Logger.LogInformation($"Granted {item.Amount}x {item.Id}");
        }

Testing in the Unity Editor

Now you’ll test your mock store. You manually grant the rewards by starting with fetching the EconomyConfiguration, and looking up the purchase definition to try and find the real money purchase by ID with GetRealMoneyPurchaseFromConfig. You’ll grant the rewards with DistributeConfiguredRewards.

public async Task ApplyPurchaseRewardsFromConfiguration(IExecutionContext context, IGameApiClient gameApiClient, string productId)
    {
        try
        {
            var configResponse = await gameApiClient.EconomyConfiguration.GetPlayerConfigurationAsync(
                context, 
                context.AccessToken, 
                context.ProjectId,
                context.PlayerId!
                );

            var realMoneyPurchase = GetRealMoneyPurchaseFromConfig(configResponse.Data.Results, productId);

            if (realMoneyPurchase?.Rewards != null)
            {
                await DistributeConfiguredRewards(context, gameApiClient, configResponse.Data.Results, realMoneyPurchase.Rewards);
            }
        }
        catch (Exception ex)
        {
            m_Logger.LogError(ex, $"Failed to grant rewards for product {productId}");
            throw;
        }
    }

Loop through the Economy configuration to find the real money purchase by ID, and through each Config result, and check it with result.ActualInstance if it’s a resource with a matching ID. If you find a match, return it immediately. If the ID doesn’t match, it’s probably a currency, item, or virtual purchase, so just continue to the next result.

private RealMoneyPurchaseResource? GetRealMoneyPurchaseFromConfig(
        List<PlayerConfigurationResponseResultsInner> results,
        string productId)
    {
        foreach (var result in results)
        {
            if (result.ActualInstance is RealMoneyPurchaseResource purchase && purchase.Id == productId)
            {
                return purchase;
            }
        }

        m_Logger.LogError($"Real money purchase not found: {productId}");
        throw new InvalidOperationException($"Real money purchase not found: {productId}");
    }

private async Task DistributeConfiguredRewards(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        List<PlayerConfigurationResponseResultsInner> configResults,
        List<Reward> rewards)
    {
        foreach (var reward in rewards)
        {
            string resourceId = reward.ResourceId;
            int amount = reward.Amount;

            m_Logger.LogInformation($"Processing reward: {resourceId}, Amount: {amount}");

            string resourceType = m_PlayerEconomyService.GetResourceType(configResults, resourceId);
            await m_PlayerEconomyService.GrantResourceReward(context, gameApiClient, resourceType, resourceId, amount);
        }
    }

In the task DistributeConfiguredRewards, take each reward, check the resourceId and amount, and if it’s an inventory or currency resource type, grant the corresponding reward using the Economy API. Granting rewards better fits the responsibilities of the Economy service so let’s implement it there in the PlayerEconomyService script. There’s a guard clause that adds a second condition before returning the type of reward in a string. That way you can check the type and ID in a single expression.

You need to differentiate between currency and inventory items since they are handled differently in the Economy service. Use your methods implemented in tutorial #7, Player Economy, to grant currency or inventory items.

public async Task GrantResourceReward(
        IExecutionContext context,
        IGameApiClient gameApiClient,
        string resourceType,
        string resourceId,
        int amount)
    {
        switch (resourceType)
        {
            case "CURRENCY":
                await AddCurrency(context, gameApiClient, resourceId, amount);
                m_Logger.LogInformation($"Added currency: {resourceId}, Amount: {amount}");
                break;

            case "INVENTORY_ITEM":
                await AddOrUpdateInventoryItemAmount(context, gameApiClient, resourceId, amount);
                m_Logger.LogInformation($"Added inventory item: {resourceId}, Amount: {amount}");
                break;

            default:
                m_Logger.LogWarning($"Unknown resource type for reward: {resourceType}");
                break;
        }
    }

Go back to Unity, generate bindings and deploy your module.

Add the IAPStoreManagerV5 script to a GameObject and the reference to the PlayerEconomyManager. Now you’re ready to test and you can add a UI button to trigger the purchase of currency as well as inventory items.


Google Play license key

If you’re targeting Google Play, there’s a step that you need to take before you’re able to use transactions. Go to Google Play console > Monetize with Play > Monetization setup > Licensing and copy the key in the grey box.

Then go to your project’s Unity Dashboard and under Project Details add the key in the Google License Key field.

When you check the services setting in Project Settings in the Unity project, you’ll see the Receipt Obfuscator section where you need to click the Obfuscate License Keys button.

When it´s done you will see a message about GooglePlayTangle.cs generated for your project. This makes it harder for attackers to find vulnerabilities in the purchasing system.

When you test you’ll see your different logs showing the process: The product definition, the gold purchase ID, the receipt content, and the pending status.

For more information on the supported stores go to this section in the UGS documentation.