Beispiel #1
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);
    }
Beispiel #2
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);
    }
Beispiel #3
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
    }
Beispiel #4
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);
    }
Beispiel #5
0
    ///<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);
        }
    }
Beispiel #6
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);
    }
    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);
    }
Beispiel #8
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);
        }
    /// <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);
    }
Beispiel #10
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
    }
Beispiel #11
0
            private IAPButtonStoreManager()
            {
                catalog = ProductCatalog.LoadDefaultCatalog();

                StandardPurchasingModule module = StandardPurchasingModule.Instance();

                module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

                ConfigurationBuilder builder = ConfigurationBuilder.Instance(module);

                //This seems to be outdated/unneeded, the value should be set in unity services
                //builder.Configure<IGooglePlayConfiguration>().SetPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2O/9/H7jYjOsLFT/uSy3ZEk5KaNg1xx60RN7yWJaoQZ7qMeLy4hsVB3IpgMXgiYFiKELkBaUEkObiPDlCxcHnWVlhnzJBvTfeCPrYNVOOSJFZrXdotp5L0iS2NVHjnllM+HA1M0W2eSNjdYzdLmZl1bxTpXa4th+dVli9lZu7B7C2ly79i/hGTmvaClzPBNyX+Rtj7Bmo336zh2lYbRdpD5glozUq+10u91PMDPH+jqhx10eyZpiapr8dFqXl5diMiobknw9CgcjxqMTVBQHK6hS0qYKPmUDONquJn280fBs1PTeA6NMG03gb9FLESKFclcuEZtvM8ZwMMRxSLA9GwIDAQAB");

                foreach (var product in catalog.allProducts)
                {
                    if (product.allStoreIDs.Count > 0)
                    {
                        var ids = new IDs();
                        foreach (var storeID in product.allStoreIDs)
                        {
                            ids.Add(storeID.id, storeID.store);
                        }
                        builder.AddProduct(product.id, product.type, ids);
                    }
                    else
                    {
                        builder.AddProduct(product.id, product.type);
                    }
                }
                                #if RECEIPT_VALIDATION
                validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
                                #endif
                UnityPurchasing.Initialize(this, builder);
            }
        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);
        }
Beispiel #13
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);
        }
Beispiel #14
0
    public void Initialize()
    {
        StandardPurchasingModule module = StandardPurchasingModule.Instance();

        // The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and
        // developer ui (initialization, purchase, failure code setting). These correspond to
        // the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
        //module.useFakeStoreUIMode = FakeStoreUIMode.DeveloperUser;

        // Define products.
        ConfigurationBuilder builder = ConfigurationBuilder.Instance(module);

        builder.AddProduct("testprod", ProductType.Consumable, new IDs
        {
            { "testprod", MacAppStore.Name },
            { "testprod", GooglePlay.Name },
        });

#if RECEIPT_VALIDATION
        validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
#endif

        // Now we're ready to initialize Unity IAP.
        UnityPurchasing.Initialize(this, builder);
    }
