Guest User

Untitled

a guest
Apr 26th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.65 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using AppsMinistry.InAppPurchases;
  5. using UnityEngine;
  6. using UnityEngine.Purchasing;
  7. using Newtonsoft.Json;
  8. using Prime31;
  9. using AppsMinistry.Common.Utils;
  10. using AppsMinistry.Common.Utils.PlayFab;
  11. using AppsMinistry.Plugins.Analytics;
  12.  
  13. using AppsMinistry.Core;
  14. using AwesomeShooter.App;
  15. using UnityEngine.Advertisements;
  16.  
  17. namespace AppsMinistry.InAppPurchases
  18. {
  19. public class UnityIapStrategy : PurchaseService, IStoreListener
  20. {
  21. private static IStoreController storeController; // Reference to the Purchasing system.
  22. private static IExtensionProvider storeExtensionProvider; // Reference to store-specific Purchasing
  23.  
  24. private Action _OnSuccess;
  25. private Action _OnFail;
  26. private Action _OnCancel;
  27.  
  28. private bool _isPurchasing;
  29. public override bool isPurchasing
  30. {
  31.  
  32. get { return _isPurchasing; }
  33. set
  34. {
  35. _isPurchasing = value;
  36.  
  37. if (_isPurchasing == false)
  38. {
  39. _OnSuccess = null;
  40. _OnFail = null;
  41. _OnCancel = null;
  42. }
  43. }
  44. }
  45.  
  46. private bool IsInitialized
  47. {
  48. get
  49. {
  50. return storeController != null && storeExtensionProvider != null;
  51. }
  52. }
  53.  
  54. public override string GetFormattedPrice(string productID)
  55. {
  56. if (IsInitialized)
  57. {
  58. var product = storeController.products.WithID(productID);
  59. if (product != null)
  60. {
  61. return product.metadata.localizedPriceString;
  62. }
  63. }
  64. return "";
  65. }
  66.  
  67. public override void Initialize()
  68. {
  69. if (!IsInitialized)
  70. {
  71.  
  72. var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  73.  
  74. var catalog = ProductCatalog.LoadDefaultCatalog();
  75.  
  76. foreach (var item in InApps.ALL_INAPPS)
  77. builder.AddProduct(item.ProductID, item.InAppType);
  78. //builder.AddProduct("com.appsministry.inc.awesomeshooter.bannersupply01", ProductType.Consumable);
  79. //builder.AddProduct("com.appsministry.inc.awesomeshooter.bannersupply02", ProductType.Consumable);
  80. builder.AddProduct("com.appsministry.inc.awesomeshooter.bannerskincamo1dd201", ProductType.Consumable);
  81. builder.AddProduct("com.appsministry.inc.awesomeshooter.bannerskincamo2dd202", ProductType.Consumable);
  82. builder.AddProduct("com.appsministry.inc.awesomeshooter.bannerskingettodd203", ProductType.Consumable);
  83.  
  84. UnityPurchasing.Initialize(this, builder);
  85. }
  86.  
  87. }
  88.  
  89. public override void PurchaseProduct(string productId, Action OnSuccess, Action OnFail = null, Action OnCancel = null)
  90. {
  91. Debug.Log("UnityIapStrategy::PurchaseProduct purchase " + productId);
  92. Debug.Log("-----------------------------------------------------------");
  93. Debug.Log("UnityIapStrategy::PurchaseProduct _OnSuccess == null: " + (_OnSuccess == null).ToString() + " _OnFail == null: " + (_OnFail == null).ToString());
  94.  
  95. if (Application.internetReachability == NetworkReachability.NotReachable)
  96. {
  97. Debug.Log("UnityIapStrategy::PurchaseProduct Network NotReachable Show Alert here ");
  98.  
  99. isPurchasing = false;
  100. }
  101. else
  102. {
  103. if (!IsInitialized)
  104. {
  105. Initialize();
  106. isPurchasing = false;
  107. }
  108. else
  109. {
  110. isPurchasing = true;
  111.  
  112. _OnSuccess = OnSuccess;
  113. _OnFail = OnFail;
  114. _OnCancel = OnCancel;
  115. // ... look up the Product reference with the general product identifier and the Purchasing system's products collection.
  116. Product product = storeController.products.WithID(productId);
  117.  
  118. // If the look up found a product for this device's store and that product is ready to be sold ...
  119. if (product != null && product.availableToPurchase)
  120. {
  121. Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));// ... buy the product. Expect a response either through ProcessPurchase or OnPurchaseFailed asynchronously.
  122.  
  123. AnalyticsManager.Instance.TrackInitiateIAP(productId);
  124. storeController.InitiatePurchase(product);
  125. }
  126. // Otherwise ...
  127. else
  128. {
  129. isPurchasing = false;
  130. // ... report the product look-up failure situation
  131. Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
  132. }
  133. }
  134. }
  135. }
  136.  
  137. public override void RestorePurchases()
  138. {
  139. if (!IsInitialized)
  140. {
  141. // ... report the situation and stop restoring. Consider either waiting longer, or retrying initialization.
  142. Debug.Log("RestorePurchases FAIL. Not initialized.");
  143. return;
  144. }
  145.  
  146. // If we are running on an Apple device ...
  147. if (Application.platform == RuntimePlatform.IPhonePlayer ||
  148. Application.platform == RuntimePlatform.OSXPlayer)
  149. {
  150. // ... begin restoring purchases
  151. Debug.Log("RestorePurchases started ...");
  152.  
  153. // Fetch the Apple store-specific subsystem.
  154. var apple = storeExtensionProvider.GetExtension<IAppleExtensions>();
  155. // Begin the asynchronous process of restoring purchases. Expect a confirmation response in
  156. // the Action<bool> below, and ProcessPurchase if there are previously purchased products to restore.
  157. apple.RestoreTransactions((result) =>
  158. {
  159. // The first phase of restoration. If no more responses are received on ProcessPurchase then
  160. // no purchases are available to be restored.
  161. Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
  162.  
  163. if (result)
  164. {
  165. PlatformUtil.ShowAlert("", "All restored");
  166. }
  167. });
  168. }
  169. // Otherwise ...
  170. else
  171. {
  172. // We are not running on an Apple device. No work is necessary to restore purchases.
  173. Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
  174. }
  175. }
  176.  
  177. public override void UpdateSuccessPurchase(string productId, int validThru)
  178. {
  179. Debug.Log("UnityIapStrategy::UpdateSuccessPurchase productId = " + productId + "_OnSuccess == null: " + (_OnSuccess == null).ToString());
  180. PlayFabManager.Instance.PlayFabStore.GetCombinedInfo(delegate (bool success)
  181. {
  182. RaiseUpdateSuccessPurchase(productId, validThru);
  183.  
  184. AppController.Instance.Model.Wallet.SendBuyEvent();
  185. if (_OnSuccess != null)
  186. _OnSuccess();
  187.  
  188. isPurchasing = false;
  189. });
  190. }
  191.  
  192.  
  193. public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
  194. {
  195. Debug.LogFormat("UnityIapStrategy::OnPurchaseSuccessful productID {0}, transactionID {1}", e.purchasedProduct.definition.id, e.purchasedProduct.transactionID);
  196. float productPrice = (float)e.purchasedProduct.metadata.localizedPrice;
  197.  
  198. if (!string.IsNullOrEmpty(e.purchasedProduct.receipt))
  199. {
  200. #if UNITY_IOS
  201. ValidateReceiptAppStore(e.purchasedProduct);
  202. #elif UNITY_ANDROID
  203. ValidateReceiptGooglePlay(e.purchasedProduct);
  204. #endif
  205. }
  206. string description = e.purchasedProduct.metadata.localizedDescription;
  207. string currencyCode = e.purchasedProduct.metadata.isoCurrencyCode;
  208. AnalyticsManager.LogInApp(e.purchasedProduct.transactionID,
  209. description,
  210. e.purchasedProduct.definition.id,
  211. productPrice,
  212. 1,
  213. "BuyServerSuccess",
  214. currencyCode);
  215.  
  216. return PurchaseProcessingResult.Pending;
  217. }
  218.  
  219. void ValidateReceiptAppStore(Product product)
  220. {
  221. var receiptData = JsonConvert.DeserializeObject<Dictionary<string, object>>(product.receipt);
  222.  
  223. var request = new PlayFab.ClientModels.ValidateIOSReceiptRequest();
  224. request.ReceiptData = (string)receiptData["Payload"];
  225. request.PurchasePrice = (int)(product.metadata.localizedPrice * 100);
  226. request.CurrencyCode = product.metadata.isoCurrencyCode;
  227.  
  228. PlayFab.PlayFabClientAPI.ValidateIOSReceipt(request,
  229. delegate (PlayFab.ClientModels.ValidateIOSReceiptResult result)
  230. {
  231. AnalyticsManager.Instance.TrackSuccessfulIAP();
  232. UpdateSuccessPurchase(product.definition.id, -1);
  233. storeController.ConfirmPendingPurchase(product);
  234. },
  235. delegate (PlayFab.PlayFabError error)
  236. {
  237. Debug.LogWarningFormat("<b><color=red>{0}</color></b>", "ValidateIOSReceipt(): " + error.ToString());
  238. isPurchasing = false;
  239. storeController.ConfirmPendingPurchase(product);
  240. });
  241. }
  242.  
  243. void ValidateReceiptGooglePlay(Product product)
  244. {
  245. var receiptData = JsonConvert.DeserializeObject<Dictionary<string, object>>(product.receipt);
  246. var detailsReceipt = JsonConvert.DeserializeObject<Dictionary<string, object>>((string)receiptData["Payload"]);
  247.  
  248. var request = new PlayFab.ClientModels.ValidateGooglePlayPurchaseRequest();
  249. request.ReceiptJson = (string)detailsReceipt["json"];
  250. request.Signature = (string)detailsReceipt["signature"];
  251. request.PurchasePrice = Convert.ToUInt32(product.metadata.localizedPrice * 100);
  252. request.CurrencyCode = product.metadata.isoCurrencyCode;
  253.  
  254. PlayFab.PlayFabClientAPI.ValidateGooglePlayPurchase(request,
  255. delegate (PlayFab.ClientModels.ValidateGooglePlayPurchaseResult result)
  256. {
  257. AnalyticsManager.Instance.TrackSuccessfulIAP();
  258. UpdateSuccessPurchase(product.definition.id, -1);
  259. storeController.ConfirmPendingPurchase(product);
  260. },
  261. delegate (PlayFab.PlayFabError error)
  262. {
  263. string errorMessage = error.ErrorMessage;
  264. Debug.LogWarningFormat("<b><color=red>{0}</color></b>", "ValidateGooglePlayPurchase() " + errorMessage);
  265. isPurchasing = false;
  266. storeController.ConfirmPendingPurchase(product);
  267. });
  268. }
  269.  
  270. public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
  271. {
  272. if (failureReason == PurchaseFailureReason.UserCancelled && _OnCancel != null)
  273. {
  274. _OnCancel();
  275. }
  276. else if (_OnFail != null)
  277. {
  278. _OnFail();
  279. }
  280.  
  281. PlatformUtil.ShowAlert("Purchase Error", failureReason.ToString());
  282. Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
  283. isPurchasing = false;
  284. }
  285.  
  286. public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
  287. {
  288. storeController = controller;
  289. storeExtensionProvider = extensions;
  290. foreach(var product in storeController.products.all)
  291. {
  292. var inapp = InApps.ALL_INAPPS.Find(obj => obj.ProductID == product.definition.id);
  293. if (inapp != null)
  294. {
  295. inapp.Price = product.metadata.localizedPrice.ToString();
  296. inapp.CurrencyCode = product.metadata.isoCurrencyCode;
  297. inapp.Description = product.metadata.localizedDescription;
  298. inapp.FormattedPrice = product.metadata.localizedPriceString;
  299. inapp.TitleLocalizationKey = product.metadata.localizedTitle;
  300. }
  301. }
  302.  
  303. AdsManager.Instance.Initialize();
  304. StartCoroutine(test());
  305. }
  306.  
  307. public void OnInitializeFailed(InitializationFailureReason error)
  308. {
  309. Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
  310.  
  311. AdsManager.Instance.Initialize();
  312.  
  313. }
  314.  
  315. IEnumerator test()
  316. {
  317. while (true)
  318. {
  319. if (Advertisement.IsReady("testPlacement"))
  320. {
  321. Advertisement.Show("testPlacement");
  322. yield break;
  323. }
  324. yield return new WaitForSeconds(1);
  325. }
  326. }
  327. }
  328. }
Add Comment
Please, Sign In to add comment