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); }
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 }
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); }
///<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); } }
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 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 }
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); }
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); }
/// <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); }
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); }
public void InitUnityPurchase() { var module = StandardPurchasingModule.Instance(); var builder = ConfigurationBuilder.Instance(module); //添加计费点 // UnityEngine.Purchasing.ProductType builder.AddProduct(littleCoins, ProductType.Consumable); builder.AddProduct(largeCoins, ProductType.Consumable); builder.AddProduct(littleGems, ProductType.Consumable); builder.AddProduct(largeGems, ProductType.Consumable); treasures.Add("40000", GameController.littleCoins); treasures.Add("40001", GameController.largeCoins); treasures.Add("40002", GameController.littleGems); treasures.Add("40003", GameController.largeGems); #if RECEIPT_VALIDATION string appIdentifier; #if UNITY_5_6_OR_NEWER appIdentifier = Application.identifier; #else appIdentifier = Application.bundleIdentifier; #endif validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), appIdentifier); #endif // Now we're ready to initialize Unity IAP. UnityPurchasing.Initialize(this, builder); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
// 상품 구매 성공 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); }
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); }
/// <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); }