Beispiel #15
0
    public void InitProduct(string[] pids, string androidKEY)
    {
        var module = StandardPurchasingModule.Instance();

        // The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and
        // developer ui (initialization, purchase, failure code setting). These correspond to
        // the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
        module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

        var builder = ConfigurationBuilder.Instance(module);

        // This enables the Microsoft IAP simulator for local testing.
        // You would remove this before building your release package.
        builder.Configure <IMicrosoftConfiguration>().useMockBillingSystem = true;
//		builder.Configure<IGooglePlayConfiguration>().SetPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2O/9/H7jYjOsLFT/uSy3ZEk5KaNg1xx60RN7yWJaoQZ7qMeLy4hsVB3IpgMXgiYFiKELkBaUEkObiPDlCxcHnWVlhnzJBvTfeCPrYNVOOSJFZrXdotp5L0iS2NVHjnllM+HA1M0W2eSNjdYzdLmZl1bxTpXa4th+dVli9lZu7B7C2ly79i/hGTmvaClzPBNyX+Rtj7Bmo336zh2lYbRdpD5glozUq+10u91PMDPH+jqhx10eyZpiapr8dFqXl5diMiobknw9CgcjxqMTVBQHK6hS0qYKPmUDONquJn280fBs1PTeA6NMG03gb9FLESKFclcuEZtvM8ZwMMRxSLA9GwIDAQAB");
        builder.Configure <IGooglePlayConfiguration>().SetPublicKey(androidKEY);

        // Define our products.
        // In this case our products have the same identifier across all the App stores,
        // except on the Mac App store where product IDs cannot be reused across both Mac and
        // iOS stores.
        // So on the Mac App store our products have different identifiers,
        // and we tell Unity IAP this by using the IDs class.

        string pName = "";

        if (Application.platform == RuntimePlatform.Android)
        {
            pName = GooglePlay.Name;
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            pName = AppleAppStore.Name;
        }
        else
        {
            pName = "";
        }
        if (pids != null && pids.Length > 0)
        {
            for (int i = 0; i < pids.Length; i++)
            {
                builder.AddProduct(pids[i], ProductType.Consumable, new IDs
                {
                    { pids[i], pName },
                });
            }
        }
        // Write Amazon's JSON description of our products to storage when using Amazon's local sandbox.
        // This should be removed from a production build.
        builder.Configure <IAmazonConfiguration>().WriteSandboxJSON(builder.products);

                #if RECEIPT_VALIDATION
        validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
                #endif

        // Now we're ready to initialize Unity IAP.
        UnityPurchasing.Initialize(this, builder);
    }
Beispiel #16
0
    protected override void GameSetup()
    {
        PaymentProductCoins[] coins = new PaymentProductCoins[6];
        coins[0] = new PaymentProductCoins {
            Price = 0.99m, Currency = "USD", Coins = 1500, NoAds = 0, EventCode = "IAP_BunchofCoins", Description = LocaliseText.Get("Payment.BunchOfCoins"), LanguageKey = "Payment.BunchOfCoins", Product = new PaymentProduct {
                Name = "com.wordfarm.iap.BunchOfCoins", ProductType = ProductType.Consumable
            }
        };
        coins[1] = new PaymentProductCoins {
            Price = 4.99m, Currency = "USD", Coins = 8700, NoAds = 0, EventCode = "IAP_BagofCoins", Description = LocaliseText.Get("Payment.BagOfCoins"), LanguageKey = "Payment.BagOfCoins", Product = new PaymentProduct {
                Name = "com.wordfarm.iap.BagOfCoins", ProductType = ProductType.Consumable
            }
        };
        coins[2] = new PaymentProductCoins {
            Price = 7.99m, Currency = "USD", Coins = 17500, NoAds = 0, EventCode = "IAP_SackofCoins", Description = LocaliseText.Get("Payment.SackOfCoins"), LanguageKey = "Payment.SackOfCoins", Product = new PaymentProduct {
                Name = "com.wordfarm.iap.SackOfCoins", ProductType = ProductType.Consumable
            }
        };
        coins[3] = new PaymentProductCoins {
            Price = 11.99m, Currency = "USD", Coins = 38900, NoAds = 0, EventCode = "IAP_PotofCoins", Description = LocaliseText.Get("Payment.PotOfCoins"), LanguageKey = "Payment.PotOfCoins", Product = new PaymentProduct {
                Name = "com.wordfarm.iap.PotOfCoins", ProductType = ProductType.Consumable
            }
        };
        coins[4] = new PaymentProductCoins {
            Price = 16.99m, Currency = "USD", Coins = 60000, NoAds = 0, EventCode = "IAP_ChestofCoins", Description = LocaliseText.Get("Payment.ChestOfCoins"), LanguageKey = "Payment.ChestOfCoins", Product = new PaymentProduct {
                Name = "com.wordfarm.iap.ChestOfCoins", ProductType = ProductType.Consumable
            }
        };
        coins[5] = new PaymentProductCoins {
            Price = 1.99m, Currency = "USD", Coins = 0, NoAds = 1, EventCode = "IAP_NoAds", Description = LocaliseText.Get("Payment.NoAds"), LanguageKey = "Payment.NoAds", Product = new PaymentProduct {
                Name = "com.wordfarm.iap.noads", ProductType = ProductType.NonConsumable
            }
        };

        CustomPaymentManager.Coins = coins;

        Products = new PaymentProduct[coins.Length];

        for (int i = 0; i < coins.Length; i++)
        {
#if UNITY_ANDROID
            coins[i].Product.Name = coins[i].Product.Name.ToLower(); // android play store allow only lowercase
#endif
            Products[i] = coins[i].Product;
        }

        // Initialise purchasing
        if (InitOnAwake)
        {
            InitializePurchasing();
        }

        GameManager.SafeAddListener <ItemPurchasedMessage> (ItemPurchasedHandler);
        GameManager.SafeAddListener <LocalisationChangedMessage>(LocalisationHandler);

        validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(),
                                               UnityChannelTangle.Data(), Application.identifier);
    }
