MainMenu.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. using System;
  2. using System.Collections;
  3. using System.Text;
  4. using AppleAuth;
  5. using AppleAuth.Enums;
  6. using AppleAuth.Extensions;
  7. using AppleAuth.Interfaces;
  8. using AppleAuth.Native;
  9. using Newtonsoft.Json;
  10. using UnityEngine;
  11. using UnityEngine.Networking;
  12. public class MainMenu : MonoBehaviour
  13. {
  14. private const string AppleUserIdKey = "AppleUserId";
  15. private IAppleAuthManager _appleAuthManager;
  16. public LoginMenuHandler LoginMenu;
  17. public GameMenuHandler GameMenu;
  18. private void Start()
  19. {
  20. // If the current platform is supported
  21. if (AppleAuthManager.IsCurrentPlatformSupported)
  22. {
  23. // Creates a default JSON deserializer, to transform JSON Native responses to C# instances
  24. var deserializer = new PayloadDeserializer();
  25. // Creates an Apple Authentication manager with the deserializer
  26. this._appleAuthManager = new AppleAuthManager(deserializer);
  27. }
  28. this.InitializeLoginMenu();
  29. }
  30. private void Update()
  31. {
  32. // Updates the AppleAuthManager instance to execute
  33. // pending callbacks inside Unity's execution loop
  34. if (this._appleAuthManager != null)
  35. {
  36. this._appleAuthManager.Update();
  37. }
  38. this.LoginMenu.UpdateLoadingMessage(Time.deltaTime);
  39. }
  40. public void SignInWithAppleButtonPressed()
  41. {
  42. this.SetupLoginMenuForAppleSignIn();
  43. this.SignInWithApple();
  44. }
  45. public void SignInWithAppleButtonPressed2()
  46. {
  47. this.SignInWithApple();
  48. }
  49. public void SignInWithAppleButtonPressedDelete()
  50. {
  51. this.DeleteSignInWithApple();
  52. }
  53. private void InitializeLoginMenu()
  54. {
  55. this.LoginMenu.SetVisible(visible: true);
  56. this.GameMenu.SetVisible(visible: false);
  57. // Check if the current platform supports Sign In With Apple
  58. if (this._appleAuthManager == null)
  59. {
  60. this.SetupLoginMenuForUnsupportedPlatform();
  61. return;
  62. }
  63. // If at any point we receive a credentials revoked notification, we delete the stored User ID, and go back to login
  64. this._appleAuthManager.SetCredentialsRevokedCallback(result =>
  65. {
  66. Debug.Log("Received revoked callback " + result);
  67. this.SetupLoginMenuForSignInWithApple();
  68. PlayerPrefs.DeleteKey(AppleUserIdKey);
  69. });
  70. // If we have an Apple User Id available, get the credential status for it
  71. if (PlayerPrefs.HasKey(AppleUserIdKey))
  72. {
  73. var storedAppleUserId = PlayerPrefs.GetString(AppleUserIdKey);
  74. this.SetupLoginMenuForCheckingCredentials();
  75. this.CheckCredentialStatusForUserId(storedAppleUserId);
  76. }
  77. // If we do not have an stored Apple User Id, attempt a quick login
  78. else
  79. {
  80. this.SetupLoginMenuForQuickLoginAttempt();
  81. this.AttemptQuickLogin();
  82. }
  83. }
  84. private void SetupLoginMenuForUnsupportedPlatform()
  85. {
  86. this.LoginMenu.SetVisible(visible: true);
  87. this.GameMenu.SetVisible(visible: false);
  88. this.LoginMenu.SetSignInWithAppleButton(visible: false, enabled: false);
  89. this.LoginMenu.SetLoadingMessage(visible: true, message: "Unsupported platform");
  90. }
  91. private void SetupLoginMenuForSignInWithApple()
  92. {
  93. this.LoginMenu.SetVisible(visible: true);
  94. this.GameMenu.SetVisible(visible: false);
  95. this.LoginMenu.SetSignInWithAppleButton(visible: true, enabled: true);
  96. this.LoginMenu.SetLoadingMessage(visible: false, message: string.Empty);
  97. }
  98. private void SetupLoginMenuForCheckingCredentials()
  99. {
  100. this.LoginMenu.SetVisible(visible: true);
  101. this.GameMenu.SetVisible(visible: false);
  102. this.LoginMenu.SetSignInWithAppleButton(visible: true, enabled: false);
  103. this.LoginMenu.SetLoadingMessage(visible: true, message: "Checking Apple Credentials");
  104. }
  105. private void SetupLoginMenuForQuickLoginAttempt()
  106. {
  107. this.LoginMenu.SetVisible(visible: true);
  108. this.GameMenu.SetVisible(visible: false);
  109. this.LoginMenu.SetSignInWithAppleButton(visible: true, enabled: false);
  110. this.LoginMenu.SetLoadingMessage(visible: true, message: "Attempting Quick Login");
  111. }
  112. private void SetupLoginMenuForAppleSignIn()
  113. {
  114. this.LoginMenu.SetVisible(visible: true);
  115. this.GameMenu.SetVisible(visible: false);
  116. this.LoginMenu.SetSignInWithAppleButton(visible: true, enabled: false);
  117. this.LoginMenu.SetLoadingMessage(visible: true, message: "Signing In with Apple");
  118. }
  119. private void SetupGameMenu(string appleUserId, ICredential credential)
  120. {
  121. this.LoginMenu.SetVisible(visible: false);
  122. this.GameMenu.SetVisible(visible: true);
  123. this.GameMenu.SetupAppleData(appleUserId, credential);
  124. }
  125. private void CheckCredentialStatusForUserId(string appleUserId)
  126. {
  127. // If there is an apple ID available, we should check the credential state
  128. this._appleAuthManager.GetCredentialState(
  129. appleUserId,
  130. state =>
  131. {
  132. switch (state)
  133. {
  134. // If it's authorized, login with that user id
  135. case CredentialState.Authorized:
  136. this.SetupGameMenu(appleUserId, null);
  137. return;
  138. // If it was revoked, or not found, we need a new sign in with apple attempt
  139. // Discard previous apple user id
  140. case CredentialState.Revoked:
  141. case CredentialState.NotFound:
  142. this.SetupLoginMenuForSignInWithApple();
  143. PlayerPrefs.DeleteKey(AppleUserIdKey);
  144. return;
  145. }
  146. },
  147. error =>
  148. {
  149. var authorizationErrorCode = error.GetAuthorizationErrorCode();
  150. Debug.LogWarning("Error while trying to get credential state " + authorizationErrorCode.ToString() + " " + error.ToString());
  151. this.SetupLoginMenuForSignInWithApple();
  152. });
  153. }
  154. private void AttemptQuickLogin()
  155. {
  156. var quickLoginArgs = new AppleAuthQuickLoginArgs();
  157. // Quick login should succeed if the credential was authorized before and not revoked
  158. this._appleAuthManager.QuickLogin(
  159. quickLoginArgs,
  160. credential =>
  161. {
  162. // If it's an Apple credential, save the user ID, for later logins
  163. var appleIdCredential = credential as IAppleIDCredential;
  164. if (appleIdCredential != null)
  165. {
  166. PlayerPrefs.SetString(AppleUserIdKey, credential.User);
  167. }
  168. this.SetupGameMenu(credential.User, credential);
  169. this.onAppleData(credential.User, credential);
  170. },
  171. error =>
  172. {
  173. // If Quick Login fails, we should show the normal sign in with apple menu, to allow for a normal Sign In with apple
  174. var authorizationErrorCode = error.GetAuthorizationErrorCode();
  175. Debug.LogWarning("Quick Login Failed " + authorizationErrorCode.ToString() + " " + error.ToString());
  176. this.SetupLoginMenuForSignInWithApple();
  177. });
  178. }
  179. private void SignInWithApple()
  180. {
  181. var loginArgs = new AppleAuthLoginArgs(LoginOptions.IncludeEmail | LoginOptions.IncludeFullName);
  182. this._appleAuthManager.LoginWithAppleId(
  183. loginArgs,
  184. credential =>
  185. {
  186. // If a sign in with apple succeeds, we should have obtained the credential with the user id, name, and email, save it
  187. PlayerPrefs.SetString(AppleUserIdKey, credential.User);
  188. this.SetupGameMenu(credential.User, credential);
  189. this.onAppleData(credential.User, credential);
  190. },
  191. error =>
  192. {
  193. var authorizationErrorCode = error.GetAuthorizationErrorCode();
  194. Debug.LogWarning("Sign in with Apple failed " + authorizationErrorCode.ToString() + " " + error.ToString());
  195. this.SetupLoginMenuForSignInWithApple();
  196. });
  197. }
  198. private void DeleteSignInWithApple() {
  199. var loginArgs = new AppleAuthLoginArgs(LoginOptions.IncludeEmail | LoginOptions.IncludeFullName);
  200. this._appleAuthManager.LoginWithAppleId(
  201. loginArgs,
  202. credential =>
  203. {
  204. var appleIdCredential = credential as IAppleIDCredential;
  205. if (appleIdCredential.AuthorizationCode != null)
  206. {
  207. var authorizationCode = Encoding.UTF8.GetString(appleIdCredential.AuthorizationCode, 0, appleIdCredential.AuthorizationCode.Length);
  208. Debug.Log("delete===authorizationCode======= " + authorizationCode.Substring(0, 45));
  209. StartCoroutine(DdeleteUserByApple(authorizationCode, (res) =>
  210. {
  211. Debug.Log($"DdeleteUserByApple service rescode {res.code}, msg {res.msg}");
  212. if (res.code == 0)
  213. {
  214. Debug.Log("删除成功");
  215. this.SetupLoginMenuForSignInWithApple();
  216. PlayerPrefs.DeleteKey(AppleUserIdKey);
  217. }
  218. }));
  219. }
  220. },
  221. error =>
  222. {
  223. var authorizationErrorCode = error.GetAuthorizationErrorCode();
  224. Debug.LogWarning("Sign in with Apple failed " + authorizationErrorCode.ToString() + " " + error.ToString());
  225. this.SetupLoginMenuForSignInWithApple();
  226. });
  227. }
  228. public void onAppleData(string appleUserId, ICredential receivedCredential)
  229. {
  230. var appleIdCredential = receivedCredential as IAppleIDCredential;
  231. if (appleIdCredential != null)
  232. {
  233. if (appleIdCredential.IdentityToken != null)
  234. {
  235. var identityToken = Encoding.UTF8.GetString(appleIdCredential.IdentityToken, 0, appleIdCredential.IdentityToken.Length);
  236. Debug.Log("11===identityToken======= " + identityToken);
  237. }
  238. if (appleIdCredential.AuthorizationCode != null)
  239. {
  240. var authorizationCode = Encoding.UTF8.GetString(appleIdCredential.AuthorizationCode, 0, appleIdCredential.AuthorizationCode.Length);
  241. Debug.Log("22===authorizationCode======= " + authorizationCode.Substring(0, 45));
  242. }
  243. string _email = "";
  244. if (appleIdCredential.Email != null)
  245. {
  246. _email = appleIdCredential.Email;
  247. }
  248. Debug.Log("33===Email======= " + _email);
  249. string _fullName = "";
  250. if (appleIdCredential.FullName != null)
  251. {
  252. var fullName = appleIdCredential.FullName;
  253. if (appleIdCredential.FullName.PhoneticRepresentation != null)
  254. {
  255. var phoneticName = appleIdCredential.FullName.PhoneticRepresentation;
  256. //phoneticName.ToLocalizedString()
  257. }
  258. _fullName = fullName.ToLocalizedString();
  259. }
  260. Debug.Log("44===FullName======= " + appleIdCredential.FullName);
  261. var _identityToken = Encoding.UTF8.GetString(appleIdCredential.IdentityToken, 0, appleIdCredential.IdentityToken.Length);
  262. StartCoroutine(LoginByApple(_identityToken, _email, _fullName, (res) =>
  263. {
  264. Debug.Log($"LoginByApple service rescode {res.code}, msg {res.msg}");
  265. if (res.code == 0)
  266. {
  267. Debug.Log("LoginByApple 登录");
  268. }
  269. else
  270. {
  271. this.SetupLoginMenuForSignInWithApple();
  272. PlayerPrefs.DeleteKey(AppleUserIdKey);
  273. }
  274. }));
  275. }
  276. else
  277. {
  278. this.SetupLoginMenuForSignInWithApple();
  279. PlayerPrefs.DeleteKey(AppleUserIdKey);
  280. }
  281. }
  282. public IEnumerator LoginByApple(string identityToken, string email, string fullName, Action<RequestResult> callback)
  283. {
  284. string url = "http://192.168.0.112:11432/SmartBowBusinessServer/gameLogin/loginByApple";
  285. WWWForm form = new WWWForm();
  286. form.AddField("identityToken", identityToken);
  287. form.AddField("email", email);
  288. form.AddField("fullName", fullName);
  289. form.AddField("serverIndex", 0);
  290. using (UnityWebRequest request = UnityWebRequest.Post(url, form))
  291. {
  292. request.timeout = 10;
  293. yield return request.SendWebRequest();
  294. RequestResult requestResult = new RequestResult();
  295. if (request.result == UnityWebRequest.Result.Success)
  296. {
  297. requestResult = JsonConvert.DeserializeObject<RequestResult>(request.downloadHandler.text);
  298. }
  299. if (callback != null) callback(requestResult);
  300. }
  301. }
  302. public IEnumerator DdeleteUserByApple(string identityToken, Action<RequestResult> callback)
  303. {
  304. string url = "http://192.168.0.112:11432/SmartBowBusinessServer/gameLogin/deleteUserByApple";
  305. WWWForm form = new WWWForm();
  306. form.AddField("identityToken", identityToken);
  307. using (UnityWebRequest request = UnityWebRequest.Post(url, form))
  308. {
  309. request.timeout = 10;
  310. yield return request.SendWebRequest();
  311. RequestResult requestResult = new RequestResult();
  312. if (request.result == UnityWebRequest.Result.Success)
  313. {
  314. requestResult = JsonConvert.DeserializeObject<RequestResult>(request.downloadHandler.text);
  315. }
  316. if (callback != null) callback(requestResult);
  317. }
  318. }
  319. public class RequestResult
  320. {
  321. public int code = -9999;
  322. public object data;
  323. public string msg;
  324. }
  325. }