Ingen beskrivning
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WinRTStore.cs 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using Windows.ApplicationModel.Core;
  8. using Windows.ApplicationModel.Store;
  9. using Windows.System;
  10. using Windows.UI.Core;
  11. #pragma warning disable 4014
  12. namespace UnityEngine.Purchasing.Default
  13. {
  14. class WinRTStore : IWindowsIAP
  15. {
  16. private IWindowsIAPCallback callback;
  17. private ICurrentApp currentApp;
  18. private Dictionary<string, string> transactionIdToProductId = new Dictionary<string, string>();
  19. private int m_loginDelay;
  20. public WinRTStore(ICurrentApp currentApp)
  21. {
  22. this.currentApp = currentApp;
  23. }
  24. public void Initialize(IWindowsIAPCallback callback)
  25. {
  26. this.callback = callback;
  27. this.m_loginDelay = 30;
  28. }
  29. public void Initialize(IWindowsIAPCallback callback, int delayTime = 30)
  30. {
  31. this.callback = callback;
  32. this.m_loginDelay = delayTime;
  33. }
  34. public void SetLoginDelay(int delayTime)
  35. {
  36. this.m_loginDelay = delayTime;
  37. }
  38. public int LoginDelay()
  39. {
  40. return m_loginDelay;
  41. }
  42. public void RetrieveProducts(bool persistent)
  43. {
  44. RunOnUIThread(() =>
  45. {
  46. if (LoginDelay() > 0)
  47. {
  48. PollForProducts(persistent, 0, LoginDelay(), true, false);
  49. }
  50. else
  51. {
  52. PollForProducts(persistent, 0);
  53. }
  54. });
  55. }
  56. private async void PollForProducts(bool persistent, int delay, int retryCount = 10, bool tryLogin = false, bool loginAttempted = false, bool productsOnly = false)
  57. {
  58. await Task.Delay(delay);
  59. try
  60. {
  61. var result = await DoRetrieveProducts(productsOnly);
  62. callback.OnProductListReceived(result);
  63. }
  64. catch (Exception e)
  65. {
  66. LogError("PollForProducts() Exception (persistent = {0}, delay = {1}, retry = {2}), exception: {3}", persistent, delay, retryCount, e.Message);
  67. // NB: persistent here is used to distinguish when this is used by restoreTransactions() so we will
  68. // keep it intact and supplement for retries on initialization
  69. //
  70. if (persistent)
  71. {
  72. // This seems to indicate the App is not uploaded on
  73. // the dev portal, but is undocumented by Microsoft.
  74. if (e.Message.Contains("801900CC"))
  75. {
  76. LogError("Exception loading listing information: {0}", e.Message);
  77. callback.OnProductListError("AppNotKnown");
  78. // JDRjr: in the main store code this is not being checked correctly
  79. // and will result in repeated init attempts. Leaving it for now, but broken...
  80. }
  81. else if (e.Message.Contains("80070525"))
  82. {
  83. LogError("PollForProducts() User not signed in error HResult = 0x{0:X} (delay = {1}, retry = {2})", e.HResult, delay, retryCount);
  84. if ((delay == 0) && (productsOnly == false))
  85. {
  86. // First time failure give products only a try
  87. PollForProducts(true, 1000, retryCount, tryLogin, loginAttempted, true);
  88. }
  89. else
  90. {
  91. // Gonna call this an error
  92. LogError("Calling OnProductListError() delay = {0}, productsOnly = {1}", delay, productsOnly);
  93. callback.OnProductListError("801900CC because the C# code is broken");
  94. }
  95. }
  96. else
  97. {
  98. // other (no special handling) error codes
  99. // Wait up to 5 mins.
  100. // JDRjr: this seems like too long...
  101. delay = Math.Max(5000, delay);
  102. var newDelay = Math.Min(300000, delay * 2);
  103. PollForProducts(true, newDelay);
  104. }
  105. }
  106. else
  107. {
  108. // This is a restore attempt that has thrown an exception
  109. // We should allow for a login attempt here as well...
  110. if (tryLogin == true)
  111. {
  112. var uri = new Uri("ms-windows-store://signin");
  113. var loginResult = await global::Windows.System.Launcher.LaunchUriAsync(uri);
  114. PollForProducts(true, 1000, retryCount, false, true, false);
  115. }
  116. else
  117. {
  118. if (retryCount > 0)
  119. {
  120. if (loginAttempted)
  121. {
  122. // Will wait for retryCount seconds...
  123. PollForProducts(true, 1000, --retryCount, false, true);
  124. }
  125. else
  126. {
  127. // Wait up to 5 mins.
  128. delay = Math.Max(5000, delay);
  129. var newDelay = Math.Min(300000, delay * 2);
  130. PollForProducts(true, newDelay, --retryCount, false, false);
  131. }
  132. }
  133. else
  134. {
  135. callback.OnProductListError("801900CC because the C# code is broken");
  136. }
  137. }
  138. }
  139. } // end of catch()
  140. }
  141. private async Task<WinProductDescription[]> DoRetrieveProducts(bool productsOnly)
  142. {
  143. ListingInformation result = await currentApp.LoadListingInformationAsync();
  144. if (productsOnly == false)
  145. {
  146. // We need a comprehensive list of transaction IDs for owned items.
  147. // Microsoft make this difficult by failing to provide transaction IDs
  148. // on product licenses that are owned.
  149. // Therefore two data sets are joined; unfulfilled consumables (which have product IDs)
  150. // and transactions from the App receipt (Durables).
  151. var unfulfilledConsumables = await currentApp.GetUnfulfilledConsumablesAsync();
  152. var transactionMap = unfulfilledConsumables.ToDictionary(x => x.ProductId, x => x.TransactionId.ToString());
  153. // Add transaction IDs from our app receipt.
  154. string appReceipt = null;
  155. try
  156. {
  157. appReceipt = await currentApp.RequestAppReceiptAsync();
  158. }
  159. catch (Exception e)
  160. {
  161. LogError("Unable to retrieve app receipt:{0}", e.Message);
  162. }
  163. var receiptTransactions = XMLUtils.ParseProducts(appReceipt);
  164. foreach (var receiptTran in receiptTransactions)
  165. {
  166. transactionMap[receiptTran.productId] = receiptTran.transactionId;
  167. }
  168. // Create fake transaction Ids for any owned items that we can't find transaction IDs for.
  169. foreach (var license in currentApp.LicenseInformation.ProductLicenses)
  170. {
  171. if (!transactionMap.ContainsKey(license.Key))
  172. {
  173. transactionMap[license.Key] = license.Key.GetHashCode().ToString();
  174. }
  175. }
  176. // Construct our products including receipts and transaction ID where owned
  177. var productDescriptions = from listing in result.ProductListings.Values
  178. let priceDecimal = TryParsePrice(listing.FormattedPrice)
  179. let transactionId = transactionMap.ContainsKey(listing.ProductId) ? transactionMap[listing.ProductId] : null
  180. let receipt = transactionId == null ? null : appReceipt
  181. select new WinProductDescription(listing.ProductId,
  182. listing.FormattedPrice, listing.Name, string.Empty, RegionInfo.CurrentRegion.ISOCurrencySymbol,
  183. priceDecimal, receipt, transactionId);
  184. // Transaction IDs tracked for finalising transactions
  185. transactionIdToProductId = transactionMap.ToDictionary(x => x.Value, x => x.Key);
  186. return productDescriptions.ToArray();
  187. }
  188. else
  189. {
  190. var productDescriptions = from listing in result.ProductListings.Values
  191. let priceDecimal = TryParsePrice(listing.FormattedPrice)
  192. select new WinProductDescription(listing.ProductId,
  193. listing.FormattedPrice, listing.Name, string.Empty, RegionInfo.CurrentRegion.ISOCurrencySymbol,
  194. priceDecimal, null, null);
  195. return productDescriptions.ToArray();
  196. }
  197. }
  198. private decimal TryParsePrice(string formattedPrice)
  199. {
  200. decimal price = 0;
  201. decimal.TryParse(formattedPrice, NumberStyles.Currency, CultureInfo.CurrentCulture, out price);
  202. return price;
  203. }
  204. public void Purchase(string productId)
  205. {
  206. RunOnUIThread(async () =>
  207. {
  208. try
  209. {
  210. var result = await currentApp.RequestProductPurchaseAsync(productId);
  211. switch (result.Status)
  212. {
  213. case ProductPurchaseStatus.Succeeded:
  214. onPurchaseSucceeded(productId, result.ReceiptXml, result.TransactionId);
  215. break;
  216. case ProductPurchaseStatus.NotFulfilled:
  217. case ProductPurchaseStatus.AlreadyPurchased:
  218. case ProductPurchaseStatus.NotPurchased:
  219. callback.OnPurchaseFailed(productId, result.Status.ToString());
  220. break;
  221. }
  222. }
  223. catch (Exception e)
  224. {
  225. callback.OnPurchaseFailed(productId, e.Message);
  226. }
  227. });
  228. }
  229. private async Task FulfillConsumable(string productId, string transactionId)
  230. {
  231. try
  232. {
  233. var result = await currentApp.ReportConsumableFulfillmentAsync(productId, Guid.Parse(transactionId));
  234. if (FulfillmentResult.Succeeded == result)
  235. {
  236. lock (transactionIdToProductId)
  237. {
  238. transactionIdToProductId.Remove(transactionId);
  239. }
  240. }
  241. // It doesn't matter if the consumption succeeds or not.
  242. // If it doesn't, it will eventually be retried automatically.
  243. }
  244. catch (Exception e)
  245. {
  246. LogError("Exception consuming {0} : {1} (non-fatal)", productId, e.Message);
  247. }
  248. }
  249. private void LogError(string message, params object[] formatArgs)
  250. {
  251. callback.logError(string.Format("UnityIAPWin8:" + message, formatArgs));
  252. }
  253. private void onPurchaseSucceeded(string productId, string receipt, Guid transactionId)
  254. {
  255. var tranId = transactionId.ToString();
  256. // Make a note of which product this transaction pertains to.
  257. lock (transactionIdToProductId)
  258. {
  259. transactionIdToProductId[tranId] = productId;
  260. }
  261. callback.OnPurchaseSucceeded(productId, receipt, tranId);
  262. }
  263. public void FinaliseTransaction(string transactionId)
  264. {
  265. RunOnUIThread(() =>
  266. {
  267. // We occasionally supply null transaction IDs,
  268. // to the biller for owned non consumables.
  269. // The biller will try to finalise these, so we
  270. // ignore them.
  271. if (!string.IsNullOrEmpty(transactionId))
  272. {
  273. if (transactionIdToProductId.ContainsKey(transactionId))
  274. {
  275. FulfillConsumable(transactionIdToProductId[transactionId], transactionId);
  276. }
  277. else
  278. {
  279. callback.logError("Nothing to fulfill for transaction " + transactionId);
  280. }
  281. }
  282. });
  283. }
  284. private static void RunOnUIThread(Action a)
  285. {
  286. CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
  287. {
  288. a();
  289. });
  290. }
  291. /// <summary>
  292. /// Builds a dummy list of Products.
  293. /// </summary>
  294. /// <param name="products"> The list of product descriptions. </param>
  295. public void BuildDummyProducts(List<WinProductDescription> products)
  296. {
  297. currentApp.BuildMockProducts(products);
  298. }
  299. }
  300. }
  301. #pragma warning restore 4014