PaymentManager.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. using UnityEngine;
  2. using UnityEngine.Purchasing;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using LitJson;
  6. using UnityEngine.Purchasing.Security;
  7. public class PaymentManager : IStoreListener
  8. {
  9. private IStoreController controller;
  10. private IExtensionProvider extensions;
  11. private CrossPlatformValidator validator;
  12. private ConfigurationBuilder builder;
  13. private string itemCode;
  14. public PaymentManager ()
  15. {
  16. builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  17. builder.AddProduct("VIP4", ProductType.Subscription, new IDs
  18. {
  19. {"VIP4_EN", GooglePlay.Name},
  20. {"VIP4_EN", AppleAppStore.Name}
  21. });
  22. builder.AddProduct("C10000", ProductType.Consumable, new IDs
  23. {
  24. {"C10000_EN", GooglePlay.Name},
  25. {"C10000_EN", AppleAppStore.Name}
  26. });
  27. builder.AddProduct("C25000", ProductType.Consumable, new IDs
  28. {
  29. {"C25000_EN", GooglePlay.Name},
  30. {"C25000_EN", AppleAppStore.Name}
  31. });
  32. builder.AddProduct("C75000", ProductType.Consumable, new IDs
  33. {
  34. {"C75000_EN", GooglePlay.Name},
  35. {"C75000_EN", AppleAppStore.Name}
  36. });
  37. #if RECEIPT_VALIDATION
  38. validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
  39. #endif
  40. }
  41. public void OnInitialized (IStoreController controller, IExtensionProvider extensions)
  42. {
  43. Debug.Log("Billing initialize!");
  44. this.controller = controller;
  45. this.extensions = extensions;
  46. extensions.GetExtension<IAppleExtensions> ().RefreshAppReceipt ((string result) => {
  47. if (!StringUtil.Empty(result)) {
  48. // Refresh finished successfully.
  49. } else {
  50. // Refresh failed.
  51. }
  52. Debug.Log("RefreshAppReceipt result "+result);
  53. if(!StringUtil.Empty(itemCode))
  54. {
  55. OnPurchaseClicked (itemCode);
  56. }
  57. }, () => {
  58. Debug.Log("RefreshAppReceipt error");
  59. if(!StringUtil.Empty(itemCode))
  60. {
  61. OnPurchaseClicked (itemCode);
  62. }
  63. });
  64. }
  65. /// <summary>
  66. /// Called when Unity IAP encounters an unrecoverable initialization error.
  67. ///
  68. /// Note that this will not be called if Internet is unavailable; Unity IAP
  69. /// will attempt initialization until it becomes available.
  70. /// </summary>
  71. public void OnInitializeFailed (InitializationFailureReason error)
  72. {
  73. Debug.Log("Billing failed to initialize!");
  74. switch (error)
  75. {
  76. case InitializationFailureReason.AppNotKnown:
  77. Debug.LogError("Is your App correctly uploaded on the relevant publisher console?");
  78. break;
  79. case InitializationFailureReason.PurchasingUnavailable:
  80. // Ask the user if billing is disabled in device settings.
  81. Debug.Log("Billing disabled!");
  82. break;
  83. case InitializationFailureReason.NoProductsAvailable:
  84. // Developer configuration error; check product metadata.
  85. Debug.Log("No products available for purchase!");
  86. break;
  87. }
  88. Toast.MakeText(Language.GetStr("Shop", "payFail")+" !");
  89. }
  90. public void OnPurchaseClicked(string productId)
  91. {
  92. if (controller != null) {
  93. itemCode = "";
  94. // ProgressPanel.Show(Language.GetStr("Shop", "payBegin"));
  95. controller.InitiatePurchase (productId);
  96. } else {
  97. itemCode = productId;
  98. UnityPurchasing.Initialize (this, builder);
  99. }
  100. }
  101. /// <summary>
  102. /// Called when a purchase completes.
  103. ///
  104. /// May be called at any time after OnInitialized().
  105. /// </summary>
  106. public PurchaseProcessingResult ProcessPurchase (PurchaseEventArgs e)
  107. {
  108. Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
  109. Debug.Log("Receipt: " + e.purchasedProduct.receipt);
  110. // #if RECEIPT_VALIDATION
  111. // Local validation is available for GooglePlay and Apple stores
  112. if (Application.platform == RuntimePlatform.Android ||
  113. Application.platform == RuntimePlatform.IPhonePlayer ||
  114. Application.platform == RuntimePlatform.OSXPlayer ||
  115. Application.platform == RuntimePlatform.tvOS) {
  116. try {
  117. var result = validator.Validate(e.purchasedProduct.receipt);
  118. Debug.Log("Receipt is valid. Contents:");
  119. foreach (IPurchaseReceipt productReceipt in result) {
  120. Debug.Log(productReceipt.productID);
  121. Debug.Log(productReceipt.purchaseDate);
  122. Debug.Log(productReceipt.transactionID);
  123. GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
  124. if (null != google) {
  125. Debug.Log(google.purchaseState);
  126. Debug.Log(google.purchaseToken);
  127. }
  128. AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
  129. if (null != apple) {
  130. Debug.Log(apple.originalTransactionIdentifier);
  131. Debug.Log(apple.subscriptionExpirationDate);
  132. Debug.Log(apple.cancellationDate);
  133. Debug.Log(apple.quantity);
  134. IOSPayment(e.purchasedProduct.definition.id, e.purchasedProduct.receipt);
  135. }
  136. }
  137. } catch (IAPSecurityException) {
  138. Debug.Log("Invalid receipt, not unlocking content");
  139. return PurchaseProcessingResult.Complete;
  140. }
  141. }
  142. // #endif
  143. return PurchaseProcessingResult.Complete;
  144. }
  145. /// <summary>
  146. /// Called when a purchase fails.
  147. /// </summary>
  148. public void OnPurchaseFailed (Product item, PurchaseFailureReason r)
  149. {
  150. Debug.Log("Purchase failed: " + item.definition.id);
  151. Debug.Log(r);
  152. Toast.MakeText(Language.GetStr("Shop", "payFail")+" !!!");
  153. ProgressPanel.Hide();
  154. }
  155. public void IOSPayment(string product, string receipt)
  156. {
  157. UserData userData = Session.GetInstance ().myUserData;
  158. URLRequestData data = new URLRequestData(true);
  159. data.Add("userid", userData.id);
  160. data.Add("item", product);
  161. data.Add("receipt", receipt);
  162. URLRequest.CreateURLRequest(NetworkManager.GetURL(NetworkManager.URL.IOSPayment), data, (JsonData json)=>{
  163. int resCode = JsonUtil.ToInt(json["c"]);
  164. if(resCode == 0)
  165. {
  166. JsonData info = json["d"];
  167. if(JsonUtil.ContainKey(info, "d"))
  168. {
  169. userData.diamond = JsonUtil.ToInt(info["d"]);
  170. }
  171. if(JsonUtil.ContainKey(info, "c"))
  172. {
  173. userData.coin = JsonUtil.ToInt(info["c"]);
  174. }
  175. if(JsonUtil.ContainKey(info, "v"))
  176. {
  177. userData.vipExpireTime = info["v"].ToString();
  178. }
  179. BuyUtil.Bought(product);
  180. }
  181. ProgressPanel.Hide();
  182. }, URLRequest.Method.POST);
  183. }
  184. public void IOSPayment(string result)
  185. {
  186. string[] strArr = StringUtil.Split(result, '|');
  187. string itemCode = strArr[0];
  188. string receipt = strArr.Length > 1 ? strArr[1] : "none";
  189. UserData userData = Session.GetInstance ().myUserData;
  190. URLRequestData data = new URLRequestData(true);
  191. data.Add("userid", userData.id);
  192. data.Add("item", itemCode);
  193. data.Add("receipt", receipt);
  194. URLRequest.CreateURLRequest(NetworkManager.GetURL(NetworkManager.URL.IOSPayment), data, (JsonData json)=>{
  195. int resCode = JsonUtil.ToInt(json["c"]);
  196. if(resCode == 0)
  197. {
  198. JsonData info = json["d"];
  199. if(JsonUtil.ContainKey(info, "d"))
  200. {
  201. userData.diamond = JsonUtil.ToInt(info["d"]);
  202. }
  203. if(JsonUtil.ContainKey(info, "c"))
  204. {
  205. userData.coin = JsonUtil.ToInt(info["c"]);
  206. }
  207. if(JsonUtil.ContainKey(info, "v"))
  208. {
  209. userData.vipExpireTime = info["v"].ToString();
  210. }
  211. BuyUtil.Bought(itemCode);
  212. }
  213. ProgressPanel.Hide();
  214. }, URLRequest.Method.POST);
  215. }
  216. private static PaymentManager instance;
  217. public static PaymentManager GetIntance()
  218. {
  219. if(instance == null)
  220. {
  221. instance = new PaymentManager ();
  222. }
  223. return instance;
  224. }
  225. }