コード例 #1
0
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            Product product = e.purchasedProduct;

            Debug.Log($"{product.metadata.localizedTitle}");

          #if UNITY_ANDROID || UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_TVOS
            var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                       AppleTangle.Data(), Application.identifier);

            try {
                var result = validator.Validate(e.purchasedProduct.receipt);

                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);
                }
            } catch (IAPSecurityException) {
                Debug.Log("Invalid receipt, not unlocking content");
                return(PurchaseProcessingResult.Complete);
            }
          #endif

            StartCoroutine(DoPurchase(product));
            return(PurchaseProcessingResult.Pending);
        }
コード例 #2
0
    /// <summary>
    /// Called when a purchase completes.
    ///
    /// May be called at any time after OnInitialized().
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        PurchaseInProgress = false;
        Loading.Instance.Hide();

        try
        {
            var result   = validator.Validate(args.purchasedProduct.receipt);
            var products = new List <string>();

            foreach (IPurchaseReceipt productReceipt in result)
            {
                if (args.purchasedProduct.transactionID == productReceipt.transactionID)
                {
                    products.Add(productReceipt.productID);
                }
            }

            if (!products.Contains(LastPurchaseProductId))
            {
                return(PurchaseProcessingResult.Complete);
            }

            return(ProcessPurchase(args.purchasedProduct.definition.id));
        }
        catch (IAPSecurityException ex)
        {
            return(PurchaseProcessingResult.Complete);
        }
    }
コード例 #3
0
        public static bool IsProductReceiptValid(Product product)
        {
            if (product == null)
            {
                return(false);
            }

#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
            var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
            try {
                var result = validator.Validate(product.receipt);
                UDBG.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    UDBG.Log(productReceipt.productID);
                    UDBG.Log(productReceipt.purchaseDate);
                    UDBG.Log(productReceipt.transactionID);
                }
            } catch (IAPSecurityException exception) {
                UDBG.Log("Invalid receipt not unlcokded content".Attrib(bold: true, italic: true, color: "r"));
                return(false);
            }
#endif
            return(true);
        }
コード例 #4
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        bool success = true;
        // 아래 소스코드는 안드로이드(Android)에서 실행했을 때에만 정상적으로 동작합니다.
        CrossPlatformValidator validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);

        try
        {
            // 앱상에서 구매한 물품에 대하여 결제 처리를 진행합니다.
            IPurchaseReceipt[] result = validator.Validate(e.purchasedProduct.receipt);
            for (int i = 0; i < result.Length; i++)
            {
                Analytics.Transaction(productID, e.purchasedProduct.metadata.localizedPrice, e.purchasedProduct.metadata.isoCurrencyCode);
            }
        }
        catch (IAPSecurityException ex)
        {
            // 유니티 에디터에서 실행하는 경우 오류가 발생합니다.
            Debug.Log("오류 발생: " + ex.Message);
            success = false;
        }
        if (success)
        {
            text.text = "결제 완료";
        }
        else
        {
            text.text = "결제 실패";
        }
        return(PurchaseProcessingResult.Complete);
    }
コード例 #5
0
ファイル: IAPManager.cs プロジェクト: wllmwu/2020-snake-cubed
    ///<summary>Returns whether the given IAP receipt a) is a valid receipt and b) contains the given product ID.
    /// The receipt string must be formatted as a Unity IAP receipt.
    /// IMPORTANT: Only call this method when running on iOS or Android. Otherwise, perhaps assume the receipt is valid.</summary>
    private static bool validateReceipt(string receipt, string intendedProductID)
    {
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);

        try {
            var  result     = validator.Validate(receipt); // checks whether the receipt is valid, throws if not
            bool foundMatch = false;
            foreach (IPurchaseReceipt productReceipt in result)
            {
                // user may provide a "valid" receipt from somewhere else, so look for the ID of the intended product
                if (productReceipt.productID.Equals(intendedProductID))
                {
                    foundMatch = true;
                    break;
                }
            }
            return(foundMatch);
        }
        catch (IAPSecurityException) {
            Debug.Log("invalid receipt");
            return(false);
        }
        catch (System.Exception) {
            Debug.Log("something bad happened while validating receipt");
            return(false);
        }
    }
コード例 #6
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        bool isSuccess = true;
        //#if UNITY_ANDROID && !UNITY_EDITOR
        CrossPlatformValidator validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);

        try
        {
            IPurchaseReceipt[] result = validator.Validate(e.purchasedProduct.receipt);
            for (int i = 0; i < result.Length; i++)
            {
                Analytics.Transaction(result[i].productID, e.purchasedProduct.metadata.localizedPrice,
                                      e.purchasedProduct.metadata.isoCurrencyCode,
                                      result[i].transactionID, null);
            }
        }
        catch (IAPSecurityException)
        {
            isSuccess = false;
        }
        //#endif
        if (isSuccess)
        {
            Debug.Log("구매 완료");
            BuyNoAds();
        }
        else
        {
            Debug.Log("구매 실패 : 비정상 결제");
        }

        return(PurchaseProcessingResult.Complete);
    }
コード例 #7
0
        PurchaseProcessingResult IStoreListener.ProcessPurchase(PurchaseEventArgs args)
        {
            if (googleTangleData == null)
            {
                Debug.Log($" ***** ProcessGooglePurchase   googleTangleData IS NULL");
                OnPurchased?.Invoke(PurchaseResponse.Ok, args.purchasedProduct);
                return(PurchaseProcessingResult.Complete);
            }

            // validate receipt.
            try {
                Debug.Log($" ***** ProcessAmazonPurchase   validate receipt.");
                var validator = new CrossPlatformValidator(googleTangleData, null, Application.identifier);
                // On Google Play, result has a single product ID.
                // On Apple stores, receipts contain multiple products.
                var result = validator.Validate(args.purchasedProduct.receipt);
    #if DEBUG_IAP
                // For informational purposes, we list the receipt(s)
                foreach (IPurchaseReceipt receipt in result)
                {
                    var sb = new StringBuilder("Purchase Receipt Details:");
                    sb.Append($"\n  Product ID: {receipt.productID}");
                    sb.Append($"\n  Purchase Date: {receipt.purchaseDate}");
                    sb.Append($"\n  Transaction ID: {receipt.transactionID}");
                    Debug.Log(sb);
                }
    #endif
                OnPurchased?.Invoke(PurchaseResponse.Ok, args.purchasedProduct);
            } catch (IAPSecurityException err) {
                Debug.Log($"Invalid receipt or security exception: {err.Message}");
                OnPurchased?.Invoke(PurchaseResponse.InvalidReceipt, args.purchasedProduct);
            }

            return(PurchaseProcessingResult.Complete);
        }
コード例 #8
0
    bool ValidateReceipt(PurchaseEventArgs e)
    {
#if UNITY_EDITOR
        return(true);

        // Unity IAP's validation logic is only included on these platforms.
#elif UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
        // Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                   AppleTangle.Data(), Application.bundleIdentifier);

        try
        {
            // On Google Play, result will have a single product Id.
            // On Apple stores receipts contain multiple products.
            var result = validator.Validate(e.purchasedProduct.receipt);
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log(productReceipt.productID);
                Debug.Log(productReceipt.purchaseDate);
                Debug.Log(productReceipt.transactionID);
            }
            // Unlock the appropriate content here.
            return(true);
        }
        catch (IAPSecurityException)
        {
            Debug.Log("Invalid receipt, not unlocking content");
            return(false);
        }
#endif
    }
コード例 #9
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs evt)
    {
        try
        {
            bool flag = false;
            // CrossPlatformValidator crossPlatformValidator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
            CrossPlatformValidator crossPlatformValidator = new CrossPlatformValidator(null, null, Application.identifier);
            IPurchaseReceipt[]     array = crossPlatformValidator.Validate(evt.purchasedProduct.receipt);
            for (int i = 0; i < array.Count(); i++)
            {
                IPurchaseReceipt productReceipt = array[i];
                if (productReceipt.productID == evt.purchasedProduct.definition.storeSpecificId && PersistentSingleton <Economies> .Instance.IAPs.Find((IAPConfig iap) => iap.ProductID == productReceipt.productID) != null)
                {
                    flag = true;
                }
            }
            IAPConfig iAPConfig = PersistentSingleton <Economies> .Instance.IAPs.Find((IAPConfig iap) => iap.ProductID == evt.purchasedProduct.definition.storeSpecificId);

            if (flag && iAPConfig != null)
            {
                IAPValidated.Value = new IAPTransactionState(iAPConfig, evt.purchasedProduct, evt.purchasedProduct.receipt);
            }
            if (!flag)
            {
                IAPInvalidated.SetValueAndForceNotify(value: true);
            }
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.LogWarning("Invalid receipt - " + ex.Message);
        }
        PurchaseInProgress.SetValueAndForceNotify(value: false);
        GiveIAPToUser(evt.purchasedProduct);
        return(PurchaseProcessingResult.Complete);
    }
コード例 #10
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        Debug.Log(string.Format("[InPurchase] ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));

        if (!storeData.isStoreClick)
        {
            return(PurchaseProcessingResult.Complete);
        }

        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                   AppleTangle.Data(), Application.identifier);

        try {
            var result = validator.Validate(args.purchasedProduct.receipt);

            Debug.Log("Receipt is valid. Contents:");

            foreach (IPurchaseReceipt productReceipt in result)
            {
                GooglePlayReceipt google = productReceipt as GooglePlayReceipt;

                if (null != google)
                {
                    validationIAB(args.purchasedProduct.definition.id, google.purchaseToken);
                }
            }
        } catch (IAPSecurityException) {
            Debug.Log("Invalid receipt, not unlocking content");
        }

        return(PurchaseProcessingResult.Complete);
    }
コード例 #11
0
    private static bool ClientSideReceiptValidation(string unityIapReceipt)
    {
        bool validPurchase = true;

#if UNITY_ANDROID
        // Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                   AppleTangle.Data(), Application.identifier);

        try
        {
            // Validate the signature of the receipt with unity cross platform validator
            var result = validator.Validate(unityIapReceipt);

            // Validate the obfuscated account id of the receipt.
            ObfuscatedAccountIdValidation(unityIapReceipt);

            // For informational purposes, we list the receipt(s).
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log(productReceipt.productID);
                Debug.Log(productReceipt.purchaseDate);
                Debug.Log(productReceipt.transactionID);
            }
        }
        catch (IAPSecurityException)
        {
            Debug.Log("Invalid receipt, not unlocking content");
            validPurchase = false;
        }
#endif
        return(validPurchase);
    }
コード例 #12
0
    public bool CheckHistory()
    {
#if UNITY_EDITOR
        Product product = m_StoreController.products.WithID(productId);
        Return product.hasReceipt;
#elif UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
        Product product = m_StoreController.products.WithID(productId);
        // Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                   AppleTangle.Data(), Application.Identifier);

        try {
            // On Google Play, result will have a single product Id.
            // On Apple stores receipts contain multiple products.
            var result = validator.Validate(product.receipt);
            // For informational purposes, we list the receipt(s)
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log(productReceipt.productID);
                Debug.Log(productReceipt.purchaseDate);
                Debug.Log(productReceipt.transactionID);
            }
        } catch (IAPSecurityException) {
            Debug.Log("Invalid receipt, not unlocking content");
            validPurchase = false;
        }
#endif
    }
コード例 #13
0
    /// <summary>
    /// Receipt validation method
    /// </summary>
    /// <param name="productName"></param>
    /// <param name="receipt"></param>
    /// <param name="exception"></param>
    /// <returns>true if receipt is valid</returns>
    bool ReceiptIsValid(string productName, string receipt, out IAPSecurityException exception)
    {
        exception = null;
        bool validPurchase = true;

#if GleyUseValidation
#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
        CrossPlatformValidator validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);

        try
        {
            validator.Validate(receipt);
            if (debug)
            {
                Debug.Log(this + " Receipt is valid for " + productName);
                ScreenWriter.Write(this + " Receipt is valid for " + productName);
            }
        }
        catch (IAPSecurityException ex)
        {
            exception = ex;
            if (debug)
            {
                Debug.Log(this + " Receipt is NOT valid for " + productName);
                ScreenWriter.Write(this + " Receipt is NOT valid for " + productName);
            }
            validPurchase = false;
        }
#endif
#endif
        return(validPurchase);
    }
コード例 #14
0
ファイル: IAPManager.cs プロジェクト: HOBOOK/Flat-Heroes
    PurchaseProcessingResult IStoreListener.ProcessPurchase(PurchaseEventArgs e)
    {
        bool isSuccess = true;

#if UNITY_ANDROID && !UNITY_EDITOR
        CrossPlatformValidator validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
        try
        {
            IPurchaseReceipt[] result = validator.Validate(e.purchasedProduct.receipt);
            for (int i = 0; i < result.Length; i++)
            {
                Analytics.Transaction(result[i].productID, e.purchasedProduct.metadata.localizedPrice, e.purchasedProduct.metadata.isoCurrencyCode, result[i].transactionID, null);
            }
        }
        catch (IAPSecurityException)
        {
            isSuccess = false;
        }
#endif
        if (isSuccess)
        {
            Debug.Log("구매 완료");
            if (e.purchasedProduct.definition.id.Equals(sProductIds[0]))
            {
                SuccessPurchase(buyItemId);
            }
            else if (e.purchasedProduct.definition.id.Equals(sProductIds[1]))
            {
                SuccessPurchase(buyItemId);
            }
            else if (e.purchasedProduct.definition.id.Equals(sProductIds[2]))
            {
                SuccessPurchase(buyItemId);
            }
            else if (e.purchasedProduct.definition.id.Equals(sProductIds[3]))
            {
                SuccessPurchase(buyItemId);
            }
            else if (e.purchasedProduct.definition.id.Equals(sProductIds[4]))
            {
                SuccessPurchase(buyItemId);
            }
            else if (e.purchasedProduct.definition.id.Equals(sProductIds[5]))
            {
                SuccessPurchase(buyItemId);
            }
            else if (e.purchasedProduct.definition.id.Equals(sProductIds[6]))
            {
                SuccessPurchase(buyItemId);
            }
        }
        else
        {
            Debug.Log("구매 실패 : 비정상 결제");
        }

        return(PurchaseProcessingResult.Complete);
    }
コード例 #15
0
            public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
            {
                Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
                Debug.Log("Receipt: " + e.purchasedProduct.receipt);

                m_LastTransationID = e.purchasedProduct.transactionID;
                m_LastReceipt      = e.purchasedProduct.receipt;

                                #if RECEIPT_VALIDATION
                // Local validation is available for GooglePlay and Apple stores
                if (m_IsGooglePlayStoreSelected ||
                    Application.platform == RuntimePlatform.IPhonePlayer ||
                    Application.platform == RuntimePlatform.OSXPlayer ||
                    Application.platform == RuntimePlatform.tvOS)
                {
                    try {
                        var result = validator.Validate(e.purchasedProduct.receipt);
                        Debug.Log("Receipt is valid. Contents:");
                        foreach (IPurchaseReceipt productReceipt in result)
                        {
                            Debug.Log(productReceipt.productID);
                            Debug.Log(productReceipt.purchaseDate);
                            Debug.Log(productReceipt.transactionID);

                            GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                            if (null != google)
                            {
                                Debug.Log(google.purchaseState);
                                Debug.Log(google.purchaseToken);
                            }

                            AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                            if (null != apple)
                            {
                                Debug.Log(apple.originalTransactionIdentifier);
                                Debug.Log(apple.subscriptionExpirationDate);
                                Debug.Log(apple.cancellationDate);
                                Debug.Log(apple.quantity);
                            }
                        }
                    } catch (IAPSecurityException) {
                        Debug.Log("Invalid receipt, not unlocking content");
                        return(PurchaseProcessingResult.Complete);
                    }
                }
                                #endif

                foreach (var button in activeButtons)
                {
                    if (button.productId == e.purchasedProduct.definition.id)
                    {
                        return(button.ProcessPurchase(e));
                    }
                }

                return(PurchaseProcessingResult.Complete);                // TODO: Maybe this shouldn't return complete
            }
コード例 #16
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        bool   validPurchase = true; // Presume valid for platforms with no R.V.
        string id            = e.purchasedProduct.definition.id;

        // Unity IAP's validation logic is only included on these platforms.
#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
        //Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                   AppleTangle.Data(), Application.identifier);

        try
        {
            // On Google Play, result has a single product ID.
            // On Apple stores, receipts contain multiple products.
            var result = validator.Validate(e.purchasedProduct.receipt);
            // For informational purposes, we list the receipt(s)
            // foreach (IPurchaseReceipt productReceipt in result)
            // {
            //     Debug.Log(productReceipt.productID);
            //     Debug.Log(productReceipt.purchaseDate);
            //     Debug.Log(productReceipt.transactionID);
            // }
        }
        catch (IAPSecurityException)
        {
            UIController.Instance.PushHint("IAPSecurityException", "购买验证失败");
            validPurchase = false;
        }
#endif
//#if UNITY_IOS
//        if (productIdEx != "_huifu" && productIdEx != id)
//        {
//            UIController.Instance.PushHint("IAPSecurityException", "购买验证失败");
//            validPurchase = false;
//        }
//#elif UNITY_ANDROID
//        if (productIdEx != "" && productIdEx != id)
//        {
//            UIController.Instance.PushHint("IAPSecurityException", "购买验证失败");
//            validPurchase = false;
//        }
//#endif

        if (validPurchase)
        {
            SendCallBack(true, id);
        }
        else
        {
            SendCallBack(false, id);
        }

        return(PurchaseProcessingResult.Complete);
    }
コード例 #17
0
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
        {
            // Unity IAP's validation logic is only included on these platforms.
                        #if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
            // Prepare the validator with the secrets we prepared in the Editor
            // obfuscation window.
            var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                       AppleTangle.Data(), Application.bundleIdentifier);

            try {
                // On Google Play, result will have a single product Id.
                // On Apple stores receipts contain multiple products.
                var result = validator.Validate(args.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);
                }
                // Unlock the appropriate content here.
            } catch (IAPSecurityException) {
                Debug.LogError("Invalid receipt, not unlocking content");
            }
                        #endif

            //@Angelo: here is the result of a successful purchase of a consumable (100 coins, in our case), in the Editor once you press the "Buy" button you'll immediately see the
            //"ProcessPurchase: PASS" message on the Console. On a device you would see the OS pop-up confirming the purchase
            // A consumable product has been purchased by this user.
            if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal))
            {
                Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));                //If the consumable item has been successfully purchased, add 100 coins to the player's in-game score.ScoreManager.score += 100;
                // ここに消費アイテムを買った時の処理を入れる
                PlayerPrefs.SetInt("CoinNum", PlayerPrefs.GetInt("CoinNum") + 100);
                GameObject.Find("CoinNumUI").GetComponent <ScoreManager>().UpdateCoin();
            }

            //@Angelo: Same here for a non-consumable (in our chase, the old lady character)
            // Or ... a non-consumable product has been purchased by this user.
            else if (String.Equals(args.purchasedProduct.definition.id, kProductIDNonConsumable, StringComparison.Ordinal))
            {
                Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
                // ここに非消費アイテムを買った時の処理を入れる
                PlayerPrefs.SetInt("NewCharaUnlocked", 1);
            }            // Or ... a subscription product has been purchased by this user.
            else if (String.Equals(args.purchasedProduct.definition.id, kProductIDSubscription, StringComparison.Ordinal))
            {
                Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
            }                                                                                                                           // Or ... an unknown product has been purchased by this user. Fill in additional products here.
            else
            {
                Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
            }                                                                                                                                        // Return a flag indicating wither this product has completely been received, or if the application needs to be reminded of this purchase at next app launch. Is useful when saving purchased products to the cloud, and when that save is delayed.
            return(PurchaseProcessingResult.Complete);
        }
コード例 #18
0
ファイル: IAP.cs プロジェクト: cankarakuzulu/PTBTemp
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            var productID = e.purchasedProduct.definition.id;

            // Validate receipts using obfuscated keys. (Local validation)
            // Read more: https://docs.unity3d.com/Manual/UnityIAPValidatingReceipts.html
            // or ask <*****@*****.**>.

            bool validPurchase = false;

            var validator = new CrossPlatformValidator(
                GooglePlayTangle.Data(),
                AppleTangle.Data(),
                Application.identifier);

#if UNITY_EDITOR
            if (isDebugging)
            {
                Debug.Log("[IAP] Receipt validation is skipped on editor.");
            }
            validPurchase = true;
#else
            try
            {
                var result = validator.Validate(e.purchasedProduct.receipt);

                System.Text.StringBuilder resultStringBuilder = new System.Text.StringBuilder();
                resultStringBuilder.Append("[IAP] Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    resultStringBuilder.AppendFormat(
                        "\n id: {0} date: {1} transactionID:{2} ",
                        productReceipt.productID,
                        productReceipt.purchaseDate,
                        productReceipt.transactionID
                        );
                }

                if (isDebugging)
                {
                    Debug.Log(resultStringBuilder.ToString());
                }
                validPurchase = true;
            }
            catch (IAPSecurityException)
            {
                Debug.LogWarning("Invalid receipt, not unlocking content");
                validPurchase = false;
            }
#endif

            listener.OnPurchaseResult(validPurchase, productID, e.purchasedProduct.transactionID);
            return(PurchaseProcessingResult.Complete);
        }
コード例 #19
0
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEventArgs)
        {
            log.Debug(nameof(ProcessPurchase));
            string receipt = purchaseEventArgs.purchasedProduct.receipt;

            bool   purchaseIsValid = true;
            string sku             = purchaseEventArgs.purchasedProduct.definition.id;
            string token           = null;


#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
            CrossPlatformValidator validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                                          AppleTangle.Data(), Application.identifier);

            purchaseEventArgs.purchasedProduct.LogProduct(log);

            try
            {
                IPurchaseReceipt[] result = validator.Validate(purchaseEventArgs.purchasedProduct.receipt);

                log.Debug("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    log.Debug(productReceipt.productID);
                    log.Debug(productReceipt.purchaseDate.ToString());
                    log.Debug(productReceipt.transactionID);
                    if (productReceipt is GooglePlayReceipt google)
                    {
                        log.Debug(google.transactionID);
                        log.Debug(google.purchaseState.ToString());
                        log.Debug(google.purchaseToken);
                        token = google.purchaseToken;
                    }
                }
            }
            catch (IAPSecurityException)
            {
                log.Error("Invalid receipt, not unlocking content");
                purchaseIsValid = false;
            }
            catch (Exception e)
            {
                log.Error(e.Message + " " + e.StackTrace);
            }
#endif
            if (!purchaseIsValid)
            {
                log.Fatal($"Покупка не прошла локальную проверку");
                UiSoundsManager.Instance().PlayError();
            }

            serverValidator.StartValidation(sku, token);
            return(PurchaseProcessingResult.Pending);
        }
コード例 #20
0
ファイル: IAPManager.cs プロジェクト: lipnus/musicGame
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            bool isSuccess = true;


            #if UNITY_ANDROID && !UNITY_EDITOR
            CrossPlatformValidator validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                                          AppleTangle.Data(), Application.identifier);

            try {
                IPurchaseReceipt[] result = validator.Validate(e.purchasedProduct.receipt);
                for (int i = 0; i < result.Length; i++)
                {
                    Analytics.Transaction(result[i].productID, e.purchasedProduct.metadata.localizedPrice,
                                          e.purchasedProduct.metadata.isoCurrencyCode, result[i].transactionID, null);
                }
            }
            catch (IAPSecurityException) {
                isSuccess = false;
            }
            #endif


            if (isSuccess == false)
            {
                Debug.Log("인앱결제 isSuccess==false");
            }


            if (isSuccess == true)
            {
                Debug.Log("구매완료");

                if (e.purchasedProduct.definition.id.Equals(sProductIds[0])) //샤넬 넘버5
                {
                    buyNumber5();
                }
                else if (e.purchasedProduct.definition.id.Equals(sProductIds[1])) //에어팟
                {
                    buyAirPods();
                }
                else if (e.purchasedProduct.definition.id.Equals(sProductIds[2]))   //스벅텀블러
                {
                    buyTumbler();
                }
                else if (e.purchasedProduct.definition.id.Equals(sProductIds[3]))   //정관장 홍삼정
                {
                    buyRedGinseng();
                }
            }

            return(PurchaseProcessingResult.Complete);
        }
