Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
11 kB
3
Indexable
Never
using BravestarsSDK;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Unity.Services.Core;
using Unity.Services.Core.Environments;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Extension;
using UnityEngine.Purchasing.Security;

public class IAPManager : MonoBehaviour, IStoreListener, IDetailedStoreListener {
    // Start is called before the first frame update
    private string[] _productId = {
        "draw_bridge_noads",
    };

    private IStoreController m_StoreController;
    private IExtensionProvider m_StoreExtensionProvider;
    private IGooglePlayStoreExtensions m_GoogleExtensions;
    private IAppleExtensions m_AppleExtensions;
    private ConfigurationBuilder builder;

    private Action _iapCallback = null;
    public bool IsHasBuyNoAdsBefore = false;
    private bool _isNoAds = false;
    public string environment = "production";
    private bool _purcharseBefore = false; 
    public bool GetIsNoAds {
        get {
            return _isNoAds;
        }
    }
    private Coroutine _action;
    public void SetNoAds() {
        _isNoAds = true;
    }


    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() {
        if (IsInitialized())
            return;

        builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
        builder.AddProduct(_productId[0], ProductType.NonConsumable);

        Debug.Log("Starting Initialized...");
        UnityPurchasing.Initialize(this, builder);
        Debug.Log("End Initialized...");
        Debug.Log("purcharseBefore : " + _purcharseBefore);
    }

    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");
        } else {
            Debug.Log("IAP =====> Bought No Ads");
            MediationManager.Instance.ShowBanner(false);
            UserData.Instance.IsNoAds = true;
        }
        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());
                }
            }
        }

        Debug.Log($"====> IAP Initilize successfully! IsPurchasedNodAds {_isNoAds}");
    }

    public void OnPurchaseComplete(Product product) {
        if (product.hasReceipt) {
            RestorePack();
        } else {
            UIManager.Instance.ShowToast("You have not purchased any packages yet");
        }
    }
    public void RestorePack() {
        UserData.Instance.IsNoAds = true;
        GameController.Instance.CheckBtnNoAds();
        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());
            MediationManager.IsSkipResumeAds = true;
            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);
                if (product.hasReceipt)
                {
                    _purcharseBefore = true;
                    Debug.Log("tuan anh purchasing " + _purcharseBefore);
                }
                _iapCallback = callback;
            } else {
                _iapCallback = null;
                Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
                SDKManager.AddTrackingEvent("IAP_Fail");
            }

        } else {
            Debug.Log("BuyProductID FAIL. Not initialized.");
            SDKManager.AddTrackingEvent("IAP_Fail");
        }
    }
    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);
        SDKManager.AddTrackingEvent("Log_AF_Purchased_IAP");
    }
    public void OnPurchaseFailed(Product product, PurchaseFailureReason error) {
        Debug.Log($"Purchase Failed! Product: {product.definition.id}, error {error}");
        SDKManager.AddTrackingEvent("IAP_Fail");
        MediationManager.IsSkipResumeAds = true;
        _iapCallback = null;
        try {
            NoAdsPopup.IsClickedBtn = false;

        } catch (Exception) {

        }
    }
    public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription) {
        Debug.Log($"Purchase Failed! Product: {product.definition.id}, error {failureDescription}");
        SDKManager.AddTrackingEvent("IAP_Fail");
        MediationManager.IsSkipResumeAds = true;
        // UIManager.Instance._shopPopup.SetIsClickBtn = false;
        _iapCallback = null;
        try {
            NoAdsPopup.IsClickedBtn = false;

        } catch (Exception) {

        }
    }

    public void OnInitializeFailed(InitializationFailureReason error) {
        MediationManager.IsSkipResumeAds = true;
        Debug.Log($"====> IAP Initilize Failed: {error}");
    }

    public void OnInitializeFailed(InitializationFailureReason error, string message) {
        MediationManager.IsSkipResumeAds = true;
        Debug.Log($"====> IAP Initilize Failed:{error}, message : {message} ");
    }
    DateTime timeFirstPurchase;

    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        MediationManager.IsSkipResumeAds = true;
        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();
    
            var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
            IPurchaseReceipt[] result = validator.Validate(args.purchasedProduct.receipt);
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log("TA productID :" + productReceipt.productID);
                timeFirstPurchase = productReceipt.purchaseDate;
                
                Debug.Log("TA purchaseDate: " + timeFirstPurchase);
                Debug.Log("TA + transactionID: "+productReceipt.transactionID);
                AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                if (null != apple)
                {
                    Debug.Log("TA originalTransactionIdentifier: "+apple.originalTransactionIdentifier);
                    Debug.Log("TA subscriptionExpirationDate: " +apple.subscriptionExpirationDate);
                    Debug.Log("TA cancellationDate: " +apple.cancellationDate);
                    Debug.Log("TA quantity: "+apple.quantity);
                }
            }
            Debug.Log("TA + utc Now " + DateTime.UtcNow);
            if (timeFirstPurchase >= DateTime.UtcNow.AddMinutes(-15f))
            {
                LogAFPurchase(args.purchasedProduct);
            }
            else
            {
                Debug.Log("tuan anh k log event AF");
            }
            _iapCallback = null;
        }
        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;
    }
    public void OnDestroy()
    {
        if(_action != null)
        StopCoroutine(_action);
    }
}
Leave a Comment