Beispiel #17
0
    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);
    }
    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);
    }
        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);
        }
Beispiel #20
0
        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);
        }
Beispiel #21
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);
        }
Beispiel #22
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 == 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);
        }
Beispiel #23
0
    public void Awake()
    {
        var module = StandardPurchasingModule.Instance();

        // The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and
        // developer ui (initialization, purchase, failure code setting). These correspond to
        // the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
        module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

        var builder = ConfigurationBuilder.Instance(module);

        // This enables the Microsoft IAP simulator for local testing.
        // You would remove this before building your release package.
        builder.Configure <IMicrosoftConfiguration>().useMockBillingSystem = true;

        // Define our products.
        // In this case our products have the same identifier across all the App stores,
        // except on the Mac App store where product IDs cannot be reused across both Mac and
        // iOS stores.
        // So on the Mac App store our products have different identifiers,
        // and we tell Unity IAP this by using the IDs class.
        builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs
        {
            { "100.gold.coins.mac", MacAppStore.Name },
        });

        builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs
        {
            { "500.gold.coins.mac", MacAppStore.Name },
        });

        builder.AddProduct("sword", ProductType.NonConsumable, new IDs
        {
            { "sword.mac", MacAppStore.Name }
        });

        builder.AddProduct("subscription", ProductType.Subscription, new IDs
        {
            { "subscription.mac", MacAppStore.Name }
        });

        // Write Amazon's JSON description of our products to storage when using Amazon's local sandbox.
        // This should be removed from a production build.
        builder.Configure <IAmazonConfiguration>().WriteSandboxJSON(builder.products);

                #if RECEIPT_VALIDATION
        validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
                #endif

        // Now we're ready to initialize Unity IAP.
        UnityPurchasing.Initialize(this, builder);
    }
Beispiel #24
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);
        }
Beispiel #25
0
        void InitializeValidator()
        {
            if (IsCurrentStoreSupportedByValidator())
            {
#if !UNITY_EDITOR
                m_Validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
#endif
            }
            else
            {
                userWarning.WarnInvalidStore(StandardPurchasingModule.Instance().appStore);
            }
        }
    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);
    }
    /// <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);
    }
Beispiel #28
0
    public void Awake()
    {
        var module = StandardPurchasingModule.Instance();

        // The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and
        // developer ui (initialization, purchase, failure code setting). These correspond to
        // the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
        module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

        var builder = ConfigurationBuilder.Instance(module);

        // This enables the Microsoft IAP simulator for local testing.
        // You would remove this before building your release package.
        builder.Configure <IMicrosoftConfiguration>().useMockBillingSystem = true;
        builder.Configure <IGooglePlayConfiguration>().SetPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2O/9/H7jYjOsLFT/uSy3ZEk5KaNg1xx60RN7yWJaoQZ7qMeLy4hsVB3IpgMXgiYFiKELkBaUEkObiPDlCxcHnWVlhnzJBvTfeCPrYNVOOSJFZrXdotp5L0iS2NVHjnllM+HA1M0W2eSNjdYzdLmZl1bxTpXa4th+dVli9lZu7B7C2ly79i/hGTmvaClzPBNyX+Rtj7Bmo336zh2lYbRdpD5glozUq+10u91PMDPH+jqhx10eyZpiapr8dFqXl5diMiobknw9CgcjxqMTVBQHK6hS0qYKPmUDONquJn280fBs1PTeA6NMG03gb9FLESKFclcuEZtvM8ZwMMRxSLA9GwIDAQAB");

        // Define our products.
        // In this case our products have the same identifier across all the App stores,
        // except on the Mac App store where product IDs cannot be reused across both Mac and
        // iOS stores.
        // So on the Mac App store our products have different identifiers,
        // and we tell Unity IAP this by using the IDs class.
        builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs
        {
            { "100.gold.coins.mac", MacAppStore.Name },
        });

        builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs
        {
            { "500.gold.coins.mac", MacAppStore.Name },
        });

        builder.AddProduct("sword", ProductType.NonConsumable, new IDs
        {
            { "sword.mac", MacAppStore.Name }
        });

        builder.AddProduct("subscription", ProductType.Subscription, new IDs
        {
            { "subscription.mac", MacAppStore.Name }
        });

                #if RECEIPT_VALIDATION
        validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
                #endif

        // Now we're ready to initialize Unity IAP.
        UnityPurchasing.Initialize(this, builder);
    }
