Advertisement
Guest User

Untitled

a guest
May 2nd, 2016
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.97 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.Purchasing;
  6.  
  7. // Placing the Purchaser class in the CompleteProject namespace allows it to interact with ScoreManager, one of the existing Survival Shooter scripts.
  8. namespace CompleteProject
  9. {
  10.  
  11. // Deriving the Purchaser class from IStoreListener enables it to receive messages from Unity Purchasing.
  12. public class Purchaser : MonoBehaviour, IStoreListener
  13. {
  14.  
  15. public static int totalAmountOfCourses = 12;
  16.  
  17. private static IStoreController m_StoreController; // Reference to the Purchasing system.
  18. private static IExtensionProvider m_StoreExtensionProvider; // Reference to store-specific Purchasing subsystems.
  19.  
  20. // Product identifiers for all products capable of being purchased: "convenience" general identifiers for use with Purchasing, and their store-specific identifier counterparts
  21. // for use with and outside of Unity Purchasing. Define store-specific identifiers also on each platform's publisher dashboard (iTunes Connect, Google Play Developer Console, etc.)
  22.  
  23. public static string productMonthlySub = "KidsVsPhonics.MonthlySubscription";
  24. public static string[] productUnlockLevel = new string[totalAmountOfCourses];
  25. public static string productUnlockAll = "KidsVsPhonics.UnlockAllLevels";
  26. //private int courseInterested;
  27.  
  28. public Text alertText;
  29.  
  30. void Start()
  31. {
  32.  
  33. for (int i = 1; i < totalAmountOfCourses; i++)
  34. {
  35. productUnlockLevel[i] = "KidsVsPhonics.UnlockLevel" + i;
  36. //print("unlocked " + i);
  37. }
  38.  
  39. // If we haven't set up the Unity Purchasing reference
  40. if (m_StoreController == null)
  41. {
  42. // Begin to configure our connection to Purchasing
  43. InitializePurchasing();
  44. }
  45. }
  46.  
  47. public void InitializePurchasing()
  48. {
  49. // If we have already connected to Purchasing ...
  50. if (IsInitialized())
  51. {
  52. // ... we are done here.
  53. return;
  54. }
  55.  
  56. // Create a builder, first passing in a suite of Unity provided stores.
  57. var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  58.  
  59. for (int i = 1; i < totalAmountOfCourses; i++)
  60. {
  61. builder.AddProduct(productUnlockLevel[i], ProductType.NonConsumable, new IDs()
  62. {
  63. { productUnlockLevel[i], AppleAppStore.Name },
  64. { (productUnlockLevel[i]).ToLower(), GooglePlay.Name },
  65. });
  66. }
  67. builder.AddProduct(productUnlockAll, ProductType.NonConsumable, new IDs()
  68. {
  69. { productUnlockAll, AppleAppStore.Name },
  70. { productUnlockAll.ToLower(), GooglePlay.Name },
  71. });
  72. builder.AddProduct(productMonthlySub, ProductType.Subscription, new IDs()
  73. {
  74. { productMonthlySub, AppleAppStore.Name },
  75. { productMonthlySub.ToLower(), GooglePlay.Name },
  76. });
  77.  
  78. UnityPurchasing.Initialize(this, builder);
  79. }
  80.  
  81.  
  82. private bool IsInitialized()
  83. {
  84. // Only say we are initialized if both the Purchasing references are set.
  85. return m_StoreController != null && m_StoreExtensionProvider != null;
  86. }
  87.  
  88.  
  89. public void BuyOneLevel()
  90. {
  91. // Buy the non-consumable product using its general identifier. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  92. #if UNITY_ANDROID
  93. BuyProductID(productUnlockLevel[PlayerPrefs.GetInt("courseInterested")].ToLower());
  94. #endif
  95.  
  96. #if UNITY_IPHONE
  97. BuyProductID(productUnlockLevel[PlayerPrefs.GetInt("courseInterested")]);
  98. #endif
  99. }
  100.  
  101. public void BuyAllLevels()
  102. {
  103. // Buy the non-consumable product using its general identifier. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  104. #if UNITY_ANDROID
  105. BuyProductID(productUnlockAll.ToLower());
  106. #endif
  107.  
  108. #if UNITY_IPHONE
  109. BuyProductID(productUnlockAll);
  110. #endif
  111. }
  112.  
  113. public void BuySubscription()
  114. {
  115. // Buy the subscription product using its the general identifier. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  116. #if UNITY_ANDROID
  117. BuyProductID(productMonthlySub.ToLower());
  118. #endif
  119.  
  120. #if UNITY_IPHONE
  121. BuyProductID(productMonthlySub);
  122. #endif
  123. }
  124.  
  125.  
  126. void BuyProductID(string productId)
  127. {
  128. // If the stores throw an unexpected exception, use try..catch to protect my logic here.
  129. try
  130. {
  131. // If Purchasing has been initialized ...
  132. if (IsInitialized())
  133. {
  134. // ... look up the Product reference with the general product identifier and the Purchasing system's products collection.
  135. Product product = m_StoreController.products.WithID(productId);
  136. print("Initialised. Trying to purchase: " + productId);
  137.  
  138. // If the look up found a product for this device's store and that product is ready to be sold ...
  139. if (product != null && product.availableToPurchase)
  140. {
  141. Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));// ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  142. alertText.text = string.Format("Purchasing product asychronously: '{0}'", product.definition.id);
  143. m_StoreController.InitiatePurchase(product);
  144. }
  145. // Otherwise ...
  146. else
  147. {
  148. // ... report the product look-up failure situation
  149. Debug.Log("BuyProductID: FAIL. Not purchasing product '" + productId + "', either is not found or is not available for purchase");
  150. alertText.text = "BuyProductID: FAIL. Not purchasing product '" + productId + "', either is not found or is not available for purchase";
  151. }
  152. }
  153. // Otherwise ...
  154. else
  155. {
  156. // ... report the fact Purchasing has not succeeded initializing yet. Consider waiting longer or retrying initiailization.
  157. Debug.Log("BuyProductID FAIL. Not initialized.");
  158. alertText.text = "BuyProductID FAIL. Not initialized.";
  159. }
  160. }
  161. // Complete the unexpected exception handling ...
  162. catch (Exception e)
  163. {
  164. // ... by reporting any unexpected exception for later diagnosis.
  165. Debug.Log("BuyProductID: FAIL. Exception during purchase. " + e);
  166. alertText.text = "BuyProductID: FAIL. Exception during purchase. " + e;
  167. }
  168. }
  169.  
  170.  
  171. // Restore purchases previously made by this customer. Some platforms automatically restore purchases. Apple currently requires explicit purchase restoration for IAP.
  172. public void RestorePurchases()
  173. {
  174. // If Purchasing has not yet been set up ...
  175. if (!IsInitialized())
  176. {
  177. // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
  178. Debug.Log("RestorePurchases FAIL. Not initialized.");
  179. alertText.text = "RestorePurchases FAIL. Not initialized.";
  180. return;
  181. }
  182.  
  183. // If we are running on an Apple device ...
  184. if (Application.platform == RuntimePlatform.IPhonePlayer ||
  185. Application.platform == RuntimePlatform.OSXPlayer)
  186. {
  187. // ... begin restoring purchases
  188. Debug.Log("RestorePurchases started ...");
  189.  
  190. // Fetch the Apple store-specific subsystem.
  191. var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
  192. // Begin the asynchronous process of restoring purchases. Expect a confirmation response in the Action<bool> below, and ProcessPurchase if there are previously purchased products to restore.
  193. apple.RestoreTransactions((result) => {
  194. // The first phase of restoration. If no more responses are received on ProcessPurchase then no purchases are available to be restored.
  195. Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
  196. alertText.text = "RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.";
  197. });
  198. }
  199. // Otherwise ...
  200. else
  201. {
  202. // We are not running on an Apple device. No work is necessary to restore purchases.
  203. Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
  204. alertText.text = "RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform;
  205. }
  206. }
  207.  
  208.  
  209. //
  210. // --- IStoreListener
  211. //
  212.  
  213. public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  214. {
  215. // Purchasing has succeeded initializing. Collect our Purchasing references.
  216. Debug.Log("[IAP] OnInitialized: PASS");
  217. alertText.text = "OnInitialized: PASS";
  218.  
  219. // Overall Purchasing system, configured with products for this application.
  220. m_StoreController = controller;
  221. // Store specific subsystem, for accessing device-specific store features.
  222. m_StoreExtensionProvider = extensions;
  223. }
  224.  
  225.  
  226. public void OnInitializeFailed(InitializationFailureReason error)
  227. {
  228. // Purchasing set-up has not succeeded. Check error for reason. Consider sharing this reason with the user.
  229. Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
  230. alertText.text = "OnInitializeFailed InitializationFailureReason:" + error;
  231. }
  232.  
  233.  
  234. public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
  235. {
  236. for (int i = 1; i < totalAmountOfCourses; i++)
  237. {
  238. if (String.Equals(args.purchasedProduct.definition.id, productUnlockLevel[i], StringComparison.Ordinal))
  239. {
  240. 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.
  241. alertText.text = string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id);
  242. PlayerPrefs.SetInt("purchasedCourse" + PlayerPrefs.GetInt("courseInterested"), 1);
  243.  
  244. return PurchaseProcessingResult.Complete;
  245. }
  246. }
  247.  
  248. if (String.Equals(args.purchasedProduct.definition.id, productUnlockAll, StringComparison.Ordinal))
  249. {
  250. Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  251. alertText.text = string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id);
  252.  
  253. for (int i = 1; i < totalAmountOfCourses; i++)
  254. {
  255. PlayerPrefs.SetInt("purchasedCourse" + i, 1);
  256. }
  257. }// Or ... a subscription product has been purchased by this user.
  258. else if (String.Equals(args.purchasedProduct.definition.id, productMonthlySub, StringComparison.Ordinal))
  259. {
  260. Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
  261. alertText.text = string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id);
  262.  
  263. for (int i = 1; i < totalAmountOfCourses; i++)
  264. {
  265. PlayerPrefs.SetInt("purchasedCourse" + i, 1);
  266. }
  267. }// Or ... an unknown product has been purchased by this user. Fill in additional products here.
  268. else
  269. {
  270. Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
  271. alertText.text = string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id);
  272. }// 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.
  273. return PurchaseProcessingResult.Complete;
  274. }
  275.  
  276.  
  277. public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
  278. {
  279. // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing this reason with the user.
  280. Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
  281. alertText.text = string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason);
  282. }
  283. }
  284. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement