Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using AppsMinistry.InAppPurchases;
- using UnityEngine;
- using UnityEngine.Purchasing;
- using Newtonsoft.Json;
- using Prime31;
- using AppsMinistry.Common.Utils;
- using AppsMinistry.Common.Utils.PlayFab;
- using AppsMinistry.Plugins.Analytics;
- using AppsMinistry.Core;
- using AwesomeShooter.App;
- using UnityEngine.Advertisements;
- namespace AppsMinistry.InAppPurchases
- {
- public class UnityIapStrategy : PurchaseService, IStoreListener
- {
- private static IStoreController storeController; // Reference to the Purchasing system.
- private static IExtensionProvider storeExtensionProvider; // Reference to store-specific Purchasing
- private Action _OnSuccess;
- private Action _OnFail;
- private Action _OnCancel;
- private bool _isPurchasing;
- public override bool isPurchasing
- {
- get { return _isPurchasing; }
- set
- {
- _isPurchasing = value;
- if (_isPurchasing == false)
- {
- _OnSuccess = null;
- _OnFail = null;
- _OnCancel = null;
- }
- }
- }
- private bool IsInitialized
- {
- get
- {
- return storeController != null && storeExtensionProvider != null;
- }
- }
- public override string GetFormattedPrice(string productID)
- {
- if (IsInitialized)
- {
- var product = storeController.products.WithID(productID);
- if (product != null)
- {
- return product.metadata.localizedPriceString;
- }
- }
- return "";
- }
- public override void Initialize()
- {
- if (!IsInitialized)
- {
- var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
- var catalog = ProductCatalog.LoadDefaultCatalog();
- foreach (var item in InApps.ALL_INAPPS)
- builder.AddProduct(item.ProductID, item.InAppType);
- //builder.AddProduct("com.appsministry.inc.awesomeshooter.bannersupply01", ProductType.Consumable);
- //builder.AddProduct("com.appsministry.inc.awesomeshooter.bannersupply02", ProductType.Consumable);
- builder.AddProduct("com.appsministry.inc.awesomeshooter.bannerskincamo1dd201", ProductType.Consumable);
- builder.AddProduct("com.appsministry.inc.awesomeshooter.bannerskincamo2dd202", ProductType.Consumable);
- builder.AddProduct("com.appsministry.inc.awesomeshooter.bannerskingettodd203", ProductType.Consumable);
- UnityPurchasing.Initialize(this, builder);
- }
- }
- public override void PurchaseProduct(string productId, Action OnSuccess, Action OnFail = null, Action OnCancel = null)
- {
- Debug.Log("UnityIapStrategy::PurchaseProduct purchase " + productId);
- Debug.Log("-----------------------------------------------------------");
- Debug.Log("UnityIapStrategy::PurchaseProduct _OnSuccess == null: " + (_OnSuccess == null).ToString() + " _OnFail == null: " + (_OnFail == null).ToString());
- if (Application.internetReachability == NetworkReachability.NotReachable)
- {
- Debug.Log("UnityIapStrategy::PurchaseProduct Network NotReachable Show Alert here ");
- isPurchasing = false;
- }
- else
- {
- if (!IsInitialized)
- {
- Initialize();
- isPurchasing = false;
- }
- else
- {
- isPurchasing = true;
- _OnSuccess = OnSuccess;
- _OnFail = OnFail;
- _OnCancel = OnCancel;
- // ... look up the Product reference with the general product identifier and the Purchasing system's products collection.
- Product product = storeController.products.WithID(productId);
- // If the look up found a product for this device's store and that product is ready to be sold ...
- if (product != null && product.availableToPurchase)
- {
- Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));// ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
- AnalyticsManager.Instance.TrackInitiateIAP(productId);
- storeController.InitiatePurchase(product);
- }
- // Otherwise ...
- else
- {
- isPurchasing = false;
- // ... report the product look-up failure situation
- Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
- }
- }
- }
- }
- public override void RestorePurchases()
- {
- if (!IsInitialized)
- {
- // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
- Debug.Log("RestorePurchases FAIL. Not initialized.");
- return;
- }
- // If we are running on an Apple device ...
- if (Application.platform == RuntimePlatform.IPhonePlayer ||
- Application.platform == RuntimePlatform.OSXPlayer)
- {
- // ... begin restoring purchases
- Debug.Log("RestorePurchases started ...");
- // Fetch the Apple store-specific subsystem.
- var apple = storeExtensionProvider.GetExtension<IAppleExtensions>();
- // Begin the asynchronous process of restoring purchases. Expect a confirmation response in
- // the Action<bool> below, and ProcessPurchase if there are previously purchased products to restore.
- apple.RestoreTransactions((result) =>
- {
- // The first phase of restoration. If no more responses are received on ProcessPurchase then
- // no purchases are available to be restored.
- Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
- if (result)
- {
- PlatformUtil.ShowAlert("", "All restored");
- }
- });
- }
- // Otherwise ...
- else
- {
- // We are not running on an Apple device. No work is necessary to restore purchases.
- Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
- }
- }
- public override void UpdateSuccessPurchase(string productId, int validThru)
- {
- Debug.Log("UnityIapStrategy::UpdateSuccessPurchase productId = " + productId + "_OnSuccess == null: " + (_OnSuccess == null).ToString());
- PlayFabManager.Instance.PlayFabStore.GetCombinedInfo(delegate (bool success)
- {
- RaiseUpdateSuccessPurchase(productId, validThru);
- AppController.Instance.Model.Wallet.SendBuyEvent();
- if (_OnSuccess != null)
- _OnSuccess();
- isPurchasing = false;
- });
- }
- public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
- {
- Debug.LogFormat("UnityIapStrategy::OnPurchaseSuccessful productID {0}, transactionID {1}", e.purchasedProduct.definition.id, e.purchasedProduct.transactionID);
- float productPrice = (float)e.purchasedProduct.metadata.localizedPrice;
- if (!string.IsNullOrEmpty(e.purchasedProduct.receipt))
- {
- #if UNITY_IOS
- ValidateReceiptAppStore(e.purchasedProduct);
- #elif UNITY_ANDROID
- ValidateReceiptGooglePlay(e.purchasedProduct);
- #endif
- }
- string description = e.purchasedProduct.metadata.localizedDescription;
- string currencyCode = e.purchasedProduct.metadata.isoCurrencyCode;
- AnalyticsManager.LogInApp(e.purchasedProduct.transactionID,
- description,
- e.purchasedProduct.definition.id,
- productPrice,
- 1,
- "BuyServerSuccess",
- currencyCode);
- return PurchaseProcessingResult.Pending;
- }
- void ValidateReceiptAppStore(Product product)
- {
- var receiptData = JsonConvert.DeserializeObject<Dictionary<string, object>>(product.receipt);
- var request = new PlayFab.ClientModels.ValidateIOSReceiptRequest();
- request.ReceiptData = (string)receiptData["Payload"];
- request.PurchasePrice = (int)(product.metadata.localizedPrice * 100);
- request.CurrencyCode = product.metadata.isoCurrencyCode;
- PlayFab.PlayFabClientAPI.ValidateIOSReceipt(request,
- delegate (PlayFab.ClientModels.ValidateIOSReceiptResult result)
- {
- AnalyticsManager.Instance.TrackSuccessfulIAP();
- UpdateSuccessPurchase(product.definition.id, -1);
- storeController.ConfirmPendingPurchase(product);
- },
- delegate (PlayFab.PlayFabError error)
- {
- Debug.LogWarningFormat("<b><color=red>{0}</color></b>", "ValidateIOSReceipt(): " + error.ToString());
- isPurchasing = false;
- storeController.ConfirmPendingPurchase(product);
- });
- }
- void ValidateReceiptGooglePlay(Product product)
- {
- var receiptData = JsonConvert.DeserializeObject<Dictionary<string, object>>(product.receipt);
- var detailsReceipt = JsonConvert.DeserializeObject<Dictionary<string, object>>((string)receiptData["Payload"]);
- var request = new PlayFab.ClientModels.ValidateGooglePlayPurchaseRequest();
- request.ReceiptJson = (string)detailsReceipt["json"];
- request.Signature = (string)detailsReceipt["signature"];
- request.PurchasePrice = Convert.ToUInt32(product.metadata.localizedPrice * 100);
- request.CurrencyCode = product.metadata.isoCurrencyCode;
- PlayFab.PlayFabClientAPI.ValidateGooglePlayPurchase(request,
- delegate (PlayFab.ClientModels.ValidateGooglePlayPurchaseResult result)
- {
- AnalyticsManager.Instance.TrackSuccessfulIAP();
- UpdateSuccessPurchase(product.definition.id, -1);
- storeController.ConfirmPendingPurchase(product);
- },
- delegate (PlayFab.PlayFabError error)
- {
- string errorMessage = error.ErrorMessage;
- Debug.LogWarningFormat("<b><color=red>{0}</color></b>", "ValidateGooglePlayPurchase() " + errorMessage);
- isPurchasing = false;
- storeController.ConfirmPendingPurchase(product);
- });
- }
- public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
- {
- if (failureReason == PurchaseFailureReason.UserCancelled && _OnCancel != null)
- {
- _OnCancel();
- }
- else if (_OnFail != null)
- {
- _OnFail();
- }
- PlatformUtil.ShowAlert("Purchase Error", failureReason.ToString());
- Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
- isPurchasing = false;
- }
- public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
- {
- storeController = controller;
- storeExtensionProvider = extensions;
- foreach(var product in storeController.products.all)
- {
- var inapp = InApps.ALL_INAPPS.Find(obj => obj.ProductID == product.definition.id);
- if (inapp != null)
- {
- inapp.Price = product.metadata.localizedPrice.ToString();
- inapp.CurrencyCode = product.metadata.isoCurrencyCode;
- inapp.Description = product.metadata.localizedDescription;
- inapp.FormattedPrice = product.metadata.localizedPriceString;
- inapp.TitleLocalizationKey = product.metadata.localizedTitle;
- }
- }
- AdsManager.Instance.Initialize();
- StartCoroutine(test());
- }
- public void OnInitializeFailed(InitializationFailureReason error)
- {
- Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
- AdsManager.Instance.Initialize();
- }
- IEnumerator test()
- {
- while (true)
- {
- if (Advertisement.IsReady("testPlacement"))
- {
- Advertisement.Show("testPlacement");
- yield break;
- }
- yield return new WaitForSeconds(1);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment