Advertisement
btf

Unity iap

btf
Jun 22nd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.74 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Purchasing;
  5.  
  6. // Placing the Purchaser class in the CompleteProject namespace allows it to interact with ScoreManager,
  7. // one of the existing Survival Shooter scripts.
  8. namespace CompleteProject
  9. {
  10. // Deriving the Purchaser class from IStoreListener enables it to receive messages from Unity Purchasing.
  11. public class Purchaser : MonoBehaviour, IStoreListener
  12. {
  13. private static IStoreController m_StoreController; // The Unity Purchasing system.
  14. private static IExtensionProvider m_StoreExtensionProvider; // The store-specific Purchasing subsystems.
  15.  
  16. // Product identifiers for all products capable of being purchased:
  17. // "convenience" general identifiers for use with Purchasing, and their store-specific identifier
  18. // counterparts for use with and outside of Unity Purchasing. Define store-specific identifiers
  19. // also on each platform's publisher dashboard (iTunes Connect, Google Play Developer Console, etc.)
  20.  
  21. // General product identifiers for the consumable, non-consumable, and subscription products.
  22. // Use these handles in the code to reference which product to purchase. Also use these values
  23. // when defining the Product Identifiers on the store. Except, for illustration purposes, the
  24. // kProductIDSubscription - it has custom Apple and Google identifiers. We declare their store-
  25. // specific mapping to Unity Purchasing's AddProduct, below.
  26. public static string kProductIDConsumable = "consumable";
  27. public static string kProductIDNonConsumable = "nonconsumable";
  28. public static string kProductIDSubscription = "subscription";
  29.  
  30. // Apple App Store-specific product identifier for the subscription product.
  31. private static string kProductNameAppleSubscription = "com.unity3d.subscription.new";
  32.  
  33. // Google Play Store-specific product identifier subscription product.
  34. private static string kProductNameGooglePlaySubscription = "com.unity3d.subscription.original";
  35.  
  36. void Start()
  37. {
  38. // If we haven't set up the Unity Purchasing reference
  39. if (m_StoreController == null)
  40. {
  41. // Begin to configure our connection to Purchasing
  42. InitializePurchasing();
  43. }
  44. }
  45.  
  46. public void InitializePurchasing()
  47. {
  48. // If we have already connected to Purchasing ...
  49. if (IsInitialized())
  50. {
  51. // ... we are done here.
  52. return;
  53. }
  54.  
  55. // Create a builder, first passing in a suite of Unity provided stores.
  56. var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  57.  
  58. // Add a product to sell / restore by way of its identifier, associating the general identifier
  59. // with its store-specific identifiers.
  60. builder.AddProduct(kProductIDConsumable, ProductType.Consumable);
  61. // Continue adding the non-consumable product.
  62. builder.AddProduct(kProductIDNonConsumable, ProductType.NonConsumable);
  63. // And finish adding the subscription product. Notice this uses store-specific IDs, illustrating
  64. // if the Product ID was configured differently between Apple and Google stores. Also note that
  65. // one uses the general kProductIDSubscription handle inside the game - the store-specific IDs
  66. // must only be referenced here.
  67. builder.AddProduct(kProductIDSubscription, ProductType.Subscription, new IDs(){
  68. { kProductNameAppleSubscription, AppleAppStore.Name },
  69. { kProductNameGooglePlaySubscription, GooglePlay.Name },
  70. });
  71.  
  72. // Kick off the remainder of the set-up with an asynchrounous call, passing the configuration
  73. // and this class' instance. Expect a response either in OnInitialized or OnInitializeFailed.
  74. UnityPurchasing.Initialize(this, builder);
  75. }
  76.  
  77.  
  78. private bool IsInitialized()
  79. {
  80. // Only say we are initialized if both the Purchasing references are set.
  81. return m_StoreController != null && m_StoreExtensionProvider != null;
  82. }
  83.  
  84.  
  85. public void BuyConsumable()
  86. {
  87. // Buy the consumable product using its general identifier. Expect a response either
  88. // through ProcessPurchase or OnPurchaseFailed asynchronously.
  89. BuyProductID(kProductIDConsumable);
  90. }
  91.  
  92.  
  93. public void BuyNonConsumable()
  94. {
  95. // Buy the non-consumable product using its general identifier. Expect a response either
  96. // through ProcessPurchase or OnPurchaseFailed asynchronously.
  97. BuyProductID(kProductIDNonConsumable);
  98. }
  99.  
  100.  
  101. public void BuySubscription()
  102. {
  103. // Buy the subscription product using its the general identifier. Expect a response either
  104. // through ProcessPurchase or OnPurchaseFailed asynchronously.
  105. // Notice how we use the general product identifier in spite of this ID being mapped to
  106. // custom store-specific identifiers above.
  107. BuyProductID(kProductIDSubscription);
  108. }
  109.  
  110.  
  111. void BuyProductID(string productId)
  112. {
  113. // If Purchasing has been initialized ...
  114. if (IsInitialized())
  115. {
  116. // ... look up the Product reference with the general product identifier and the Purchasing
  117. // system's products collection.
  118. Product product = m_StoreController.products.WithID(productId);
  119.  
  120. // If the look up found a product for this device's store and that product is ready to be sold ...
  121. if (product != null && product.availableToPurchase)
  122. {
  123. Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));
  124. // ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed
  125. // asynchronously.
  126. m_StoreController.InitiatePurchase(product);
  127. }
  128. // Otherwise ...
  129. else
  130. {
  131. // ... report the product look-up failure situation
  132. Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
  133. }
  134. }
  135. // Otherwise ...
  136. else
  137. {
  138. // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or
  139. // retrying initiailization.
  140. Debug.Log("BuyProductID FAIL. Not initialized.");
  141. }
  142. }
  143.  
  144.  
  145. // Restore purchases previously made by this customer. Some platforms automatically restore purchases, like Google.
  146. // Apple currently requires explicit purchase restoration for IAP, conditionally displaying a password prompt.
  147. public void RestorePurchases()
  148. {
  149. // If Purchasing has not yet been set up ...
  150. if (!IsInitialized())
  151. {
  152. // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
  153. Debug.Log("RestorePurchases FAIL. Not initialized.");
  154. return;
  155. }
  156.  
  157. // If we are running on an Apple device ...
  158. if (Application.platform == RuntimePlatform.IPhonePlayer ||
  159. Application.platform == RuntimePlatform.OSXPlayer)
  160. {
  161. // ... begin restoring purchases
  162. Debug.Log("RestorePurchases started ...");
  163.  
  164. // Fetch the Apple store-specific subsystem.
  165. var apple = m_StoreExtensionProvider.GetExtension();
  166. // Begin the asynchronous process of restoring purchases. Expect a confirmation response in
  167. // the Action below, and ProcessPurchase if there are previously purchased products to restore.
  168. apple.RestoreTransactions((result) => {
  169. // The first phase of restoration. If no more responses are received on ProcessPurchase then
  170. // no purchases are available to be restored.
  171. Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
  172. });
  173. }
  174. // Otherwise ...
  175. else
  176. {
  177. // We are not running on an Apple device. No work is necessary to restore purchases.
  178. Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
  179. }
  180. }
  181.  
  182.  
  183. //
  184. // --- IStoreListener
  185. //
  186.  
  187. public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  188. {
  189. // Purchasing has succeeded initializing. Collect our Purchasing references.
  190. Debug.Log("OnInitialized: PASS");
  191.  
  192. // Overall Purchasing system, configured with products for this application.
  193. m_StoreController = controller;
  194. // Store specific subsystem, for accessing device-specific store features.
  195. m_StoreExtensionProvider = extensions;
  196. }
  197.  
  198.  
  199. public void OnInitializeFailed(InitializationFailureReason error)
  200. {
  201. // Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user.
  202. Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
  203. }
  204.  
  205.  
  206. public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
  207. {
  208. // A consumable product has been purchased by this user.
  209. if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal))
  210. {
  211. Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  212. // The consumable item has been successfully purchased, add 100 coins to the player's in-game score.
  213. ScoreManager.score += 100;
  214. }
  215. // Or ... a non-consumable product has been purchased by this user.
  216. else if (String.Equals(args.purchasedProduct.definition.id, kProductIDNonConsumable, StringComparison.Ordinal))
  217. {
  218. Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  219. // TODO: The non-consumable item has been successfully purchased, grant this item to the player.
  220. }
  221. // Or ... a subscription product has been purchased by this user.
  222. else if (String.Equals(args.purchasedProduct.definition.id, kProductIDSubscription, StringComparison.Ordinal))
  223. {
  224. Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  225. // TODO: The subscription item has been successfully purchased, grant this to the player.
  226. }
  227. // Or ... an unknown product has been purchased by this user. Fill in additional products here....
  228. else
  229. {
  230. Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
  231. }
  232.  
  233. // Return a flag indicating whether this product has completely been received, or if the application needs
  234. // to be reminded of this purchase at next app launch. Use PurchaseProcessingResult.Pending when still
  235. // saving purchased products to the cloud, and when that save is delayed.
  236. return PurchaseProcessingResult.Complete;
  237. }
  238.  
  239.  
  240. public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
  241. {
  242. // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing
  243. // this reason with 6 user to guide their troubleshooting actions.
  244. Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
  245. }
  246. }
  247. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement