|
| 1 | +#if (UNITY_IOS || UNITY_ANDROID) |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using ModIO; |
| 5 | +using Plugins.mod.io.Platform.Mobile; |
| 6 | +using Unity.Services.Core; |
| 7 | +using Unity.Services.Core.Environments; |
| 8 | +using UnityEngine; |
| 9 | +using UnityEngine.Purchasing; |
| 10 | +using UnityEngine.Purchasing.Extension; |
| 11 | +using Logger = ModIO.Implementation.Logger; |
| 12 | +using LogLevel = ModIO.LogLevel; |
| 13 | + |
| 14 | +namespace External |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// An Example of how to use the Unity Purchasing module for android and ios devices. |
| 18 | + /// </summary> |
| 19 | + public class MobilePurchasingExample : MonoBehaviour, IDetailedStoreListener |
| 20 | + { |
| 21 | + static IStoreController storeController; |
| 22 | + static IExtensionProvider storeExtensionProvider; |
| 23 | + List<ProductCatalogItem> catalogProducts; |
| 24 | + |
| 25 | + public async void Awake() |
| 26 | + { |
| 27 | + InitializationOptions options = new InitializationOptions(); |
| 28 | + |
| 29 | + // Set environment based on build type |
| 30 | +#if UNITY_EDITOR || DEVELOPMENT_BUILD |
| 31 | + options.SetEnvironmentName("test"); |
| 32 | +#else |
| 33 | + options.SetEnvironmentName("production"); |
| 34 | +#endif |
| 35 | + Logger.Log(LogLevel.Verbose, "Initializing Unity Services"); |
| 36 | + await UnityServices.InitializeAsync(options); |
| 37 | + } |
| 38 | + |
| 39 | + public void Start() |
| 40 | + { |
| 41 | + ResourceRequest operation = Resources.LoadAsync<TextAsset>("IAPProductCatalog"); |
| 42 | + operation.completed += HandleIAPCatalogLoaded; |
| 43 | + Logger.Log(LogLevel.Verbose, "Initialized Unity Services"); |
| 44 | + } |
| 45 | + |
| 46 | + bool IsInitialized() |
| 47 | + { |
| 48 | + return storeController != null && storeExtensionProvider != null; |
| 49 | + } |
| 50 | + |
| 51 | + //Converts items from the IAP catalog for use by the Unity Purchasing module |
| 52 | + void HandleIAPCatalogLoaded(AsyncOperation operation) |
| 53 | + { |
| 54 | + ResourceRequest request = operation as ResourceRequest; |
| 55 | + Logger.Log(LogLevel.Verbose, $"Loaded Asset: {request?.asset}"); |
| 56 | + |
| 57 | + var catalog = JsonUtility.FromJson<ProductCatalog>((request?.asset as TextAsset)?.text); |
| 58 | + if (catalog.allProducts is List<ProductCatalogItem> productList) |
| 59 | + { |
| 60 | + catalogProducts = productList; |
| 61 | + } |
| 62 | + else |
| 63 | + { |
| 64 | + Logger.Log(LogLevel.Error, "Catalog data is corrupted!"); |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + Logger.Log(LogLevel.Verbose, $"Loaded Catalog with {catalog.allProducts.Count} items."); |
| 69 | + ConfigurationBuilder builder; |
| 70 | +#if UNITY_IOS |
| 71 | + builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance(AppStore.AppleAppStore)); |
| 72 | +#elif UNITY_ANDROID |
| 73 | + builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance(AppStore.GooglePlay)); |
| 74 | +#else |
| 75 | + builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance()); |
| 76 | +#endif |
| 77 | + |
| 78 | + foreach (var p in catalog.allProducts) |
| 79 | + { |
| 80 | + Logger.Log(LogLevel.Verbose, $"Added product {p.id} to builder."); |
| 81 | + builder.AddProduct(p.id, p.type); |
| 82 | + } |
| 83 | + |
| 84 | + Logger.Log(LogLevel.Verbose, $"UnityPurchasing Initialize called"); |
| 85 | + UnityPurchasing.Initialize(this, builder); |
| 86 | + } |
| 87 | + |
| 88 | + |
| 89 | + // Method called when store initialization fails |
| 90 | + |
| 91 | + public void OnInitialized(IStoreController controller, IExtensionProvider extensions) |
| 92 | + { |
| 93 | + storeController = controller; |
| 94 | + storeExtensionProvider = extensions; |
| 95 | + Logger.Log(LogLevel.Verbose, $"OnInitialized IAP Success"); |
| 96 | + } |
| 97 | + |
| 98 | + // Overloaded method called when store initialization fails with message |
| 99 | + public void OnInitializeFailed(InitializationFailureReason error) |
| 100 | + { |
| 101 | + Logger.Log(LogLevel.Error, $"OnInitialize IAP Failed - {error}"); |
| 102 | + } |
| 103 | + |
| 104 | + public void OnInitializeFailed(InitializationFailureReason error, string message) |
| 105 | + { |
| 106 | + Logger.Log(LogLevel.Error, $"OnInitialize IAP Failed - {error} : {message}"); |
| 107 | + } |
| 108 | + |
| 109 | + public void GetWalletBalance() |
| 110 | + { |
| 111 | + if (!IsInitialized()) |
| 112 | + { |
| 113 | + Debug.LogWarning("IAPManager is not initialized."); |
| 114 | + return; |
| 115 | + } |
| 116 | + |
| 117 | + //We must create a wallet before a user can sync |
| 118 | + ModIOUnity.GetUserWalletBalance(balanceResult => |
| 119 | + { |
| 120 | + if (balanceResult.result.Succeeded()) |
| 121 | + { |
| 122 | + Logger.Log(LogLevel.Verbose, $"WalletBalance is {balanceResult.value.balance}"); |
| 123 | + } |
| 124 | + }); |
| 125 | + } |
| 126 | + |
| 127 | + //attached to a button to initiate a token purchase |
| 128 | + public void Buy1000Tokens() |
| 129 | + { |
| 130 | + if (!IsInitialized()) |
| 131 | + { |
| 132 | + Debug.LogWarning("IAPManager is not initialized."); |
| 133 | + return; |
| 134 | + } |
| 135 | + |
| 136 | + if(catalogProducts.Count == 0) |
| 137 | + { |
| 138 | + Logger.Log(LogLevel.Verbose, "No products found in catalog!"); |
| 139 | + return; |
| 140 | + } |
| 141 | + |
| 142 | + string id = catalogProducts[0].id; |
| 143 | + Product product = storeController.products.WithID(id); |
| 144 | + if (product != null && product.availableToPurchase) |
| 145 | + storeController.InitiatePurchase(product); |
| 146 | + } |
| 147 | + |
| 148 | + // Method called when InitiatePurchase is completed without an error |
| 149 | + public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) |
| 150 | + { |
| 151 | + Logger.Log(LogLevel.Verbose, "ProcessPurchase Called"); |
| 152 | + if(catalogProducts.Count == 0) |
| 153 | + { |
| 154 | + Logger.Log(LogLevel.Verbose, "No products found in catalog!"); |
| 155 | + return PurchaseProcessingResult.Pending; |
| 156 | + } |
| 157 | + |
| 158 | + if (String.Equals(args.purchasedProduct.definition.id, catalogProducts[0].id, StringComparison.Ordinal)) |
| 159 | + { |
| 160 | + //Save the receipt for processing. This also calls sync entitlements. |
| 161 | + MobilePurchaseHelper.QueuePurchase(args.purchasedProduct, ()=>storeController.ConfirmPendingPurchase(args.purchasedProduct)); |
| 162 | + Logger.Log(LogLevel.Verbose, string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id)); |
| 163 | + } |
| 164 | + else |
| 165 | + { |
| 166 | + Logger.Log(LogLevel.Verbose, string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id)); |
| 167 | + } |
| 168 | + |
| 169 | + return PurchaseProcessingResult.Pending; |
| 170 | + } |
| 171 | + |
| 172 | + // Method called when purchase fails |
| 173 | + public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason) |
| 174 | + { |
| 175 | + Logger.Log(LogLevel.Error, $"Purchase Failed - {product.definition.id} : {failureReason}"); |
| 176 | + } |
| 177 | + |
| 178 | + // Overloaded method called when purchase fails with description |
| 179 | + public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription) |
| 180 | + { |
| 181 | + Logger.Log(LogLevel.Error, $"Purchase Failed - {product.definition.id} : {failureDescription.message}"); |
| 182 | + } |
| 183 | + } |
| 184 | +} |
| 185 | +#endif |
0 commit comments