Beispiel #29
0
    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);
    }
Beispiel #30
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);
        }
Beispiel #31
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 || 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;
    }
Beispiel #32
0
    public void Initialize()
    {
        StandardPurchasingModule module = StandardPurchasingModule.Instance();

        // The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and
        // developer ui (initialization, purchase, failure code setting). These correspond to
        // the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
        //module.useFakeStoreUIMode = FakeStoreUIMode.DeveloperUser;

        // Define products.
        ConfigurationBuilder builder = ConfigurationBuilder.Instance(module);
        builder.AddProduct("testprod", ProductType.Consumable, new IDs
        {
            {"testprod", MacAppStore.Name},
            {"testprod", GooglePlay.Name},
        });

        #if RECEIPT_VALIDATION
        validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
        #endif

        // Now we're ready to initialize Unity IAP.
        UnityPurchasing.Initialize(this, builder);
    }
Beispiel #33
0
	public void Awake()
	{
		var module = StandardPurchasingModule.Instance();

		// The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and 
		// developer ui (initialization, purchase, failure code setting). These correspond to 
		// the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
		module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

		var builder = ConfigurationBuilder.Instance(module);
		// This enables the Microsoft IAP simulator for local testing.
		// You would remove this before building your release package.
		builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = true;
		builder.Configure<IGooglePlayConfiguration>().SetPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2O/9/H7jYjOsLFT/uSy3ZEk5KaNg1xx60RN7yWJaoQZ7qMeLy4hsVB3IpgMXgiYFiKELkBaUEkObiPDlCxcHnWVlhnzJBvTfeCPrYNVOOSJFZrXdotp5L0iS2NVHjnllM+HA1M0W2eSNjdYzdLmZl1bxTpXa4th+dVli9lZu7B7C2ly79i/hGTmvaClzPBNyX+Rtj7Bmo336zh2lYbRdpD5glozUq+10u91PMDPH+jqhx10eyZpiapr8dFqXl5diMiobknw9CgcjxqMTVBQHK6hS0qYKPmUDONquJn280fBs1PTeA6NMG03gb9FLESKFclcuEZtvM8ZwMMRxSLA9GwIDAQAB");

		// Define our products.
		// In this case our products have the same identifier across all the App stores,
		// except on the Mac App store where product IDs cannot be reused across both Mac and
		// iOS stores.
		// So on the Mac App store our products have different identifiers,
		// and we tell Unity IAP this by using the IDs class.
		builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs
		{
			{"100.gold.coins.mac", MacAppStore.Name},
		});

		builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs
		{
			{"500.gold.coins.mac", MacAppStore.Name},
		});

		builder.AddProduct("sword", ProductType.NonConsumable, new IDs
		{
			{"sword.mac", MacAppStore.Name}
		});

		builder.AddProduct("subscription", ProductType.Subscription, new IDs
		{
			{"subscription.mac", MacAppStore.Name}
		});

		// Write Amazon's JSON description of our products to storage when using Amazon's local sandbox.
		// This should be removed from a production build.
		builder.Configure<IAmazonConfiguration>().WriteSandboxJSON(builder.products);

		#if RECEIPT_VALIDATION
		validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
		#endif

		// Now we're ready to initialize Unity IAP.
		UnityPurchasing.Initialize(this, builder);
	}
