Unity IAP makes it easy to implement in-app purchases in your application across the most popular app stores. Below is example code for Unity IAP 5.0 or above
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Purchasing;
using System.Threading.Tasks;
public class IAPManager : MonoBehaviour
{
public delegate void InitializeDelegate();
public event InitializeDelegate InitializeSuccess;
public event InitializeDelegate InitializeFailure;
public delegate void PurchaseDelegate();
public PurchaseDelegate OnPurhaseResultse;
private static Action<bool, string> ProductPurchased;
public IAPProduct[] InAppIDs;
public StoreController m_StoreController; // The Unity Purchasing system.
public static IAPManager _This;
public static bool monthlySubscribed;
public static bool yearlySubscribed;
public string monthlyID = "";
public string yearlyID = "";
void Awake()
{
if (_This == null)
{
_This = this;
}
DontDestroyOnLoad(this);
}
async void Start()
{
foreach (IAPProduct p in InAppIDs)
{
if (p.Name.ToLower().Contains("monthly"))
{
monthlyID = p.Id;
}
else if (p.Name.ToLower().Contains("yearly"))
{
yearlyID = p.Id;
}
}
// If we haven't set up the Unity Purchasing reference
await InitializeIAPAsync();
}
private async Task InitializeIAPAsync()
{
try
{
// Get the store controller instance
m_StoreController = UnityIAPServices.StoreController();
// Register event handlers
m_StoreController.OnProductsFetched += OnProductsFetched;
m_StoreController.OnPurchasesFetched += OnPurchasesFetched;
//
m_StoreController.OnPurchasePending += OnPurchasePending;
m_StoreController.OnPurchaseFailed += OnPurchaseFailed;
m_StoreController.OnPurchaseConfirmed += OnPurchaseConfirmed;
m_StoreController.OnPurchaseDeferred += OnPurchaseDeferred;
//
m_StoreController.OnCheckEntitlement += OnCheckEntitlement;
// Define which products to fetch details for
var initialProductsToFetch = new List<ProductDefinition>();
foreach (var item in InAppIDs)
{
initialProductsToFetch.Add(new(item.Id, item.Type));
}
// Connect to the store and fetch product details
await m_StoreController.Connect();
m_StoreController.FetchProducts(initialProductsToFetch);
if (InitializeSuccess != null) InitializeSuccess();
Debug.Log("Unity IAP initialized successfully.");
}
catch (UnityException ex)
{
Debug.LogError($"IAP Initialization failed: {ex.Message}");
if (InitializeFailure != null) InitializeFailure();
}
}
// Results Check Subscription Status
bool isSubscribed = false;
private void OnCheckEntitlement(Entitlement entitlement)
{
string id = entitlement.Product.definition.id;
if (entitlement.Status == EntitlementStatus.FullyEntitled)
{
if (id == monthlyID)
{
monthlySubscribed = true;
isSubscribed = true;
}
else if (id == yearlyID)
{
yearlySubscribed = true;
isSubscribed = true;
}
}
else
{
if (id == monthlyID)
{
monthlySubscribed = false;
}
else if (id == yearlyID)
{
yearlySubscribed = false;
}
}
}
// Event handler
private void OnPurchaseDeferred(DeferredOrder order)
{
if (order?.Info?.PurchasedProductInfo != null && order?.Info?.PurchasedProductInfo.Count > 0)
{
string productID = order?.Info?.PurchasedProductInfo[0].productId;
if (ProductPurchased != null)
{
ProductPurchased(false, productID);
}
}
}
private void OnPurchaseConfirmed(Order order)
{
if (order?.Info?.PurchasedProductInfo != null && order?.Info?.PurchasedProductInfo.Count > 0)
{
string productID = order?.Info?.PurchasedProductInfo[0].productId;
if (ProductPurchased != null)
{
ProductPurchased(true, productID);
}
}
}
private void OnPurchaseFailed(FailedOrder order)
{
if (order?.Info?.PurchasedProductInfo != null && order?.Info?.PurchasedProductInfo.Count > 0)
{
string productID = order?.Info?.PurchasedProductInfo[0].productId;
if (ProductPurchased != null)
{
ProductPurchased(false, productID);
}
}
}
private void OnPurchasesFetched(Orders orders)
{
if (orders?.ConfirmedOrders?.Count > 0)
{
foreach (var confirmedOrder in orders.ConfirmedOrders)
{
foreach (var productInfo in confirmedOrder.Info.PurchasedProductInfo)
{
// Handle your Restore IAP Products Consumption
}
}
}
}
private void OnPurchasePending(PendingOrder order)
{
m_StoreController.ConfirmPurchase(order);
}
private void OnProductsFetched(List<Product> products)
{
m_StoreController.FetchPurchases();
foreach (var product in products)
{
Debug.Log($"Fetched product: {product.definition.id} priced at {product.metadata.localizedPriceString}");
for (int i = 0; i < InAppIDs.Length; i++)
{
if (product.definition.id == InAppIDs[i].Id)
{
InAppIDs[i].Price = product.metadata.localizedPriceString;
if (InAppIDs[i].Type == ProductType.Subscription)
{
m_StoreController.CheckEntitlement(product);
}
break;
}
}
}
}
// Functionality for shop
public void RestorePurchases()
{
m_StoreController.FetchPurchases();
}
public void BuyProduct(string product, Action<bool, string> purchasedCallback)
{
ProductPurchased = purchasedCallback;
m_StoreController.PurchaseProduct(product);
}
}