PaymentManager.cs 7.4 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. private ConfigurationBuilder builder;
  13. private string itemCode;
  14. public PaymentManager ()
  15. {
  16. builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
  17. List<ShopData> list = ShopManager.GetInstance ().GetDataList ();
  18. for(int i=0; i<list.Count; i++)
  19. {
  20. ShopData shopData = list [i];
  21. if (shopData.sort == BuyUtil.ItemType.VIP.GetHashCode ()) {
  22. builder.AddProduct (shopData.name, ProductType.Subscription, new IDs {
  23. { shopData.ios, AppleAppStore.Name },
  24. { shopData.google, GooglePlay.Name }
  25. });
  26. } else {
  27. builder.AddProduct (shopData.name, ProductType.Consumable, new IDs {
  28. { shopData.ios, AppleAppStore.Name },
  29. { shopData.google, GooglePlay.Name }
  30. });
  31. }
  32. }
  33. validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.bundleIdentifier);
  34. }
  35. public void OnInitialized (IStoreController controller, IExtensionProvider extensions)
  36. {
  37. Debug.Log("Billing initialize!");
  38. this.controller = controller;
  39. this.extensions = extensions;
  40. extensions.GetExtension<IAppleExtensions> ().RefreshAppReceipt ((string result) => {
  41. if (!StringUtil.Empty(result)) {
  42. // Refresh finished successfully.
  43. } else {
  44. // Refresh failed.
  45. }
  46. Debug.Log("RefreshAppReceipt result "+result);
  47. if(!StringUtil.Empty(itemCode))
  48. {
  49. OnPurchaseClicked (itemCode);
  50. }
  51. }, () => {
  52. Debug.Log("RefreshAppReceipt error");
  53. if(!StringUtil.Empty(itemCode))
  54. {
  55. OnPurchaseClicked (itemCode);
  56. }
  57. });
  58. }
  59. /// <summary>
  60. /// Called when Unity IAP encounters an unrecoverable initialization error.
  61. ///
  62. /// Note that this will not be called if Internet is unavailable; Unity IAP
  63. /// will attempt initialization until it becomes available.
  64. /// </summary>
  65. public void OnInitializeFailed (InitializationFailureReason error)
  66. {
  67. Debug.Log("Billing failed to initialize!");
  68. switch (error)
  69. {
  70. case InitializationFailureReason.AppNotKnown:
  71. Debug.LogError("Is your App correctly uploaded on the relevant publisher console?");
  72. break;
  73. case InitializationFailureReason.PurchasingUnavailable:
  74. // Ask the user if billing is disabled in device settings.
  75. Debug.Log("Billing disabled!");
  76. break;
  77. case InitializationFailureReason.NoProductsAvailable:
  78. // Developer configuration error; check product metadata.
  79. Debug.Log("No products available for purchase!");
  80. break;
  81. }
  82. Toast.MakeText(Language.GetStr("Shop", "payFail")+" !");
  83. }
  84. public void OnPurchaseClicked(string productId)
  85. {
  86. if (controller != null) {
  87. itemCode = "";
  88. // ProgressPanel.Show(Language.GetStr("Shop", "payBegin"));
  89. controller.InitiatePurchase (productId);
  90. } else {
  91. itemCode = productId;
  92. UnityPurchasing.Initialize (this, builder);
  93. }
  94. }
  95. /// <summary>
  96. /// Called when a purchase completes.
  97. ///
  98. /// May be called at any time after OnInitialized().
  99. /// </summary>
  100. public PurchaseProcessingResult ProcessPurchase (PurchaseEventArgs e)
  101. {
  102. Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
  103. Debug.Log("Receipt: " + e.purchasedProduct.receipt);
  104. bool isValidation = false;
  105. // #if RECEIPT_VALIDATION
  106. // Local validation is available for GooglePlay and Apple stores
  107. if (Application.platform == RuntimePlatform.Android ||
  108. Application.platform == RuntimePlatform.IPhonePlayer ||
  109. Application.platform == RuntimePlatform.OSXPlayer ||
  110. Application.platform == RuntimePlatform.tvOS) {
  111. try {
  112. Debug.Log("validator "+validator);
  113. var result = validator.Validate(e.purchasedProduct.receipt);
  114. Debug.Log("result "+result);
  115. Debug.Log("Receipt is valid. Contents:");
  116. foreach (IPurchaseReceipt productReceipt in result) {
  117. Debug.Log(productReceipt.productID);
  118. Debug.Log(productReceipt.purchaseDate);
  119. Debug.Log(productReceipt.transactionID);
  120. GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
  121. if (null != google) {
  122. Debug.Log(google.purchaseState);
  123. Debug.Log(google.purchaseToken);
  124. isValidation = true;
  125. }
  126. AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
  127. if (null != apple) {
  128. Debug.Log(apple.originalTransactionIdentifier);
  129. Debug.Log(apple.subscriptionExpirationDate);
  130. Debug.Log(apple.cancellationDate);
  131. Debug.Log(apple.quantity);
  132. isValidation = true;
  133. }
  134. }
  135. } catch (IAPSecurityException) {
  136. Debug.Log("Invalid receipt, not unlocking content");
  137. return PurchaseProcessingResult.Complete;
  138. }
  139. }
  140. // #endif
  141. if (isValidation) {
  142. JsonData receiptJson = JsonMapper.ToObject (e.purchasedProduct.receipt);
  143. string receipt = receiptJson ["Payload"].ToString ();
  144. Debug.Log ("Final receipt " + receipt);
  145. IOSPayment (e.purchasedProduct.definition.id, receipt);
  146. }
  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. }