PaymentManager.cs 6.9 KB

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