IAPButton.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. #if UNITY_PURCHASING
  2. using UnityEngine.Events;
  3. using UnityEngine.UI;
  4. using System.IO;
  5. using System.Collections.Generic;
  6. namespace UnityEngine.Purchasing
  7. {
  8. [RequireComponent(typeof(Button))]
  9. [AddComponentMenu("Unity IAP/IAP Button")]
  10. [HelpURL("https://docs.unity3d.com/Manual/UnityIAP.html")]
  11. public class IAPButton : MonoBehaviour
  12. {
  13. public enum ButtonType
  14. {
  15. Purchase,
  16. Restore
  17. }
  18. [System.Serializable]
  19. public class OnPurchaseCompletedEvent : UnityEvent<Product>
  20. {
  21. };
  22. [System.Serializable]
  23. public class OnPurchaseFailedEvent : UnityEvent<Product, PurchaseFailureReason>
  24. {
  25. };
  26. [HideInInspector]
  27. public string productId;
  28. [Tooltip("The type of this button, can be either a purchase or a restore button")]
  29. public ButtonType buttonType = ButtonType.Purchase;
  30. [Tooltip("Consume the product immediately after a successful purchase")]
  31. public bool consumePurchase = true;
  32. [Tooltip("Event fired after a successful purchase of this product")]
  33. public OnPurchaseCompletedEvent onPurchaseComplete;
  34. [Tooltip("Event fired after a failed purchase of this product")]
  35. public OnPurchaseFailedEvent onPurchaseFailed;
  36. [Tooltip("[Optional] Displays the localized title from the app store")]
  37. public Text titleText;
  38. [Tooltip("[Optional] Displays the localized description from the app store")]
  39. public Text descriptionText;
  40. [Tooltip("[Optional] Displays the localized price from the app store")]
  41. public Text priceText;
  42. void Start()
  43. {
  44. Button button = GetComponent<Button>();
  45. if (buttonType == ButtonType.Purchase)
  46. {
  47. if (button)
  48. {
  49. button.onClick.AddListener(PurchaseProduct);
  50. }
  51. if (string.IsNullOrEmpty(productId))
  52. {
  53. Debug.LogError("IAPButton productId is empty");
  54. }
  55. if (!IAPButtonStoreManager.Instance.HasProductInCatalog(productId))
  56. {
  57. Debug.LogWarning("The product catalog has no product with the ID \"" + productId + "\"");
  58. }
  59. }
  60. else if (buttonType == ButtonType.Restore)
  61. {
  62. if (button)
  63. {
  64. button.onClick.AddListener(Restore);
  65. }
  66. }
  67. }
  68. void OnEnable()
  69. {
  70. if (buttonType == ButtonType.Purchase)
  71. {
  72. IAPButtonStoreManager.Instance.AddButton(this);
  73. UpdateText();
  74. }
  75. }
  76. void OnDisable()
  77. {
  78. if (buttonType == ButtonType.Purchase)
  79. {
  80. IAPButtonStoreManager.Instance.RemoveButton(this);
  81. }
  82. }
  83. void PurchaseProduct()
  84. {
  85. if (buttonType == ButtonType.Purchase)
  86. {
  87. Debug.Log("IAPButton.PurchaseProduct() with product ID: " + productId);
  88. IAPButtonStoreManager.Instance.InitiatePurchase(productId);
  89. }
  90. }
  91. void Restore()
  92. {
  93. if (buttonType == ButtonType.Restore)
  94. {
  95. if (Application.platform == RuntimePlatform.WSAPlayerX86 ||
  96. Application.platform == RuntimePlatform.WSAPlayerX64 ||
  97. Application.platform == RuntimePlatform.WSAPlayerARM)
  98. {
  99. IAPButtonStoreManager.Instance.ExtensionProvider.GetExtension<IMicrosoftExtensions>()
  100. .RestoreTransactions();
  101. }
  102. else if (Application.platform == RuntimePlatform.IPhonePlayer ||
  103. Application.platform == RuntimePlatform.OSXPlayer ||
  104. Application.platform == RuntimePlatform.tvOS)
  105. {
  106. IAPButtonStoreManager.Instance.ExtensionProvider.GetExtension<IAppleExtensions>()
  107. .RestoreTransactions(OnTransactionsRestored);
  108. }
  109. else if (Application.platform == RuntimePlatform.Android &&
  110. StandardPurchasingModule.Instance().appStore == AppStore.SamsungApps)
  111. {
  112. IAPButtonStoreManager.Instance.ExtensionProvider.GetExtension<ISamsungAppsExtensions>()
  113. .RestoreTransactions(OnTransactionsRestored);
  114. }
  115. else if (Application.platform == RuntimePlatform.Android &&
  116. StandardPurchasingModule.Instance().appStore == AppStore.CloudMoolah)
  117. {
  118. IAPButtonStoreManager.Instance.ExtensionProvider.GetExtension<IMoolahExtension>()
  119. .RestoreTransactionID((restoreTransactionIDState) =>
  120. {
  121. OnTransactionsRestored(
  122. restoreTransactionIDState != RestoreTransactionIDState.RestoreFailed &&
  123. restoreTransactionIDState != RestoreTransactionIDState.NotKnown);
  124. });
  125. }
  126. else
  127. {
  128. Debug.LogWarning(Application.platform.ToString() +
  129. " is not a supported platform for the Codeless IAP restore button");
  130. }
  131. }
  132. }
  133. void OnTransactionsRestored(bool success)
  134. {
  135. Debug.Log("Transactions restored: " + success);
  136. }
  137. /**
  138. * Invoked to process a purchase of the product associated with this button
  139. */
  140. public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
  141. {
  142. Debug.Log(string.Format("IAPButton.ProcessPurchase(PurchaseEventArgs {0} - {1})", e,
  143. e.purchasedProduct.definition.id));
  144. onPurchaseComplete.Invoke(e.purchasedProduct);
  145. return (consumePurchase) ? PurchaseProcessingResult.Complete : PurchaseProcessingResult.Pending;
  146. }
  147. /**
  148. * Invoked on a failed purchase of the product associated with this button
  149. */
  150. public void OnPurchaseFailed(Product product, PurchaseFailureReason reason)
  151. {
  152. Debug.Log(string.Format("IAPButton.OnPurchaseFailed(Product {0}, PurchaseFailureReason {1})", product,
  153. reason));
  154. onPurchaseFailed.Invoke(product, reason);
  155. }
  156. private void UpdateText()
  157. {
  158. var product = IAPButtonStoreManager.Instance.GetProduct(productId);
  159. if (product != null)
  160. {
  161. if (titleText != null)
  162. {
  163. titleText.text = product.metadata.localizedTitle;
  164. }
  165. if (descriptionText != null)
  166. {
  167. descriptionText.text = product.metadata.localizedDescription;
  168. }
  169. if (priceText != null)
  170. {
  171. priceText.text = product.metadata.localizedPriceString;
  172. }
  173. }
  174. }
  175. public class IAPButtonStoreManager : IStoreListener
  176. {
  177. private static IAPButtonStoreManager instance = new IAPButtonStoreManager();
  178. private ProductCatalog catalog;
  179. private List<IAPButton> activeButtons = new List<IAPButton>();
  180. private List<IAPListener> activeListeners = new List<IAPListener> ();
  181. protected IStoreController controller;
  182. protected IExtensionProvider extensions;
  183. private IAPButtonStoreManager()
  184. {
  185. catalog = ProductCatalog.LoadDefaultCatalog();
  186. StandardPurchasingModule module = StandardPurchasingModule.Instance();
  187. module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;
  188. ConfigurationBuilder builder = ConfigurationBuilder.Instance(module);
  189. IAPConfigurationHelper.PopulateConfigurationBuilder(ref builder, catalog);
  190. UnityPurchasing.Initialize(this, builder);
  191. }
  192. public static IAPButtonStoreManager Instance
  193. {
  194. get { return instance; }
  195. }
  196. public IStoreController StoreController
  197. {
  198. get { return controller; }
  199. }
  200. public IExtensionProvider ExtensionProvider
  201. {
  202. get { return extensions; }
  203. }
  204. public bool HasProductInCatalog(string productID)
  205. {
  206. foreach (var product in catalog.allProducts)
  207. {
  208. if (product.id == productID)
  209. {
  210. return true;
  211. }
  212. }
  213. return false;
  214. }
  215. public Product GetProduct(string productID)
  216. {
  217. if (controller != null && controller.products != null && !string.IsNullOrEmpty(productID))
  218. {
  219. return controller.products.WithID(productID);
  220. }
  221. return null;
  222. }
  223. public void AddButton(IAPButton button)
  224. {
  225. activeButtons.Add(button);
  226. }
  227. public void RemoveButton(IAPButton button)
  228. {
  229. activeButtons.Remove(button);
  230. }
  231. public void AddListener(IAPListener listener)
  232. {
  233. activeListeners.Add (listener);
  234. }
  235. public void RemoveListener(IAPListener listener)
  236. {
  237. activeListeners.Remove (listener);
  238. }
  239. public void InitiatePurchase(string productID)
  240. {
  241. if (controller == null)
  242. {
  243. Debug.LogError("Purchase failed because Purchasing was not initialized correctly");
  244. foreach (var button in activeButtons)
  245. {
  246. if (button.productId == productID)
  247. {
  248. button.OnPurchaseFailed(null, Purchasing.PurchaseFailureReason.PurchasingUnavailable);
  249. }
  250. }
  251. return;
  252. }
  253. controller.InitiatePurchase(productID);
  254. }
  255. public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  256. {
  257. this.controller = controller;
  258. this.extensions = extensions;
  259. foreach (var button in activeButtons)
  260. {
  261. button.UpdateText();
  262. }
  263. }
  264. public void OnInitializeFailed(InitializationFailureReason error)
  265. {
  266. Debug.LogError(string.Format("Purchasing failed to initialize. Reason: {0}", error.ToString()));
  267. }
  268. public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
  269. {
  270. PurchaseProcessingResult result;
  271. // if any receiver consumed this purchase we return the status
  272. bool consumePurchase = false;
  273. bool resultProcessed = false;
  274. foreach (IAPButton button in activeButtons)
  275. {
  276. if (button.productId == e.purchasedProduct.definition.id)
  277. {
  278. result = button.ProcessPurchase(e);
  279. if (result == PurchaseProcessingResult.Complete) {
  280. consumePurchase = true;
  281. }
  282. resultProcessed = true;
  283. }
  284. }
  285. foreach (IAPListener listener in activeListeners)
  286. {
  287. result = listener.ProcessPurchase(e);
  288. if (result == PurchaseProcessingResult.Complete) {
  289. consumePurchase = true;
  290. }
  291. resultProcessed = true;
  292. }
  293. // we expect at least one receiver to get this message
  294. if (!resultProcessed) {
  295. Debug.LogWarning("Purchase not correctly processed for product \"" +
  296. e.purchasedProduct.definition.id +
  297. "\". Add an active IAPButton to process this purchase, or add an IAPListener to receive any unhandled purchase events.");
  298. }
  299. return (consumePurchase) ? PurchaseProcessingResult.Complete : PurchaseProcessingResult.Pending;
  300. }
  301. public void OnPurchaseFailed(Product product, PurchaseFailureReason reason)
  302. {
  303. bool resultProcessed = false;
  304. foreach (IAPButton button in activeButtons)
  305. {
  306. if (button.productId == product.definition.id)
  307. {
  308. button.OnPurchaseFailed(product, reason);
  309. resultProcessed = true;
  310. }
  311. }
  312. foreach (IAPListener listener in activeListeners)
  313. {
  314. listener.OnPurchaseFailed(product, reason);
  315. resultProcessed = true;
  316. }
  317. // we expect at least one receiver to get this message
  318. if (resultProcessed) {
  319. Debug.LogWarning ("Failed purchase not correctly handled for product \"" + product.definition.id +
  320. "\". Add an active IAPButton to handle this failure, or add an IAPListener to receive any unhandled purchase failures.");
  321. }
  322. return;
  323. }
  324. }
  325. }
  326. }
  327. #endif