コード例 #21
0
    /// <summary>
    /// This will be called when a purchase completes.
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
        Debug.Log("Receipt: " + e.purchasedProduct.receipt);

        m_PurchaseInProgress = false;

        // Now that my purchase history has changed, update its UI
        UpdateHistoryUI();

                #if RECEIPT_VALIDATION
        if (Application.platform == RuntimePlatform.Android ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }
                }
            } catch (IAPSecurityException) {
                Debug.Log("Invalid receipt, not unlocking content");
                return(PurchaseProcessingResult.Complete);
            }
        }
                #endif

        // You should unlock the content here.

        // Indicate we have handled this purchase, we will not be informed of it again.x
        return(PurchaseProcessingResult.Complete);
    }
コード例 #22
0
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            var iapProduct = IAPController.Instance.GetProduct(e.purchasedProduct.definition.id);

            if (iapProduct != null)
            {
                var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
                var valid     = false;
                try
                {
                    var result = validator.Validate(e.purchasedProduct.receipt);
                    foreach (IPurchaseReceipt receipt in result)
                    {
#if UNITY_ANDROID || UNITY_STANDALONE
                        var google = receipt as GooglePlayReceipt;
                        if (null != google)
                        {
                            Debug.Log(google.transactionID);
                            Debug.Log(google.purchaseState);
                            Debug.Log(google.purchaseToken);
                        }
#elif UNITY_IOS
                        AppleInAppPurchaseReceipt apple = receipt as AppleInAppPurchaseReceipt;
                        if (null != apple)
                        {
                            Debug.Log(apple.originalTransactionIdentifier);
                            Debug.Log(apple.subscriptionExpirationDate);
                            Debug.Log(apple.cancellationDate);
                            Debug.Log(apple.quantity);
                        }
#endif
                    }
                    valid = true;
                }
                catch (IAPSecurityException secureException)
                {
                    Debug.Log(secureException.ToString());
                    valid = false;
                }

                if (valid)
                {
                    IAPController.Instance.OnPurchaseAuthorized(iapProduct);
                }
                else
                {
                    IAPController.Instance.OnPurchaseError(iapProduct);
                }
            }

            return(PurchaseProcessingResult.Complete);
        }
コード例 #23
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        bool success = true;

        // 아래 소스코드는 안드로이드(Android)에서 실행했을 때에만 정상적으로 동작합니다.
        CrossPlatformValidator validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                                      AppleTangle.Data(), Application.identifier);

        try
        {
            // 앱 상에서 구매한 물품에 대하여 결제 처리를 진행합니다.
            IPurchaseReceipt[] result = validator.Validate(e.purchasedProduct.receipt);
            for (int i = 0; i < result.Length; i++)
            {
                Analytics.Transaction(productID, e.purchasedProduct.metadata.localizedPrice,
                                      e.purchasedProduct.metadata.isoCurrencyCode);
            }
        }
        catch (IAPSecurityException ex)
        {
            // 유니티 에디터에서 실행하는 경우 오류가 발생합니다.
            Debug.Log("오류 발생: " + ex.Message);
            success = false;
        }

        if (success)
        {
            Debug.Log("결제 완료");

            // 데이터베이스에 접근.
            DatabaseReference reference = PlayerInformation.GetDatabaseReference();

            // 삽입할 데이터 준비하기
            DateTime now       = DateTime.Now.ToLocalTime();
            TimeSpan span      = (now - new DateTime(1970, 1, 1, 0, 0, 0).ToLocalTime());
            int      timestamp = (int)span.TotalSeconds;
            Charge   charge    = new Charge(timestamp);
            string   json      = JsonUtility.ToJson(charge);

            // 랭킹 점수 데이터 삽입하기
            reference.Child("charges").Child(musicIndex.ToString()).Child(PlayerInformation.auth.CurrentUser.UserId).SetRawJsonValueAsync(json);
            UpdateSong(musicIndex);
        }
        else
        {
            Debug.Log("결제 실패");
        }

        return(PurchaseProcessingResult.Complete);
    }
コード例 #24
0
    /// <summary>
    /// Called when a purchase completes.
    ///
    /// May be called at any time after OnInitialized().
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs _e)
    {
        //callbackOk?.Invoke();
        //return PurchaseProcessingResult.Complete;

        bool validPurchase = true; // Presume valid for platforms with no R.V.

        // Unity IAP's validation logic is only included on these platforms.
#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
        // Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator
                        (
            GooglePlayTangle.Data(),
            AppleTangle.Data(),
            Application.identifier
                        );

        try
        {
            // On Google Play, result has a single product ID.
            // On Apple stores, receipts contain multiple products.
            var result = validator.Validate(_e.purchasedProduct.receipt);
            // For informational purposes, we list the receipt(s)
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log(productReceipt.productID);
                Debug.Log(productReceipt.purchaseDate);
                Debug.Log(productReceipt.transactionID);
            }
        }
        catch (IAPSecurityException)
        {
            Debug.Log("Invalid receipt, not unlocking content");
            validPurchase = false;
        }
