IAPDemo.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. #if UNITY_ANDROID || UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_TVOS
  2. // You must obfuscate your secrets using Window > Unity IAP > Receipt Validation Obfuscator
  3. // before receipt validation will compile in this sample.
  4. // #define RECEIPT_VALIDATION
  5. #endif
  6. using System;
  7. using System.Collections.Generic;
  8. using UnityEngine;
  9. using UnityEngine.Events;
  10. using UnityEngine.Purchasing;
  11. using UnityEngine.UI;
  12. #if RECEIPT_VALIDATION
  13. using UnityEngine.Purchasing.Security;
  14. #endif
  15. /// <summary>
  16. /// An example of basic Unity IAP functionality.
  17. /// To use with your account, configure the product ids (AddProduct)
  18. /// and Google Play key (SetPublicKey).
  19. /// </summary>
  20. [AddComponentMenu("Unity IAP/Demo")]
  21. public class IAPDemo : MonoBehaviour, IStoreListener
  22. {
  23. // Unity IAP objects
  24. private IStoreController m_Controller;
  25. private IAppleExtensions m_AppleExtensions;
  26. private IMoolahExtension m_MoolahExtensions;
  27. private ISamsungAppsExtensions m_SamsungExtensions;
  28. private IMicrosoftExtensions m_MicrosoftExtensions;
  29. #pragma warning disable 0414
  30. private bool m_IsGooglePlayStoreSelected;
  31. #pragma warning restore 0414
  32. private bool m_IsSamsungAppsStoreSelected;
  33. private bool m_IsCloudMoolahStoreSelected;
  34. private string m_LastTransationID;
  35. private string m_LastReceipt;
  36. private string m_CloudMoolahUserName;
  37. private bool m_IsLoggedIn = false;
  38. private int m_SelectedItemIndex = -1; // -1 == no product
  39. private bool m_PurchaseInProgress;
  40. private Selectable m_InteractableSelectable; // Optimization used for UI state management
  41. #if RECEIPT_VALIDATION
  42. private CrossPlatformValidator validator;
  43. #endif
  44. /// <summary>
  45. /// This will be called when Unity IAP has finished initialising.
  46. /// </summary>
  47. public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  48. {
  49. m_Controller = controller;
  50. m_AppleExtensions = extensions.GetExtension<IAppleExtensions> ();
  51. m_SamsungExtensions = extensions.GetExtension<ISamsungAppsExtensions> ();
  52. m_MoolahExtensions = extensions.GetExtension<IMoolahExtension> ();
  53. m_MicrosoftExtensions = extensions.GetExtension<IMicrosoftExtensions> ();
  54. InitUI(controller.products.all);
  55. // On Apple platforms we need to handle deferred purchases caused by Apple's Ask to Buy feature.
  56. // On non-Apple platforms this will have no effect; OnDeferred will never be called.
  57. m_AppleExtensions.RegisterPurchaseDeferredListener(OnDeferred);
  58. Debug.Log("Available items:");
  59. foreach (var item in controller.products.all)
  60. {
  61. if (item.availableToPurchase)
  62. {
  63. Debug.Log(string.Join(" - ",
  64. new[]
  65. {
  66. item.metadata.localizedTitle,
  67. item.metadata.localizedDescription,
  68. item.metadata.isoCurrencyCode,
  69. item.metadata.localizedPrice.ToString(),
  70. item.metadata.localizedPriceString,
  71. item.transactionID,
  72. item.receipt
  73. }));
  74. }
  75. }
  76. // Prepare model for purchasing
  77. if (m_Controller.products.all.Length > 0)
  78. {
  79. m_SelectedItemIndex = 0;
  80. }
  81. // Populate the product menu now that we have Products
  82. for (int t = 0; t < m_Controller.products.all.Length; t++)
  83. {
  84. var item = m_Controller.products.all[t];
  85. var description = string.Format("{0} | {1} => {2}", item.metadata.localizedTitle, item.metadata.localizedPriceString, item.metadata.localizedPrice);
  86. // NOTE: my options list is created in InitUI
  87. GetDropdown().options[t] = new Dropdown.OptionData(description);
  88. }
  89. // Ensure I render the selected list element
  90. GetDropdown().RefreshShownValue();
  91. // Now that I have real products, begin showing product purchase history
  92. UpdateHistoryUI();
  93. LogProductDefinitions();
  94. }
  95. /// <summary>
  96. /// This will be called when a purchase completes.
  97. /// </summary>
  98. public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
  99. {
  100. Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
  101. Debug.Log("Receipt: " + e.purchasedProduct.receipt);
  102. m_LastTransationID = e.purchasedProduct.transactionID;
  103. m_LastReceipt = e.purchasedProduct.receipt;
  104. m_PurchaseInProgress = false;
  105. // Now that my purchase history has changed, update its UI
  106. UpdateHistoryUI();
  107. #if RECEIPT_VALIDATION
  108. // Local validation is available for GooglePlay and Apple stores
  109. if (m_IsGooglePlayStoreSelected ||
  110. Application.platform == RuntimePlatform.IPhonePlayer ||
  111. Application.platform == RuntimePlatform.OSXPlayer ||
  112. Application.platform == RuntimePlatform.tvOS) {
  113. try {
  114. var result = validator.Validate(e.purchasedProduct.receipt);
  115. Debug.Log("Receipt is valid. Contents:");
  116. foreach (IPurchaseReceipt productReceipt in result) {
  117. Debug.Log(productReceipt.productID);
  118. Debug.Log(productReceipt.purchaseDate);
  119. Debug.Log(productReceipt.transactionID);
  120. GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
  121. if (null != google) {
  122. Debug.Log(google.purchaseState);
  123. Debug.Log(google.purchaseToken);
  124. }
  125. AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
  126. if (null != apple) {
  127. Debug.Log(apple.originalTransactionIdentifier);
  128. Debug.Log(apple.subscriptionExpirationDate);
  129. Debug.Log(apple.cancellationDate);
  130. Debug.Log(apple.quantity);
  131. }
  132. }
  133. } catch (IAPSecurityException) {
  134. Debug.Log("Invalid receipt, not unlocking content");
  135. return PurchaseProcessingResult.Complete;
  136. }
  137. }
  138. #endif
  139. // CloudMoolah purchase completion / finishing currently requires using the API
  140. // extension IMoolahExtension.RequestPayout to finish a transaction.
  141. if (m_IsCloudMoolahStoreSelected)
  142. {
  143. // Finish transaction with CloudMoolah server
  144. m_MoolahExtensions.RequestPayOut(e.purchasedProduct.transactionID,
  145. (string transactionID, RequestPayOutState state, string message) => {
  146. if (state == RequestPayOutState.RequestPayOutSucceed) {
  147. // Finally, finish transaction with Unity IAP's local
  148. // transaction log, recording the transaction id there
  149. m_Controller.ConfirmPendingPurchase(e.purchasedProduct);
  150. // Unlock content here.
  151. } else {
  152. Debug.Log("RequestPayOut: failed. transactionID: " + transactionID +
  153. ", state: " + state + ", message: " + message);
  154. // Finishing failed. Retry later.
  155. }
  156. });
  157. }
  158. // You should unlock the content here.
  159. // Indicate if we have handled this purchase.
  160. // PurchaseProcessingResult.Complete: ProcessPurchase will not be called
  161. // with this product again, until next purchase.
  162. // PurchaseProcessingResult.Pending: ProcessPurchase will be called
  163. // again with this product at next app launch. Later, call
  164. // m_Controller.ConfirmPendingPurchase(Product) to complete handling
  165. // this purchase. Use to transactionally save purchases to a cloud
  166. // game service.
  167. return PurchaseProcessingResult.Complete;
  168. }
  169. /// <summary>
  170. /// This will be called is an attempted purchase fails.
  171. /// </summary>
  172. public void OnPurchaseFailed(Product item, PurchaseFailureReason r)
  173. {
  174. Debug.Log("Purchase failed: " + item.definition.id);
  175. Debug.Log(r);
  176. m_PurchaseInProgress = false;
  177. }
  178. public void OnInitializeFailed(InitializationFailureReason error)
  179. {
  180. Debug.Log("Billing failed to initialize!");
  181. switch (error)
  182. {
  183. case InitializationFailureReason.AppNotKnown:
  184. Debug.LogError("Is your App correctly uploaded on the relevant publisher console?");
  185. break;
  186. case InitializationFailureReason.PurchasingUnavailable:
  187. // Ask the user if billing is disabled in device settings.
  188. Debug.Log("Billing disabled!");
  189. break;
  190. case InitializationFailureReason.NoProductsAvailable:
  191. // Developer configuration error; check product metadata.
  192. Debug.Log("No products available for purchase!");
  193. break;
  194. }
  195. }
  196. public void Awake()
  197. {
  198. var module = StandardPurchasingModule.Instance();
  199. // The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and
  200. // developer ui (initialization, purchase, failure code setting). These correspond to
  201. // the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode.
  202. module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;
  203. var builder = ConfigurationBuilder.Instance(module);
  204. // This enables the Microsoft IAP simulator for local testing.
  205. // You would remove this before building your release package.
  206. builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = true;
  207. builder.Configure<IGooglePlayConfiguration>().SetPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2O/9/H7jYjOsLFT/uSy3ZEk5KaNg1xx60RN7yWJaoQZ7qMeLy4hsVB3IpgMXgiYFiKELkBaUEkObiPDlCxcHnWVlhnzJBvTfeCPrYNVOOSJFZrXdotp5L0iS2NVHjnllM+HA1M0W2eSNjdYzdLmZl1bxTpXa4th+dVli9lZu7B7C2ly79i/hGTmvaClzPBNyX+Rtj7Bmo336zh2lYbRdpD5glozUq+10u91PMDPH+jqhx10eyZpiapr8dFqXl5diMiobknw9CgcjxqMTVBQHK6hS0qYKPmUDONquJn280fBs1PTeA6NMG03gb9FLESKFclcuEZtvM8ZwMMRxSLA9GwIDAQAB");
  208. m_IsGooglePlayStoreSelected = Application.platform == RuntimePlatform.Android && module.androidStore == AndroidStore.GooglePlay;
  209. // CloudMoolah Configuration setings
  210. // All games must set the configuration. the configuration need to apply on the CloudMoolah Portal.
  211. // CloudMoolah APP Key
  212. builder.Configure<IMoolahConfiguration>().appKey = "d93f4564c41d463ed3d3cd207594ee1b";
  213. // CloudMoolah Hash Key
  214. builder.Configure<IMoolahConfiguration>().hashKey = "cc";
  215. // This enables the CloudMoolah test mode for local testing.
  216. // You would remove this, or set to CloudMoolahMode.Production, before building your release package.
  217. builder.Configure<IMoolahConfiguration>().SetMode(CloudMoolahMode.AlwaysSucceed);
  218. // This records whether we are using Cloud Moolah IAP.
  219. // Cloud Moolah requires logging in to access your Digital Wallet, so:
  220. // A) IAPDemo (this) displays the Cloud Moolah GUI button for Cloud Moolah
  221. m_IsCloudMoolahStoreSelected = Application.platform == RuntimePlatform.Android && module.androidStore == AndroidStore.CloudMoolah;
  222. // Define our products.
  223. // In this case our products have the same identifier across all the App stores,
  224. // except on the Mac App store where product IDs cannot be reused across both Mac and
  225. // iOS stores.
  226. // So on the Mac App store our products have different identifiers,
  227. // and we tell Unity IAP this by using the IDs class.
  228. builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs
  229. {
  230. {"100.gold.coins.mac", MacAppStore.Name},
  231. {"000000596586", TizenStore.Name},
  232. {"com.ff", MoolahAppStore.Name},
  233. });
  234. builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs
  235. {
  236. {"500.gold.coins.mac", MacAppStore.Name},
  237. {"000000596581", TizenStore.Name},
  238. {"com.ee", MoolahAppStore.Name},
  239. });
  240. builder.AddProduct("sword", ProductType.NonConsumable, new IDs
  241. {
  242. {"sword.mac", MacAppStore.Name},
  243. {"000000596583", TizenStore.Name},
  244. });
  245. builder.AddProduct("subscription", ProductType.Subscription, new IDs
  246. {
  247. {"subscription.mac", MacAppStore.Name}
  248. });
  249. // Write Amazon's JSON description of our products to storage when using Amazon's local sandbox.
  250. // This should be removed from a production build.
  251. builder.Configure<IAmazonConfiguration>().WriteSandboxJSON(builder.products);
  252. // This enables simulated purchase success for Samsung IAP.
  253. // You would remove this, or set to SamsungAppsMode.Production, before building your release package.
  254. builder.Configure<ISamsungAppsConfiguration>().SetMode(SamsungAppsMode.AlwaysSucceed);
  255. // This records whether we are using Samsung IAP. Currently ISamsungAppsExtensions.RestoreTransactions
  256. // displays a blocking Android Activity, so:
  257. // A) Unity IAP does not automatically restore purchases on Samsung Galaxy Apps
  258. // B) IAPDemo (this) displays the "Restore" GUI button for Samsung Galaxy Apps
  259. m_IsSamsungAppsStoreSelected = Application.platform == RuntimePlatform.Android && module.androidStore == AndroidStore.SamsungApps;
  260. // This selects the GroupId that was created in the Tizen Store for this set of products
  261. // An empty or non-matching GroupId here will result in no products available for purchase
  262. builder.Configure<ITizenStoreConfiguration>().SetGroupId("100000085616");
  263. #if RECEIPT_VALIDATION
  264. string appIdentifier;
  265. #if UNITY_5_6_OR_NEWER
  266. appIdentifier = Application.identifier;
  267. #else
  268. appIdentifier = Application.bundleIdentifier;
  269. #endif
  270. validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), appIdentifier);
  271. #endif
  272. // Now we're ready to initialize Unity IAP.
  273. UnityPurchasing.Initialize(this, builder);
  274. }
  275. /// <summary>
  276. /// This will be called after a call to IAppleExtensions.RestoreTransactions().
  277. /// </summary>
  278. private void OnTransactionsRestored(bool success)
  279. {
  280. Debug.Log("Transactions restored.");
  281. }
  282. /// <summary>
  283. /// iOS Specific.
  284. /// This is called as part of Apple's 'Ask to buy' functionality,
  285. /// when a purchase is requested by a minor and referred to a parent
  286. /// for approval.
  287. ///
  288. /// When the purchase is approved or rejected, the normal purchase events
  289. /// will fire.
  290. /// </summary>
  291. /// <param name="item">Item.</param>
  292. private void OnDeferred(Product item)
  293. {
  294. Debug.Log("Purchase deferred: " + item.definition.id);
  295. }
  296. private void InitUI(IEnumerable<Product> items)
  297. {
  298. // Disable the UI while IAP is initializing
  299. // See also UpdateInteractable()
  300. m_InteractableSelectable = GetDropdown(); // References any one of the disabled components
  301. // Show Restore button on supported platforms
  302. if (! (Application.platform == RuntimePlatform.IPhonePlayer ||
  303. Application.platform == RuntimePlatform.OSXPlayer ||
  304. Application.platform == RuntimePlatform.tvOS ||
  305. Application.platform == RuntimePlatform.WSAPlayerX86 ||
  306. Application.platform == RuntimePlatform.WSAPlayerX64 ||
  307. Application.platform == RuntimePlatform.WSAPlayerARM ||
  308. m_IsSamsungAppsStoreSelected || m_IsCloudMoolahStoreSelected) )
  309. {
  310. GetRestoreButton().gameObject.SetActive(false);
  311. }
  312. // Show Register, Login, and Validate buttons on CloudMoolah platform
  313. GetRegisterButton().gameObject.SetActive(m_IsCloudMoolahStoreSelected);
  314. GetLoginButton().gameObject.SetActive(m_IsCloudMoolahStoreSelected);
  315. GetValidateButton().gameObject.SetActive(m_IsCloudMoolahStoreSelected);
  316. foreach (var item in items)
  317. {
  318. // Add initial pre-IAP-initialization content. Update later in OnInitialized.
  319. var description = string.Format("{0} - {1}", item.definition.id, item.definition.type);
  320. GetDropdown().options.Add(new Dropdown.OptionData(description));
  321. }
  322. // Ensure I render the selected list element
  323. GetDropdown().RefreshShownValue();
  324. GetDropdown().onValueChanged.AddListener((int selectedItem) => {
  325. Debug.Log("OnClickDropdown item " + selectedItem);
  326. m_SelectedItemIndex = selectedItem;
  327. });
  328. // Initialize my button event handling
  329. GetBuyButton().onClick.AddListener(() => {
  330. if (m_PurchaseInProgress == true) {
  331. Debug.Log("Please wait, purchasing ...");
  332. return;
  333. }
  334. // For CloudMoolah, games utilizing a connected backend game server may wish to login.
  335. // Standalone games may not need to login.
  336. if (m_IsCloudMoolahStoreSelected && m_IsLoggedIn == false)
  337. {
  338. Debug.LogWarning("CloudMoolah purchase notifications will not be forwarded server-to-server. Login incomplete.");
  339. }
  340. // Don't need to draw our UI whilst a purchase is in progress.
  341. // This is not a requirement for IAP Applications but makes the demo
  342. // scene tidier whilst the fake purchase dialog is showing.
  343. m_PurchaseInProgress = true;
  344. m_Controller.InitiatePurchase(m_Controller.products.all[m_SelectedItemIndex], "aDemoDeveloperPayload");
  345. });
  346. if (GetRestoreButton() != null)
  347. {
  348. GetRestoreButton().onClick.AddListener(() => {
  349. if (m_IsCloudMoolahStoreSelected)
  350. {
  351. if (m_IsLoggedIn == false)
  352. {
  353. Debug.LogError("CloudMoolah purchase restoration aborted. Login incomplete.");
  354. }
  355. else
  356. {
  357. // Restore abnornal transaction identifer, if Client don't receive transaction identifer.
  358. m_MoolahExtensions.RestoreTransactionID((RestoreTransactionIDState restoreTransactionIDState) => {
  359. Debug.Log("restoreTransactionIDState = " + restoreTransactionIDState.ToString());
  360. bool success =
  361. restoreTransactionIDState != RestoreTransactionIDState.RestoreFailed &&
  362. restoreTransactionIDState != RestoreTransactionIDState.NotKnown;
  363. OnTransactionsRestored(success);
  364. });
  365. }
  366. }
  367. else if (m_IsSamsungAppsStoreSelected)
  368. {
  369. m_SamsungExtensions.RestoreTransactions(OnTransactionsRestored);
  370. }
  371. else if (Application.platform == RuntimePlatform.WSAPlayerX86 ||
  372. Application.platform == RuntimePlatform.WSAPlayerX64 ||
  373. Application.platform == RuntimePlatform.WSAPlayerARM)
  374. {
  375. m_MicrosoftExtensions.RestoreTransactions();
  376. }
  377. else
  378. {
  379. m_AppleExtensions.RestoreTransactions(OnTransactionsRestored);
  380. }
  381. });
  382. }
  383. // CloudMoolah requires user registration and supports login to manage the user's
  384. // digital wallet. The CM store also supports remote receipt validation.
  385. // CloudMoolah user registration extension, to establish digital wallet
  386. // This is a "fast" registration, requiring only a password. Users may provide
  387. // more detail including an email address during the purchase flow, a "slow" registration, if desired.
  388. if (GetRegisterButton() != null)
  389. {
  390. GetRegisterButton().onClick.AddListener (() => {
  391. // Provide a unique password to establish the user's account.
  392. // Typically, connected games (with backend game servers), may already
  393. // have available a user-token, which could be supplied here.
  394. m_MoolahExtensions.FastRegister("CMPassword", RegisterSucceeded, RegisterFailed);
  395. });
  396. }
  397. // CloudMoolah user login extension, to access existing digital wallet
  398. if (GetLoginButton() != null)
  399. {
  400. GetLoginButton().onClick.AddListener (() => {
  401. m_MoolahExtensions.Login(m_CloudMoolahUserName, "CMPassword", LoginResult);
  402. });
  403. }
  404. // CloudMoolah remote purchase receipt validation, to determine if the purchase is fraudulent
  405. // NOTE: Remote validation only available for CloudMoolah currently. For local validation,
  406. // see ProcessPurchase.
  407. if (GetValidateButton() != null)
  408. {
  409. GetValidateButton ().onClick.AddListener (() => {
  410. // Remotely validate the last transaction and receipt.
  411. m_MoolahExtensions.ValidateReceipt(m_LastTransationID, m_LastReceipt,
  412. (string transactionID, ValidateReceiptState state, string message) => {
  413. Debug.Log("ValidtateReceipt transactionID:" + transactionID
  414. + ", state:" + state.ToString() + ", message:" + message);
  415. });
  416. });
  417. }
  418. }
  419. public void LoginResult (LoginResultState state, string errorMsg)
  420. {
  421. if(state == LoginResultState.LoginSucceed)
  422. {
  423. m_IsLoggedIn = true;
  424. }
  425. else
  426. {
  427. m_IsLoggedIn = false;
  428. }
  429. Debug.Log ("LoginResult: state: " + state.ToString () + " errorMsg: " + errorMsg);
  430. }
  431. public void RegisterSucceeded(string cmUserName)
  432. {
  433. Debug.Log ("RegisterSucceeded: cmUserName = " + cmUserName);
  434. m_CloudMoolahUserName = cmUserName;
  435. }
  436. public void RegisterFailed (FastRegisterError error, string errorMessage)
  437. {
  438. Debug.Log ("RegisterFailed: error = " + error.ToString() + ", errorMessage = " + errorMessage);
  439. }
  440. public void UpdateHistoryUI()
  441. {
  442. if (m_Controller == null)
  443. {
  444. return;
  445. }
  446. var itemText = "Item\n\n";
  447. var countText = "Purchased\n\n";
  448. for (int t = 0; t < m_Controller.products.all.Length; t++)
  449. {
  450. var item = m_Controller.products.all [t];
  451. // Collect history status report
  452. itemText += "\n\n" + item.definition.id;
  453. countText += "\n\n" + item.hasReceipt.ToString();
  454. }
  455. // Show history
  456. GetText(false).text = itemText;
  457. GetText(true).text = countText;
  458. }
  459. protected void UpdateInteractable()
  460. {
  461. if (m_InteractableSelectable == null)
  462. {
  463. return;
  464. }
  465. bool interactable = m_Controller != null;
  466. if (interactable != m_InteractableSelectable.interactable)
  467. {
  468. if (GetRestoreButton() != null)
  469. {
  470. GetRestoreButton().interactable = interactable;
  471. }
  472. GetBuyButton().interactable = interactable;
  473. GetDropdown().interactable = interactable;
  474. GetRegisterButton().interactable = interactable;
  475. GetLoginButton().interactable = interactable;
  476. }
  477. }
  478. public void Update()
  479. {
  480. UpdateInteractable();
  481. }
  482. private Dropdown GetDropdown()
  483. {
  484. return GameObject.Find("Dropdown").GetComponent<Dropdown>();
  485. }
  486. private Button GetBuyButton()
  487. {
  488. return GameObject.Find("Buy").GetComponent<Button>();
  489. }
  490. /// <summary>
  491. /// Gets the restore button when available
  492. /// </summary>
  493. /// <returns><c>null</c> or the restore button.</returns>
  494. private Button GetRestoreButton()
  495. {
  496. return GetButton ("Restore");
  497. }
  498. private Button GetRegisterButton()
  499. {
  500. return GetButton ("Register");
  501. }
  502. private Button GetLoginButton()
  503. {
  504. return GetButton ("Login");
  505. }
  506. private Button GetValidateButton()
  507. {
  508. return GetButton ("Validate");
  509. }
  510. private Button GetButton(string buttonName)
  511. {
  512. GameObject obj = GameObject.Find(buttonName);
  513. if (obj != null)
  514. {
  515. return obj.GetComponent <Button>();
  516. }
  517. else
  518. {
  519. return null;
  520. }
  521. }
  522. private Text GetText(bool right)
  523. {
  524. var which = right ? "TextR" : "TextL";
  525. return GameObject.Find(which).GetComponent<Text>();
  526. }
  527. private void LogProductDefinitions()
  528. {
  529. var products = m_Controller.products.all;
  530. foreach (var product in products) {
  531. #if UNITY_5_6_OR_NEWER
  532. Debug.Log(string.Format("id: {0}\nstore-specific id: {1}\ntype: {2}\nenabled: {3}\n", product.definition.id, product.definition.storeSpecificId, product.definition.type.ToString(), product.definition.enabled ? "enabled" : "disabled"));
  533. #else
  534. Debug.Log(string.Format("id: {0}\nstore-specific id: {1}\ntype: {2}\n", product.definition.id, product.definition.storeSpecificId, product.definition.type.ToString()));
  535. #endif
  536. }
  537. }
  538. }