PaymentManager.cs 7.6 KB

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