#endif

        if (validPurchase)
        {
            callbackOk?.Invoke();
        }
        else
        {
            callbackFailed?.Invoke();
        }

        return(PurchaseProcessingResult.Complete);
    }
コード例 #25
0
    // 상품 구매 성공
    PurchaseProcessingResult IStoreListener.ProcessPurchase(PurchaseEventArgs e)
    {
        Log_Controller.Log("ProcessPurchase 처리 시작");

        bool t_IsBuy = true;

#if UNITY_ANDROID || UNITY_IOS
        var t_Validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
        Log_Controller.Log("ProcessPurchase 처리 시작-10");
        try
        {
            Log_Controller.Log("ProcessPurchase 처리 시작-11");
            var t_Result = t_Validator.Validate(e.purchasedProduct.receipt);
            m_Text.text += " 정상 구매에 따른 정보 \n";

            Log_Controller.Log("정상 구매에 따른 정보:");
            foreach (IPurchaseReceipt productReceipt in t_Result)
            {
                m_Text.text += productReceipt.productID.ToString() + '\n';
                m_Text.text += productReceipt.purchaseDate.ToString() + '\n';
                m_Text.text += productReceipt.transactionID.ToString() + '\n';

                Log_Controller.Log(productReceipt.productID.ToString());
                Log_Controller.Log(productReceipt.purchaseDate.ToString());
                Log_Controller.Log(productReceipt.transactionID.ToString());

                m_Text.text += Log_Controller.s_LogPath + '\n';

                Analytics.Transaction(productReceipt.productID, e.purchasedProduct.metadata.localizedPrice, e.purchasedProduct.metadata.isoCurrencyCode, productReceipt.transactionID, null);
                m_Text.text += "전송 완료 \n";
                //Analytics.Transaction(productReceipt.productID, e.purchasedProduct.metadata.localizedPrice, e.purchasedProduct.metadata.isoCurrencyCode, e.purchasedProduct.receipt, productReceipt.transactionID.ToString());
            }
        }
        catch (IAPSecurityException)
        {
            Log_Controller.Log("비정상 구매로 확인됨");
            t_IsBuy = false;
        }
#endif
        Log_Controller.Log("ProcessPurchase 처리 시작-20");
        if (t_IsBuy)
        {
            // 정상 구매 성공시 처리
            Log_Controller.Log("정상 구매 확인되어 아이템 지급 처리");
        }

        return(PurchaseProcessingResult.Complete);
    }
コード例 #26
0
        /// <summary>
        /// Called when a purchase completes.
        ///
        /// May be called at any time after OnInitialized().
        /// </summary>
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            bool validPurchase = true; // Presume valid for platforms with no R.V.

            System.DateTime purchaseData = System.DateTime.Now;

            // Unity IAP's validation logic is only included on these platforms.
#if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
            // Prepare the validator with the secrets we prepared in the Editor
            // obfuscation window.
            purchaseData = System.DateTime.MinValue;
            var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                       AppleTangle.Data(), Application.identifier);

            try
            {
                // On Google Play, result has a single product ID.
                // On Apple stores, receipts contain multiple products.
                var result = validator.Validate(e.purchasedProduct.receipt);
                // For informational purposes, we list the receipt(s)
                //Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    if (purchaseData.Ticks < productReceipt.purchaseDate.Ticks)
                    {
                        purchaseData = productReceipt.purchaseDate;
                    }
                }
            }
            catch (IAPSecurityException ex)
            {
                Debug.LogError("Invalid receipt:" + ex.Message);
                validPurchase = false;
            }
#endif

            if (validPurchase)
            {
                var pid   = e.purchasedProduct.definition.id;
                var goods = TableShop.Get(a => a.productID == pid);
                D.I.OnPurchaseSuccess(goods.id, purchaseData);
            }
            else
            {
                Toast.Show("Purchase Failed, Invalid receipt.");
            }
            return(PurchaseProcessingResult.Complete);
        }
コード例 #27
0
ファイル: StoreManager.cs プロジェクト: hferrone/IAPTest
    private bool ValidateReceipt(Product product)
    {
        bool validReceipt = true;

#if UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE_OSX
        var validator = new CrossPlatformValidator(AppleTangle.Data(), GooglePlayTangle.Data(), Application.identifier);

        try
        {
            var result = validator.Validate(product.receipt);
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.LogFormat("{0}, {1}, {2}", productReceipt.productID,
                                productReceipt.purchaseDate,
                                productReceipt.transactionID);

                AppleInAppPurchaseReceipt aReceipt = productReceipt as AppleInAppPurchaseReceipt;
                if (aReceipt != null)
                {
                    Debug.LogFormat("{0}, {1}, {2}, {3}", aReceipt.originalTransactionIdentifier,
                                    aReceipt.subscriptionExpirationDate,
                                    aReceipt.cancellationDate,
                                    aReceipt.quantity);
                }

                GooglePlayReceipt gReceipt = productReceipt as GooglePlayReceipt;
                if (gReceipt != null)
                {
                    Debug.LogFormat("{0}, {1}, {2}", gReceipt.transactionID,
                                    gReceipt.purchaseState,
                                    gReceipt.purchaseToken);
                }
            }
        }
        catch (MissingStoreSecretException)
        {
            Debug.Log("You haven't supplied a secret key for this platform...");
            validReceipt = false;
        }
        catch (IAPSecurityException)
        {
            Debug.LogFormat("Invalid receipt {0}", product.receipt);
            validReceipt = false;
        }
#endif

        return(validReceipt);
    }
コード例 #28
0
        PurchaseProcessingResult ProcessGooglePurchase(PurchaseEventArgs e)
        {
            // receipt validation tangle data not available.
            if (googleTangleData == null)
            {
                DebugLog($" ***** ProcessGooglePurchase   googleTangleData IS NULL");
                OnPurchased?.Invoke(PurchaseResponse.Ok, e.purchasedProduct);
                return(PurchaseProcessingResult.Complete);
            }

            // validate receipt.
            try {
                DebugLog($" ***** ProcessGooglePurchase   validate receipt.");
                var validator = new CrossPlatformValidator(googleTangleData, null, Application.identifier);
                // On Google Play, result has a single product ID.
                // On Apple stores, receipts contain multiple products.
                var result = validator.Validate(e.purchasedProduct.receipt);
#if DEBUG_IAP
                // For informational purposes, we list the receipt(s)
                foreach (IPurchaseReceipt receipt in result)
                {
                    var sb = new StringBuilder("Purchase Receipt Details:");
                    sb.Append($"\n  Product ID: {receipt.productID}");
                    sb.Append($"\n  Purchase Date: {receipt.purchaseDate}");
                    sb.Append($"\n  Transaction ID: {receipt.transactionID}");

                    var googleReceipt = receipt as GooglePlayReceipt;
                    if (googleReceipt != null)
                    {
                        // This is Google's Order ID.
                        // Note that it is null when testing in the sandbox
                        // because Google's sandbox does not provide Order IDs.
                        sb.Append($"\n  Purchase State: {googleReceipt.purchaseState}");
                        sb.Append($"\n  Purchase Token: {googleReceipt.purchaseToken}");
                    }

                    DebugLog(sb);
                }
#endif
                OnPurchased?.Invoke(PurchaseResponse.Ok, e.purchasedProduct);
            } catch (IAPSecurityException err) {
                DebugLog($"Invalid receipt or security exception: {err.Message}");
                OnPurchased?.Invoke(PurchaseResponse.InvalidReceipt, e.purchasedProduct);
            }

            return(PurchaseProcessingResult.Complete);
        }
    private bool CheckReceipt(Product product)
    {
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);

        try
        {
            Debug.Log(product.receipt);
            var result = validator.Validate(product.receipt);
        }
        catch (IAPSecurityException)
        {
            Debug.LogError("Invalid Receipt");
            return(false);
        }

        return(true);
    }
コード例 #30
0
    public PurchaseProcessingResult ProcessTransaction(PurchaseEventArgs e)
    {
        CrossPlatformValidator validator = new CrossPlatformValidator(GooglePlayTangle.Data(), null, Application.identifier);

        try
        {
            var result = validator.Validate(e.purchasedProduct.receipt);
            foreach (IPurchaseReceipt productReceipt in result)
            {
            }
        } catch (IAPSecurityException)
        {
            Debug.Log("Invalid");
        }

        return(PurchaseProcessingResult.Complete);
    }
コード例 #31
0
ファイル: MainPurchase.cs プロジェクト: taboo1/arena
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        // Unity IAP's validation logic is only included on these platforms.
        #if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX || UNITY_TVOS
        // Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
            AppleTangle.Data(), Application.bundleIdentifier);

        try
        {
            // On Google Play, result will have a single product Id.
            // On Apple stores receipts contain multiple products.
            var result = validator.Validate(args.purchasedProduct.receipt);
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                if (String.Equals(productReceipt.productID, firstCurrencyId, StringComparison.Ordinal))
                {
                    Bank.PlusMoney(MoneyPrice.firstPurchase);
                    PreferencesSaver.SetPurchaseComplete();
                    Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
                }
                else
                {
                    libraryMenu.windowWarning.Show("Произошла ошибка покупки. Ваши деньги не списаны");

                    Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
                }

            }
            // Unlock the appropriate content here.
        }
        catch (IAPSecurityException)
        {
            libraryMenu.windowWarning.Show("Произошла ошибка покупки. Ваши деньги не списаны");
        }
        #endif

        return PurchaseProcessingResult.Complete;
    }