Beispiel #34
0
	public void Awake()
	{
		var module = StandardPurchasingModule.Instance();

		// The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and 
		// developer ui (initialization, purchase, failure code setting). These correspond to 
		// the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
		module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

		var builder = ConfigurationBuilder.Instance(module);
		// This enables the Microsoft IAP simulator for local testing.
		// You would remove this before building your release package.
		builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = true;

		// Define our products.
		// In this case our products have the same identifier across all the App stores,
		// except on the Mac App store where product IDs cannot be reused across both Mac and
		// iOS stores.
		// So on the Mac App store our products have different identifiers,
		// and we tell Unity IAP this by using the IDs class.
		builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs
		{
			{"100.gold.coins.mac", MacAppStore.Name},
			{"000000596586", TizenStore.Name},

		});

		builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs
		{
			{"500.gold.coins.mac", MacAppStore.Name},
			{"000000596581", TizenStore.Name},

		});

		builder.AddProduct("sword", ProductType.NonConsumable, new IDs
		{
			{"sword.mac", MacAppStore.Name},
			{"000000596583", TizenStore.Name},

		});

		builder.AddProduct("subscription", ProductType.Subscription, new IDs
		{
			{"subscription.mac", MacAppStore.Name}
		});

		// Write Amazon's JSON description of our products to storage when using Amazon's local sandbox.
		// This should be removed from a production build.
		builder.Configure<IAmazonConfiguration>().WriteSandboxJSON(builder.products);

		// This enables simulated purchase success for Samsung IAP.
		// You would remove this, or set to SamsungAppsMode.Production, before building your release package.
		builder.Configure<ISamsungAppsConfiguration>().SetMode(SamsungAppsMode.AlwaysSucceed);
		// This records whether we are using Samsung IAP. Currently ISamsungAppsExtensions.RestoreTransactions
		// displays a blocking Android Activity, so: 
		// A) Unity IAP does not automatically restore purchases on Samsung Galaxy Apps
		// B) IAPDemo (this) displays the "Restore" GUI button for Samsung Galaxy Apps
		m_IsSamsungAppsStoreSelected = module.androidStore == AndroidStore.SamsungApps;


		// This selects the GroupId that was created in the Tizen Store for this set of products
		// An empty or non-matching GroupId here will result in no products available for purchase
		builder.Configure<ITizenStoreConfiguration>().SetGroupId("100000085616");


		#if RECEIPT_VALIDATION
		validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
		#endif

		// Now we're ready to initialize Unity IAP.
		UnityPurchasing.Initialize(this, builder);
	}
Beispiel #35
0
	public void Awake()
	{
		var module = StandardPurchasingModule.Instance();

		// The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and 
		// developer ui (initialization, purchase, failure code setting). These correspond to 
		// the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
		module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

		var builder = ConfigurationBuilder.Instance(module);
		// This enables the Microsoft IAP simulator for local testing.
		// You would remove this before building your release package.
		builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = true;

		// Define our products.
		// In this case our products have the same identifier across all the App stores,
		// except on the Mac App store where product IDs cannot be reused across both Mac and
		// iOS stores.
		// So on the Mac App store our products have different identifiers,
		// and we tell Unity IAP this by using the IDs class.
		builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs
		{
			{"100.gold.coins.mac", MacAppStore.Name},
		});

		builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs
		{
			{"500.gold.coins.mac", MacAppStore.Name},
		});

		builder.AddProduct("sword", ProductType.NonConsumable, new IDs
		{
			{"sword.mac", MacAppStore.Name}
		});

		builder.AddProduct("subscription", ProductType.Subscription, new IDs
		{
			{"subscription.mac", MacAppStore.Name}
		});

		// Write Amazon's JSON description of our products to storage when using Amazon's local sandbox.
		// This should be removed from a production build.
		builder.Configure<IAmazonConfiguration>().WriteSandboxJSON(builder.products);

		#if RECEIPT_VALIDATION
		validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
		#endif

		// Now we're ready to initialize Unity IAP.
		UnityPurchasing.Initialize(this, builder);
	}
