Untitled
unknown
plain_text
a month ago
8.8 kB
0
Indexable
Never
using System; using System.Collections.Generic; using Unity.Services.Core; using Unity.Services.Core.Environments; using UnityEngine; using UnityEngine.Purchasing; using UnityEngine.Purchasing.Extension; public class IAPManager : MonoBehaviour, IStoreListener, IDetailedStoreListener { // Start is called before the first frame update private string[] _productId = { "draw_bridge_noads", // id package đã tạo trên AppStoreconnect }; private IStoreController m_StoreController; private IExtensionProvider m_StoreExtensionProvider; private IGooglePlayStoreExtensions m_GoogleExtensions; private IAppleExtensions m_AppleExtensions; private ConfigurationBuilder builder; private bool _isNoAds = false; private Action _iapCallback = null; public bool IsHasBuyNoAdsBefore = false; public string environment = "production"; public bool GetIsNoAds { get { return _isNoAds; } } private async void Start() { try { var options = new InitializationOptions() .SetEnvironmentName(environment); await UnityServices.InitializeAsync(options); InitializePurchasing(); } catch (Exception) { // An error occurred during initialization. } } private bool IsInitialized() { if (m_StoreController == null) { Debug.Log("Store Controller is null"); } if (m_StoreExtensionProvider == null) { Debug.Log("Store ExtensionProvider is null"); } return m_StoreController != null && m_StoreExtensionProvider != null; } private void InitializePurchasing() { // Debug.Log("") if (IsInitialized()) return; builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance()); // add all product in builder builder.AddProduct(_productId[0], ProductType.NonConsumable); Debug.Log("Starting Initialized..."); UnityPurchasing.Initialize(this, builder); Debug.Log("End Initialized..."); } public void RestorePurchases() { if (!IsInitialized()) { return; } if (UserData.Instance.IsNoAds) { UIManager.Instance.ShowToast("You have already purchased this package!"); return; } if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer) { //Debug.Log("RestorePurchases started ..."); var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>(); apple.RestoreTransactions((result, _messege) => { if (result) { Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore."); foreach (var item in m_StoreController.products.all) { OnPurchaseComplete(item); } } else { UIManager.Instance.ShowToast("You have not purchased any packages yet"); } }); } else { Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform); } } public void OnInitialized(IStoreController controller, IExtensionProvider extensions) { m_StoreController = controller; m_StoreExtensionProvider = extensions; if (controller.products.WithID(_productId[0]).hasReceipt) { _isNoAds = true; } if (!_isNoAds) { Debug.Log("IAP =====> Did not buy No Ads"); // MediationManager.Instance.ConfigForNoAds(); } else { Debug.Log("IAP =====> Bought No Ads"); } foreach (UnityEngine.Purchasing.Product item in controller.products.all) { if (item.receipt != null) { //string intro_json = (dict == null || !dict.ContainsKey(item.definition.storeSpecificId)) ? null : dict[item.definition.storeSpecificId]; if (item.definition.type == ProductType.Subscription) { SubscriptionManager p = new SubscriptionManager(item, null); SubscriptionInfo info = p.getSubscriptionInfo(); Debug.Log("SubInfo: " + info.getProductId().ToString()); Debug.Log("getExpireDate: " + info.getExpireDate().ToString()); Debug.Log("isSubscribed: " + info.isSubscribed().ToString()); //string time = PlayerPrefs.GetString(ConfigsTIMEOVER_NOADS, string.Empty); //if (time == null) { // time = info.getExpireDate().ToString(); // PlayerPrefs.SetString(Configs.TIMEOVER_NOADS, time); //} } } } Debug.Log($"====> IAP Initilize successfully! IsPurchasedNodAds {_isNoAds}"); } public void OnPurchaseComplete(Product product) { if (product.hasReceipt) { UIManager.Instance.ShowRestoreView(); } else { UIManager.Instance.ShowToast("You have not purchased any packages yet"); } } public void RestorePack() { UserData.Instance.IsNoAds = true; MediationManager.Instance.ShowBanner(false); UIManager.Instance.ShowToast("Restore Successful"); } public void CompletePurchase(Config.IAP_PRODUCT productType, Action callback) { if (IsInitialized()) { Debug.Log("productId : " + _productId[(int)productType].ToString()); UnityEngine.Purchasing.Product product = m_StoreController.products.WithID(_productId[(int)productType]); if (product != null && product.availableToPurchase) { Debug.Log(string.Format("Purchasing product:" + product.definition.id.ToString())); m_StoreController.InitiatePurchase(product); _iapCallback = callback; } else { _iapCallback = null; Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase"); } } else { Debug.Log("BuyProductID FAIL. Not initialized."); } } private void LogAFPurchase(Product product) { double price = (double)product.metadata.localizedPrice; price *= 0.8; Dictionary<string, string> eventValues = new Dictionary<string, string>(); eventValues.Add(AFInAppEvents.CURRENCY, product.metadata.isoCurrencyCode); eventValues.Add(AFInAppEvents.REVENUE, price.ToString()); eventValues.Add(AFInAppEvents.QUANTITY, "1"); eventValues.Add("product_id", product.definition.id); SDKManager.PushAFEventIAP(AFInAppEvents.PURCHASE, eventValues); } public void OnPurchaseFailed(Product product, PurchaseFailureReason error) { Debug.Log($"Purchase Failed! Product: {product.definition.id}, error {error}"); _iapCallback = null; } public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription) { Debug.Log($"Purchase Failed! Product: {product.definition.id}, error {failureDescription}"); // UIManager.Instance._shopPopup.SetIsClickBtn = false; _iapCallback = null; } public void OnInitializeFailed(InitializationFailureReason error) { Debug.Log($"====> IAP Initilize Failed: {error}"); } public void OnInitializeFailed(InitializationFailureReason error, string message) { Debug.Log($"====> IAP Initilize Failed:{error}, message : {message} "); } public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) { Debug.Log("process purchase"); if (args == null) { Debug.Log("args process is null"); } if (String.Equals(args.purchasedProduct.definition.id, _productId[0], StringComparison.Ordinal)) { } if (_iapCallback != null) { Debug.Log("go to callback of process purchase"); _iapCallback(); _iapCallback = null; } LogAFPurchase(args.purchasedProduct); return PurchaseProcessingResult.Complete; } public string GetPricePack() { if (m_StoreController == null) return null; UnityEngine.Purchasing.Product product = m_StoreController.products.WithID(_productId[0]); if (product == null) return null; return product.metadata.localizedPriceString; } }
Leave a Comment