LocalReceiptValidation.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Purchasing;
  5. using UnityEngine.Purchasing.Security;
  6. using UnityEngine.UI;
  7. namespace Samples.Purchasing.Core.LocalReceiptValidation
  8. {
  9. public class LocalReceiptValidation : MonoBehaviour, IStoreListener
  10. {
  11. IStoreController m_StoreController;
  12. CrossPlatformValidator m_Validator = null;
  13. //Your products IDs. They should match the ids of your products in your store.
  14. public string goldProductId = "com.mycompany.mygame.gold1";
  15. public ProductType productType = ProductType.Consumable;
  16. public Text GoldCountText;
  17. public UserWarning userWarning;
  18. public Toggle appleCertificateToggle;
  19. int m_GoldCount;
  20. bool m_UseAppleStoreKitTestCertificate;
  21. void Start()
  22. {
  23. userWarning.Clear();
  24. appleCertificateToggle.onValueChanged.AddListener(OnAppleStoreKitTestCertificateChanged);
  25. m_UseAppleStoreKitTestCertificate = appleCertificateToggle.isOn;
  26. InitializePurchasing();
  27. UpdateUI();
  28. }
  29. static bool IsCurrentStoreSupportedByValidator()
  30. {
  31. //The CrossPlatform validator only supports the GooglePlayStore and Apple's App Stores.
  32. return IsGooglePlayStoreSelected() || IsAppleAppStoreSelected();
  33. }
  34. static bool IsGooglePlayStoreSelected()
  35. {
  36. var currentAppStore = StandardPurchasingModule.Instance().appStore;
  37. return currentAppStore == AppStore.GooglePlay;
  38. }
  39. static bool IsAppleAppStoreSelected()
  40. {
  41. var currentAppStore = StandardPurchasingModule.Instance().appStore;
  42. return currentAppStore == AppStore.AppleAppStore ||
  43. currentAppStore == AppStore.MacAppStore;
  44. }
  45. void InitializePurchasing()
  46. {
  47. var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  48. builder.AddProduct(goldProductId, productType);
  49. UnityPurchasing.Initialize(this, builder);
  50. }
  51. public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  52. {
  53. Debug.Log("In-App Purchasing successfully initialized");
  54. m_StoreController = controller;
  55. InitializeValidator();
  56. }
  57. void InitializeValidator()
  58. {
  59. if (IsCurrentStoreSupportedByValidator())
  60. {
  61. #if !UNITY_EDITOR
  62. var appleTangleData = m_UseAppleStoreKitTestCertificate ? AppleStoreKitTestTangle.Data() : AppleTangle.Data();
  63. m_Validator = new CrossPlatformValidator(GooglePlayTangle.Data(), appleTangleData, Application.identifier);
  64. #endif
  65. }
  66. else
  67. {
  68. userWarning.WarnInvalidStore(StandardPurchasingModule.Instance().appStore);
  69. }
  70. }
  71. public void OnInitializeFailed(InitializationFailureReason error)
  72. {
  73. Debug.Log($"In-App Purchasing initialize failed: {error}");
  74. }
  75. public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
  76. {
  77. Debug.Log($"Purchase failed - Product: '{product.definition.id}', PurchaseFailureReason: {failureReason}");
  78. }
  79. public void BuyGold()
  80. {
  81. m_StoreController.InitiatePurchase(goldProductId);
  82. }
  83. public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
  84. {
  85. //Retrieve the purchased product
  86. var product = args.purchasedProduct;
  87. var isPurchaseValid = IsPurchaseValid(product);
  88. if (isPurchaseValid)
  89. {
  90. //Add the purchased product to the players inventory
  91. UnlockContent(product);
  92. Debug.Log("Valid receipt, unlocking content.");
  93. }
  94. else
  95. {
  96. Debug.Log("Invalid receipt, not unlocking content.");
  97. }
  98. //We return Complete, informing Unity IAP that the processing on our side is done and the transaction can be closed.
  99. return PurchaseProcessingResult.Complete;
  100. }
  101. bool IsPurchaseValid(Product product)
  102. {
  103. //If we the validator doesn't support the current store, we assume the purchase is valid
  104. if (IsCurrentStoreSupportedByValidator())
  105. {
  106. try
  107. {
  108. var result = m_Validator.Validate(product.receipt);
  109. //The validator returns parsed receipts.
  110. LogReceipts(result);
  111. }
  112. //If the purchase is deemed invalid, the validator throws an IAPSecurityException.
  113. catch (IAPSecurityException reason)
  114. {
  115. Debug.Log($"Invalid receipt: {reason}");
  116. return false;
  117. }
  118. }
  119. return true;
  120. }
  121. void UnlockContent(Product product)
  122. {
  123. if (product.definition.id == goldProductId)
  124. {
  125. AddGold();
  126. }
  127. }
  128. void AddGold()
  129. {
  130. m_GoldCount++;
  131. UpdateUI();
  132. }
  133. void UpdateUI()
  134. {
  135. GoldCountText.text = $"Your Gold: {m_GoldCount}";
  136. }
  137. static void LogReceipts(IEnumerable<IPurchaseReceipt> receipts)
  138. {
  139. Debug.Log("Receipt is valid. Contents:");
  140. foreach (var receipt in receipts)
  141. {
  142. LogReceipt(receipt);
  143. }
  144. }
  145. static void LogReceipt(IPurchaseReceipt receipt)
  146. {
  147. Debug.Log($"Product ID: {receipt.productID}\n" +
  148. $"Purchase Date: {receipt.purchaseDate}\n" +
  149. $"Transaction ID: {receipt.transactionID}");
  150. if (receipt is GooglePlayReceipt googleReceipt)
  151. {
  152. Debug.Log($"Purchase State: {googleReceipt.purchaseState}\n" +
  153. $"Purchase Token: {googleReceipt.purchaseToken}");
  154. }
  155. if (receipt is AppleInAppPurchaseReceipt appleReceipt)
  156. {
  157. Debug.Log($"Original Transaction ID: {appleReceipt.originalTransactionIdentifier}\n" +
  158. $"Subscription Expiration Date: {appleReceipt.subscriptionExpirationDate}\n" +
  159. $"Cancellation Date: {appleReceipt.cancellationDate}\n" +
  160. $"Quantity: {appleReceipt.quantity}");
  161. }
  162. }
  163. void OnAppleStoreKitTestCertificateChanged(bool value)
  164. {
  165. m_UseAppleStoreKitTestCertificate = value;
  166. InitializeValidator();
  167. }
  168. }
  169. }