Beispiel #36
0
	public void Awake()
	{
		var module = StandardPurchasingModule.Instance();

		// The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and 
		// developer ui (initialization, purchase, failure code setting). These correspond to 
		// the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
		module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;

		var builder = ConfigurationBuilder.Instance(module);

		// This enables the Microsoft IAP simulator for local testing.
		// You would remove this before building your release package.
		builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = true;
		builder.Configure<IGooglePlayConfiguration>().SetPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2O/9/H7jYjOsLFT/uSy3ZEk5KaNg1xx60RN7yWJaoQZ7qMeLy4hsVB3IpgMXgiYFiKELkBaUEkObiPDlCxcHnWVlhnzJBvTfeCPrYNVOOSJFZrXdotp5L0iS2NVHjnllM+HA1M0W2eSNjdYzdLmZl1bxTpXa4th+dVli9lZu7B7C2ly79i/hGTmvaClzPBNyX+Rtj7Bmo336zh2lYbRdpD5glozUq+10u91PMDPH+jqhx10eyZpiapr8dFqXl5diMiobknw9CgcjxqMTVBQHK6hS0qYKPmUDONquJn280fBs1PTeA6NMG03gb9FLESKFclcuEZtvM8ZwMMRxSLA9GwIDAQAB");
		m_IsGooglePlayStoreSelected = Application.platform == RuntimePlatform.Android && module.androidStore == AndroidStore.GooglePlay;

		// CloudMoolah Configuration setings 
		// All games must set the configuration. the configuration need to apply on the CloudMoolah Portal.
		// CloudMoolah APP Key
		builder.Configure<IMoolahConfiguration>().appKey = "d93f4564c41d463ed3d3cd207594ee1b";
		// CloudMoolah Hash Key
		builder.Configure<IMoolahConfiguration>().hashKey = "cc";
		// This enables the CloudMoolah test mode for local testing.
		// You would remove this, or set to CloudMoolahMode.Production, before building your release package.
		builder.Configure<IMoolahConfiguration>().SetMode(CloudMoolahMode.AlwaysSucceed);
		// This records whether we are using Cloud Moolah IAP. 
		// Cloud Moolah requires logging in to access your Digital Wallet, so: 
		// A) IAPDemo (this) displays the Cloud Moolah GUI button for Cloud Moolah
		m_IsCloudMoolahStoreSelected = Application.platform == RuntimePlatform.Android && module.androidStore == AndroidStore.CloudMoolah;

		// Define our products.
		// In this case our products have the same identifier across all the App stores,
		// except on the Mac App store where product IDs cannot be reused across both Mac and
		// iOS stores.
		// So on the Mac App store our products have different identifiers,
		// and we tell Unity IAP this by using the IDs class.
		builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs
		{
			{"100.gold.coins.mac", MacAppStore.Name},
			{"000000596586", TizenStore.Name},
			{"com.ff", MoolahAppStore.Name},
		});

		builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs
		{
			{"500.gold.coins.mac", MacAppStore.Name},
			{"000000596581", TizenStore.Name},
			{"com.ee", MoolahAppStore.Name},
		});

		builder.AddProduct("sword", ProductType.NonConsumable, new IDs
		{
			{"sword.mac", MacAppStore.Name},
			{"000000596583", TizenStore.Name},
		});

		builder.AddProduct("subscription", ProductType.Subscription, new IDs
		{
			{"subscription.mac", MacAppStore.Name}
		});
		
		// Write Amazon's JSON description of our products to storage when using Amazon's local sandbox.
		// This should be removed from a production build.
		builder.Configure<IAmazonConfiguration>().WriteSandboxJSON(builder.products);

		// This enables simulated purchase success for Samsung IAP.
		// You would remove this, or set to SamsungAppsMode.Production, before building your release package.
		builder.Configure<ISamsungAppsConfiguration>().SetMode(SamsungAppsMode.AlwaysSucceed);
		// This records whether we are using Samsung IAP. Currently ISamsungAppsExtensions.RestoreTransactions
		// displays a blocking Android Activity, so: 
		// A) Unity IAP does not automatically restore purchases on Samsung Galaxy Apps
		// B) IAPDemo (this) displays the "Restore" GUI button for Samsung Galaxy Apps
		m_IsSamsungAppsStoreSelected = module.androidStore == AndroidStore.SamsungApps;


		// This selects the GroupId that was created in the Tizen Store for this set of products
		// An empty or non-matching GroupId here will result in no products available for purchase
		builder.Configure<ITizenStoreConfiguration>().SetGroupId("100000085616");


		#if RECEIPT_VALIDATION
		validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
		#endif

		// Now we're ready to initialize Unity IAP.
		UnityPurchasing.Initialize(this, builder);
	}