UdpSynchronizationApi.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. using UnityEngine.Purchasing;
  9. namespace UnityEditor.Purchasing
  10. {
  11. /// <summary>
  12. /// Synchronize store data from UDP and IAP
  13. /// </summary>
  14. public static class UdpSynchronizationApi
  15. {
  16. internal const string kOAuthClientId = "channel_editor";
  17. // Although a client secret is here, it doesn't matter
  18. // because the user information is also secured by user's token
  19. private const string kOAuthClientSecret = "B63AFB324DE3D12A13827340019D1EE3";
  20. private const string kHttpVerbGET = "GET";
  21. private const string kHttpVerbPOST = "POST";
  22. private const string kHttpVerbPUT = "PUT";
  23. private const string kContentType = "Content-Type";
  24. private const string kApplicationJson = "application/json";
  25. private const string kAuthHeader = "Authorization";
  26. private static void CheckUdpBuildConfig()
  27. {
  28. Type udpBuildConfig = BuildConfigInterface.GetClassType();
  29. if (udpBuildConfig == null)
  30. {
  31. Debug.LogError("Cannot Retrieve Build Config Endpoints for UDP. Please make sure the UDP package is installed");
  32. throw new NotImplementedException();
  33. }
  34. }
  35. /// <summary>
  36. /// Get Access Token according to authCode.
  37. /// </summary>
  38. /// <param name="authCode"> Acquired by UnityOAuth</param>
  39. /// <returns></returns>
  40. [Obsolete("Internal API, it will be removed soon.")]
  41. public static object GetAccessToken(string authCode)
  42. {
  43. return CreateGetAccessTokenRequest(authCode);
  44. }
  45. /// <summary>
  46. /// Create a Web Request to get the UDP Access Token according to authCode.
  47. /// </summary>
  48. /// <param name="authCode">Acquired by UnityOAuth</param>
  49. /// <returns></returns>
  50. internal static UnityWebRequest CreateGetAccessTokenRequest(string authCode)
  51. {
  52. CheckUdpBuildConfig();
  53. TokenRequest req = new TokenRequest();
  54. req.code = authCode;
  55. req.client_id = kOAuthClientId;
  56. req.client_secret = kOAuthClientSecret;
  57. req.grant_type = "authorization_code";
  58. req.redirect_uri = BuildConfigInterface.GetIdEndpoint();
  59. return AsyncRequest(kHttpVerbPOST, BuildConfigInterface.GetApiEndpoint(), "/v1/oauth2/token", null, req);
  60. }
  61. /// <summary>
  62. /// Call UDP store asynchronously to retrieve the Organization Identifier.
  63. /// </summary>
  64. /// <param name="accessToken">The bearer token to UDP.</param>
  65. /// <param name="projectGuid">The project id.</param>
  66. /// <returns>The HTTP GET Request to get the organization identifier.</returns>
  67. [Obsolete("Internal API, it will be removed soon.")]
  68. public static object GetOrgId(string accessToken, string projectGuid)
  69. {
  70. return CreateGetOrgIdRequest(accessToken, projectGuid);
  71. }
  72. /// <summary>
  73. /// Call UDP store asynchronously to retrieve the Organization Identifier.
  74. /// </summary>
  75. /// <param name="accessToken">The bearer token to UDP.</param>
  76. /// <param name="projectGuid">The project id.</param>
  77. /// <returns>The HTTP GET Request to get the organization identifier.</returns>
  78. internal static UnityWebRequest CreateGetOrgIdRequest(string accessToken, string projectGuid)
  79. {
  80. CheckUdpBuildConfig();
  81. string api = "/v1/core/api/projects/" + projectGuid;
  82. return AsyncRequest(kHttpVerbGET, BuildConfigInterface.GetApiEndpoint(), api, accessToken, null);
  83. }
  84. /// <summary>
  85. /// Call UDP store asynchronously to create a store item.
  86. /// </summary>
  87. /// <param name="accessToken">The bearer token to UDP.</param>
  88. /// <param name="orgId">The organization identifier to create the store item under.</param>
  89. /// <param name="iapItem">The store item to create.</param>
  90. /// <returns>The HTTP POST Request to create a store item.</returns>
  91. [Obsolete("Internal API, it will be removed soon.")]
  92. public static object CreateStoreItem(string accessToken, string orgId, IapItem iapItem)
  93. {
  94. return CreateAddStoreItemRequest(accessToken, orgId, iapItem);
  95. }
  96. /// <summary>
  97. /// Call UDP store asynchronously to create a store item.
  98. /// </summary>
  99. /// <param name="accessToken">The bearer token to UDP.</param>
  100. /// <param name="orgId">The organization identifier to create the store item under.</param>
  101. /// <param name="iapItem">The store item to create.</param>
  102. /// <returns>The HTTP POST Request to create a store item.</returns>
  103. internal static UnityWebRequest CreateAddStoreItemRequest(string accessToken, string orgId, IapItem iapItem)
  104. {
  105. CheckUdpBuildConfig();
  106. string api = "/v1/store/items";
  107. iapItem.ownerId = orgId;
  108. return AsyncRequest(kHttpVerbPOST, BuildConfigInterface.GetUdpEndpoint(), api, accessToken, iapItem);
  109. }
  110. /// <summary>
  111. /// Call UDP store asynchronously to update a store item.
  112. /// </summary>
  113. /// <param name="accessToken">The bearer token to UDP.</param>
  114. /// <param name="iapItem">The updated store item.</param>
  115. /// <returns>The HTTP PUT Request to update a store item.</returns>
  116. [Obsolete("Internal API, it will be removed soon.")]
  117. public static object UpdateStoreItem(string accessToken, IapItem iapItem)
  118. {
  119. return CreateUpdateStoreItemRequest(accessToken, iapItem);
  120. }
  121. /// <summary>
  122. /// Call UDP store asynchronously to update a store item.
  123. /// </summary>
  124. /// <param name="accessToken">The bearer token to UDP.</param>
  125. /// <param name="iapItem">The updated store item.</param>
  126. /// <returns>The HTTP PUT Request to update a store item.</returns>
  127. internal static UnityWebRequest CreateUpdateStoreItemRequest(string accessToken, IapItem iapItem)
  128. {
  129. CheckUdpBuildConfig();
  130. string api = "/v1/store/items/" + iapItem.id;
  131. return AsyncRequest(kHttpVerbPUT, BuildConfigInterface.GetUdpEndpoint(), api, accessToken, iapItem);
  132. }
  133. /// <summary>
  134. /// Call UDP store asynchronously to search for a store item.
  135. /// </summary>
  136. /// <param name="accessToken">The bearer token to UDP.</param>
  137. /// <param name="orgId">The organization identifier where to find the store item.</param>
  138. /// <param name="appItemSlug">The store item slug name.</param>
  139. /// <returns>The HTTP GET Request to update a store item.</returns>
  140. [Obsolete("Internal API, it will be removed soon.")]
  141. public static object SearchStoreItem(string accessToken, string orgId, string appItemSlug)
  142. {
  143. return CreateSearchStoreItemRequest(accessToken, orgId, appItemSlug);
  144. }
  145. /// <summary>
  146. /// Call UDP store asynchronously to search for a store item.
  147. /// </summary>
  148. /// <param name="accessToken">The bearer token to UDP.</param>
  149. /// <param name="orgId">The organization identifier where to find the store item.</param>
  150. /// <param name="appItemSlug">The store item slug name.</param>
  151. /// <returns>The HTTP GET Request to update a store item.</returns>
  152. internal static UnityWebRequest CreateSearchStoreItemRequest(string accessToken, string orgId, string appItemSlug)
  153. {
  154. CheckUdpBuildConfig();
  155. string api = "/v1/store/items/search?ownerId=" + orgId +
  156. "&ownerType=ORGANIZATION&start=0&count=20&type=IAP&masterItemSlug=" + appItemSlug;
  157. return AsyncRequest(kHttpVerbGET, BuildConfigInterface.GetUdpEndpoint(), api, accessToken, null);
  158. }
  159. // Return UnityWebRequest instance
  160. static UnityWebRequest AsyncRequest(string method, string url, string api, string token, object postObject)
  161. {
  162. UnityWebRequest request = new UnityWebRequest(url + api, method);
  163. if (postObject != null)
  164. {
  165. string postData = HandlePostData(JsonUtility.ToJson(postObject));
  166. byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
  167. request.uploadHandler = new UploadHandlerRaw(postDataBytes);
  168. }
  169. request.downloadHandler = new DownloadHandlerBuffer();
  170. request.SetRequestHeader(kContentType, kApplicationJson);
  171. if (token != null)
  172. {
  173. request.SetRequestHeader(kAuthHeader, "Bearer " + token);
  174. }
  175. request.SendWebRequest();
  176. return request;
  177. }
  178. internal static bool CheckUdpAvailability()
  179. {
  180. return true;
  181. }
  182. internal static bool CheckUdpCompatibility()
  183. {
  184. Type udpBuildConfig = BuildConfigInterface.GetClassType();
  185. if (udpBuildConfig == null)
  186. {
  187. Debug.LogError("Cannot Retrieve Build Config Endpoints for UDP. Please make sure the UDP package is installed");
  188. return false;
  189. }
  190. var udpVersion = BuildConfigInterface.GetVersion();
  191. int majorVersion = 0;
  192. int.TryParse(udpVersion.Split('.')[0], out majorVersion);
  193. return majorVersion >= 2;
  194. }
  195. // A very tricky way to deal with the json string, need to be improved
  196. // en-US and zh-CN will appear in the JSON and Unity JsonUtility cannot
  197. // recognize them to variables. So we change this to a string (remove "-").
  198. private static string HandlePostData(string oldData)
  199. {
  200. string newData = oldData.Replace("thisShouldBeENHyphenUS", "en-US");
  201. newData = newData.Replace("thisShouldBeZHHyphenCN", "zh-CN");
  202. Regex re = new Regex("\"\\w+?\":\"\",");
  203. newData = re.Replace(newData, "");
  204. re = new Regex(",\"\\w+?\":\"\"");
  205. newData = re.Replace(newData, "");
  206. re = new Regex("\"\\w+?\":\"\"");
  207. newData = re.Replace(newData, "");
  208. return newData;
  209. }
  210. }
  211. #region model
  212. /// <summary>
  213. /// This class is used to authenticate the API call to UDP. In OAuth2.0 authentication format.
  214. /// </summary>
  215. [Serializable]
  216. public class TokenRequest
  217. {
  218. /// <summary>
  219. /// The access token. Acquired by UnityOAuth
  220. /// </summary>
  221. public string code;
  222. /// <summary>
  223. /// The client identifier
  224. /// </summary>
  225. public string client_id;
  226. /// <summary>
  227. /// The client secret key
  228. /// </summary>
  229. public string client_secret;
  230. /// <summary>
  231. /// The type of OAuth2.0 code granting.
  232. /// </summary>
  233. public string grant_type;
  234. /// <summary>
  235. /// Redirect use after a successful authorization.
  236. /// </summary>
  237. public string redirect_uri;
  238. /// <summary>
  239. /// When the access token is expire. This token is used to renew it.
  240. /// </summary>
  241. public string refresh_token;
  242. }
  243. /// <summary>
  244. /// PriceSets holds the PurchaseFee. Used for IapItem.
  245. /// </summary>
  246. [Serializable]
  247. public class PriceSets
  248. {
  249. /// <summary>
  250. /// Get the PurchaseFee
  251. /// </summary>
  252. public PurchaseFee PurchaseFee = new PurchaseFee();
  253. }
  254. /// <summary>
  255. /// A PurchaseFee contains the PriceMap which contains the prices and currencies.
  256. /// </summary>
  257. [Serializable]
  258. public class PurchaseFee
  259. {
  260. /// <summary>
  261. /// The PurchaseFee type
  262. /// </summary>
  263. public string priceType = "CUSTOM";
  264. /// <summary>
  265. /// Holds a list of prices with their currencies
  266. /// </summary>
  267. public PriceMap priceMap = new PriceMap();
  268. }
  269. /// <summary>
  270. /// PriceMap hold a list of PriceDetail.
  271. /// </summary>
  272. [Serializable]
  273. public class PriceMap
  274. {
  275. /// <summary>
  276. /// List of prices with their currencies.
  277. /// </summary>
  278. public List<PriceDetail> DEFAULT = new List<PriceDetail>();
  279. }
  280. /// <summary>
  281. /// Price and the currency of a IAPItem.
  282. /// </summary>
  283. [Serializable]
  284. public class PriceDetail
  285. {
  286. /// <summary>
  287. /// Price of a IAPItem.
  288. /// </summary>
  289. public string price;
  290. /// <summary>
  291. /// Currency of the price.
  292. /// </summary>
  293. public string currency = "USD";
  294. }
  295. /// <summary>
  296. /// The Response from and HTTP response converted into an object.
  297. /// </summary>
  298. [Serializable]
  299. public class GeneralResponse
  300. {
  301. /// <summary>
  302. /// The body from the HTTP response.
  303. /// </summary>
  304. public string message;
  305. }
  306. /// <summary>
  307. /// The properties of a IAPItem.
  308. /// </summary>
  309. [Serializable]
  310. public class Properties
  311. {
  312. /// <summary>
  313. /// The description of a IAPItem.
  314. /// </summary>
  315. public string description;
  316. }
  317. /// <summary>
  318. /// The response used when creating/updating IAP item succeeds
  319. /// </summary>
  320. [Serializable]
  321. public class IapItemResponse : GeneralResponse
  322. {
  323. /// <summary>
  324. /// The IapItem identifier.
  325. /// </summary>
  326. public string id;
  327. }
  328. /// <summary>
  329. /// IapItem is the representation of a purchasable product from the UDP store
  330. /// </summary>
  331. [Serializable]
  332. public class IapItem
  333. {
  334. /// <summary>
  335. /// A unique identifier to identify the product.
  336. /// </summary>
  337. public string id;
  338. /// <summary>
  339. /// The product url stripped of all unsafe characters.
  340. /// </summary>
  341. public string slug;
  342. /// <summary>
  343. /// The product name.
  344. /// </summary>
  345. public string name;
  346. /// <summary>
  347. /// The organization url stripped of all unsafe characters.
  348. /// </summary>
  349. public string masterItemSlug;
  350. /// <summary>
  351. /// Is product a consumable type. If set to false it is a subscriptions.
  352. /// Consumables may be purchased more than once.
  353. /// Subscriptions have a finite window of validity.
  354. /// </summary>
  355. public bool consumable = true;
  356. /// <summary>
  357. /// The product type.
  358. /// </summary>
  359. public string type = "IAP";
  360. /// <summary>
  361. /// The product status.
  362. /// </summary>
  363. public string status = "STAGE";
  364. /// <summary>
  365. /// The organization id.
  366. /// </summary>
  367. public string ownerId;
  368. /// <summary>
  369. /// The organization type.
  370. /// </summary>
  371. public string ownerType = "ORGANIZATION";
  372. /// <summary>
  373. /// The product's prices with currencies.
  374. /// </summary>
  375. public PriceSets priceSets = new PriceSets();
  376. /// <summary>
  377. /// The properties of the product.
  378. /// </summary>
  379. public Properties properties = new Properties();
  380. /// <summary>
  381. /// Validates that the IapItem has at least the minimum amount of information set.
  382. /// </summary>
  383. /// <returns>A string error of missing information to the IapItem.</returns>
  384. public string ValidationCheck()
  385. {
  386. if (string.IsNullOrEmpty(slug))
  387. {
  388. return "Please fill in the ID";
  389. }
  390. if (string.IsNullOrEmpty(name))
  391. {
  392. return "Please fill in the title";
  393. }
  394. if (properties == null || string.IsNullOrEmpty(properties.description))
  395. {
  396. return "Please fill in the description";
  397. }
  398. return "";
  399. }
  400. }
  401. /// <summary>
  402. /// TokenInfo holds all the authentication token required to authenticate the API call.
  403. /// </summary>
  404. [Serializable]
  405. public class TokenInfo : GeneralResponse
  406. {
  407. /// <summary>
  408. /// The OAuth2.0 access token.
  409. /// </summary>
  410. public string access_token;
  411. /// <summary>
  412. /// The OAuth2.0 refresh token.
  413. /// </summary>
  414. public string refresh_token;
  415. }
  416. /// <summary>
  417. /// The response used when searching for IAP item.
  418. /// </summary>
  419. [Serializable]
  420. public class IapItemSearchResponse : GeneralResponse
  421. {
  422. /// <summary>
  423. /// The total amount of IAP item found.
  424. /// </summary>
  425. public int total;
  426. /// <summary>
  427. /// The list of IAP item found.
  428. /// </summary>
  429. public List<IapItem> results;
  430. }
  431. struct ReqStruct
  432. {
  433. public UnityWebRequest request;
  434. public GeneralResponse resp;
  435. public ProductCatalogEditor.ProductCatalogItemEditor itemEditor;
  436. public IapItem iapItem;
  437. }
  438. /// <summary>
  439. /// The response used when searching for Organization identifier.
  440. /// </summary>
  441. [Serializable]
  442. public class OrgIdResponse : GeneralResponse
  443. {
  444. /// <summary>
  445. /// The organization identifier.
  446. /// </summary>
  447. public string org_foreign_key;
  448. }
  449. /// <summary>
  450. /// The response used when searching for Organization roles.
  451. /// </summary>
  452. [Serializable]
  453. public class OrgRoleResponse : GeneralResponse
  454. {
  455. /// <summary>
  456. /// The organization roles.
  457. /// </summary>
  458. public List<string> roles;
  459. }
  460. /// <summary>
  461. /// The response used when getting an error.
  462. /// </summary>
  463. [Serializable]
  464. public class ErrorResponse : GeneralResponse
  465. {
  466. /// <summary>
  467. /// The http error code.
  468. /// </summary>
  469. public string code;
  470. /// <summary>
  471. /// The details of an error.
  472. /// </summary>
  473. public ErrorDetail[] details;
  474. }
  475. /// <summary>
  476. /// The details of an error return from the api.
  477. /// </summary>
  478. [Serializable]
  479. public class ErrorDetail
  480. {
  481. /// <summary>
  482. /// The error context where it occured.
  483. /// </summary>
  484. public string field;
  485. /// <summary>
  486. /// The error message reason.
  487. /// </summary>
  488. public string reason;
  489. }
  490. #endregion
  491. }