com.xd.sdk.account 7.9.2 → 7.10.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/Plugins/iOS/XDAccountSDK.framework/Headers/XDGAccount.h +6 -1
  2. package/Plugins/iOS/XDAccountSDK.framework/Headers/XDGAccountVersion.h +3 -3
  3. package/Plugins/iOS/XDAccountSDK.framework/Info.plist +0 -0
  4. package/Plugins/iOS/XDAccountSDK.framework/XDAccountSDK +0 -0
  5. package/Runtime/Internal/IXDGAccount.Extended.cs +4 -0
  6. package/Runtime/Internal/Mobile/AccountFeaturesImpl.cs +30 -0
  7. package/Runtime/Internal/Standalone/AccessToken/AccessTokenModule.cs +14 -4
  8. package/Runtime/Internal/Standalone/AccountFeaturesImpl.cs +100 -38
  9. package/Runtime/Internal/Standalone/Auth/AppleAuth.cs +1 -2
  10. package/Runtime/Internal/Standalone/Auth/FacebookAuth.cs +2 -3
  11. package/Runtime/Internal/Standalone/Auth/GoogleAuth.cs +1 -2
  12. package/Runtime/Internal/Standalone/Auth/SteamAuth.cs +1 -2
  13. package/Runtime/Internal/Standalone/Auth/TapAuth.cs +12 -9
  14. package/Runtime/Internal/Standalone/Auth/UrlSchemeAuth.cs +4 -1
  15. package/Runtime/Internal/Standalone/Auth/WebAuth.cs +25 -27
  16. package/Runtime/Internal/Standalone/Compliance/XDCompliance.cs +27 -6
  17. package/Runtime/Internal/Standalone/Compliance/XDComplianceException.cs +1 -0
  18. package/Runtime/Internal/Standalone/Compliance/XDComplianceWebOpener.cs +8 -4
  19. package/Runtime/Internal/Standalone/UserModule.cs +73 -37
  20. package/Runtime/Internal/Standalone/WebFunction/LoginBridgeProtocol.cs +37 -0
  21. package/Runtime/Internal/Standalone/WebFunction/LoginBridgeProtocol.cs.meta +2 -0
  22. package/Runtime/Internal/Standalone/WebFunction/LoginByTypeWebFunction.cs +36 -0
  23. package/Runtime/Internal/Standalone/WebFunction/LoginByTypeWebFunction.cs.meta +2 -0
  24. package/Runtime/Internal/Standalone/WebFunction/LoginPanelController.cs +92 -0
  25. package/Runtime/Internal/Standalone/WebFunction/LoginPanelController.cs.meta +2 -0
  26. package/Runtime/Internal/Standalone/WebFunction/LoginWithAuthWebFunction.cs +61 -0
  27. package/Runtime/Internal/Standalone/WebFunction/LoginWithAuthWebFunction.cs.meta +2 -0
  28. package/Runtime/Internal/XDGAccountInternal.cs +12 -1
  29. package/Runtime/Public/XDGAccount.cs +11 -1
  30. package/package.json +2 -2
@@ -13,6 +13,11 @@ NS_ASSUME_NONNULL_BEGIN
13
13
  /// @param handler 回调处理器
14
14
  + (void)addUserStatusChangeCallback:(XDGUserStatusChangeCallback)handler;
15
15
 
16
+ /// 打开 SDK 登录面板,由面板展示登录渠道并完成登录
17
+ /// @param handler 只回调一次:登录成功返回用户;用户关闭面板返回 XDGErrorCodeCancelled;
18
+ /// 未初始化、面板已打开、未配置面板地址或无可用渠道时立即返回失败
19
+ + (void)login:(XDGLoginManagerRequestCallback)handler;
20
+
16
21
  /**
17
22
  你可以自定义登录按钮的展示方式,并调用此方法来登录用户。
18
23
  步骤:
@@ -20,7 +25,7 @@ NS_ASSUME_NONNULL_BEGIN
20
25
  2. 如果步骤1失败,显示登录按钮,当用户点击时调用对应类型的登录
21
26
  */
22
27
  /// 开始登录
23
- /// @param loginType 登录类型
28
+ /// @param loginType 登录类型;不支持 LoginEntryTypeXD(心动账号只能通过 login: 登录面板登录),传入时返回 XDGErrorCodeAuthTypeNotAvailable
24
29
  /// @param handler 回调处理器
25
30
  + (void)loginByType:(LoginEntryType)loginType loginHandler:(XDGLoginManagerRequestCallback)handler;
26
31
 
@@ -4,6 +4,6 @@
4
4
  //
5
5
  // Created by Fattycat on 2023/4/14.
6
6
  //
7
- #define XDGAccount_VERSION @"7.9.0"
8
- #define XDSAccount_VERSION_CODE @"7090000"
9
- // HASH 1e690d3c
7
+ #define XDGAccount_VERSION @"7.10.0"
8
+ #define XDSAccount_VERSION_CODE @"7100000"
9
+ // HASH 1fb1f617
@@ -1,11 +1,15 @@
1
+ using System;
1
2
  using System.Collections.Generic;
2
3
  using System.Net.Http;
3
4
  using System.Threading.Tasks;
5
+ using XD.SDK.Common;
4
6
 
5
7
  namespace XD.SDK.Account
6
8
  {
7
9
  interface IXDGAccountExtended : IXDGAccount
8
10
  {
11
+ void Login(Action<XDGUser> successCallback, Action<XDGError> errorCallback);
12
+
9
13
  Task<Dictionary<string, string>> GetRequestAuthorizationHeader(HttpRequestMessage request, long timestamp);
10
14
  }
11
15
  }
@@ -67,6 +67,36 @@ namespace XD.SDK.Account.Internal.Mobile
67
67
  });
68
68
  }
69
69
 
70
+ public void Login(Action<XDGUser> successCallback, Action<XDGError> errorCallback)
71
+ {
72
+ var command = new Command.Builder()
73
+ .Service(BridgeConstants.Account.BridgeName)
74
+ .Method("login")
75
+ .Callback(true)
76
+ .OnceTime(true)
77
+ .CommandBuilder();
78
+
79
+ EngineBridge.GetInstance().CallHandler(command, result =>
80
+ {
81
+ var error = result.Parse2XDGError();
82
+ if (error != null)
83
+ {
84
+ errorCallback?.Invoke(error);
85
+ return;
86
+ }
87
+
88
+ var content = XDGJson.Deserialize(result.content) as Dictionary<string, object>;
89
+ var user = XDDictionary.GetValue<Dictionary<string, object>>(content, "user");
90
+ if (user == null)
91
+ {
92
+ errorCallback?.Invoke(new XDGError(ResponseCode.Common.Failed, "user is null"));
93
+ return;
94
+ }
95
+
96
+ successCallback?.Invoke(new XDGUser(user));
97
+ });
98
+ }
99
+
70
100
  public void LoginByType(LoginType loginType, Action<XDGUser> callback, Action<XDGError> errorCallback)
71
101
  {
72
102
  var command = new Command.Builder()
@@ -79,9 +79,17 @@ namespace XD.SDK.Account.Internal.Standalone
79
79
  /// </summary>
80
80
  /// <param name="param"></param>
81
81
  /// <returns></returns>
82
- public static Task<XDGAccessToken> Login(Dictionary<string, object> param, Dictionary<string, object> cacheData)
82
+ public static Task<XDGAccessToken> Login(Dictionary<string, object> param, Dictionary<string, object> cacheData,
83
+ Action onAuthenticated = null)
83
84
  {
84
- return LoginInternal(XDG_COMMON_LOGIN, param, cacheData);
85
+ return LoginInternal(XDG_COMMON_LOGIN, param, cacheData, onAuthenticated);
86
+ }
87
+
88
+ internal static Task<XDGAccessToken> ImportAuthenticatedToken(XDGAccessToken token)
89
+ {
90
+ // Web union 已完成认证,替换本次上下文,不继承旧账号的 Steam 等缓存。
91
+ local = new XDGAccessToken { MacAlgorithm = token.MacAlgorithm };
92
+ return UpdateLocalToken(token);
85
93
  }
86
94
 
87
95
  /// <summary>
@@ -95,11 +103,13 @@ namespace XD.SDK.Account.Internal.Standalone
95
103
  }
96
104
 
97
105
  static async Task<XDGAccessToken> LoginInternal(string path,
98
- Dictionary<string, object> param, Dictionary<string, object> cacheData)
106
+ Dictionary<string, object> param, Dictionary<string, object> cacheData, Action onAuthenticated = null)
99
107
  {
100
108
  try
101
109
  {
102
110
  AccessTokenResponse response = await XDHttpClient.Client.PostAsync<AccessTokenResponse>(path, data: param);
111
+ onAuthenticated?.Invoke();
112
+ if (XDCompliance.UsesXdProvider) XDCompliance.Stop();
103
113
 
104
114
  if (cacheData == null)
105
115
  {
@@ -173,4 +183,4 @@ namespace XD.SDK.Account.Internal.Standalone
173
183
  }
174
184
  }
175
185
  }
176
- #endif
186
+ #endif
@@ -61,22 +61,84 @@ namespace XD.SDK.Account.Internal.Standalone
61
61
  return UserStatusChangeCallback;
62
62
  }
63
63
 
64
+ public void Login(Action<XDGUser> successCallback, Action<XDGError> errorCallback)
65
+ {
66
+ #if ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) || ((UNITY_EDITOR_WIN || UNITY_EDITOR_OSX) && !UNITY_ANDROID && !UNITY_IOS))
67
+ LoginPanelController.Open(successCallback, errorCallback);
68
+ #else
69
+ errorCallback?.Invoke(new XDGError(ResponseCode.Common.UnavailableService,
70
+ "Web login panel is not supported on this platform."));
71
+ #endif
72
+ }
73
+
64
74
  public async void LoginByType(LoginType loginType, Action<XDGUser> callback, Action<XDGError> errorCallback)
65
75
  {
66
76
  try
67
77
  {
68
78
  var user = await LoginByTypeInternal(loginType);
69
- XDGCommonInternal.TrackUser(user.UserId);
70
- callback.Invoke(await InvokeXdgPaymentCheckRefundStatusWithUI(user));
79
+ var result = await FinishLogin(user);
80
+ callback?.Invoke(result);
71
81
  }
72
- catch (XDGError xe)
82
+ catch (Exception e) { errorCallback?.Invoke(e.ParseToError()); }
83
+ }
84
+
85
+ internal async Task<XDGUser> LoginWithAuth(LoginType type, XDGAccessToken credential)
86
+ {
87
+ PrepareLogin(type);
88
+ // 开始导入凭据后,失败才清理本次账号。
89
+ var authenticated = false;
90
+ try
73
91
  {
74
- errorCallback?.Invoke(xe.ParseToError());
92
+ var user = await UserModule.Login(type, credential, () =>
93
+ {
94
+ authenticated = true;
95
+ XDCompliance.Stop();
96
+ }, showAuthorizationLoading: false);
97
+ if (!await CheckLoginAdmission(user)) throw new XDGError("防沉迷校验失败");
98
+ return await FinishLogin(user);
99
+ }
100
+ catch (Exception failure)
101
+ {
102
+ Exception error = failure;
103
+ var complianceError = failure as XDComplianceException;
104
+ if (complianceError != null && complianceError.OriginalException != null)
105
+ error = complianceError.OriginalException;
106
+ var message = (error as XDGError)?.ErrorMsg ?? error.Message;
107
+ if ((failure as XDHttpException)?.Code == ResponseCode.Account.TokenExpired) message = "XD_TOKEN_EXPIRED";
108
+ AliyunTrack.LoginFail(message);
109
+ if (authenticated) CleanupLogin(type, failure);
110
+ throw error;
75
111
  }
76
- catch (Exception e)
112
+ }
113
+
114
+ private void PrepareLogin(LoginType type)
115
+ {
116
+ if (!XDGCommonInternal.IsInitialized()) throw XDGErrorExtensions.NotInitError();
117
+ AliyunTrack.LoginStart(type.ToString());
118
+ XDCompliance.LogoutHandler = needNotify =>
119
+ {
120
+ InternalLogout(GlobalComplianceExit, needNotify);
121
+ };
122
+ }
123
+
124
+ private static async Task<bool> CheckLoginAdmission(XDGUser user)
125
+ {
126
+ AliyunTrack.LoginAntiAddictionStartup();
127
+ if (!XDCompliance.UsesXdProvider)
77
128
  {
78
- errorCallback?.Invoke(e.ParseToError());
129
+ var result = await XDGEventBus.PublishAsync<Dictionary<string, object>>(XDGEvents.TapSDKComplianceStartup, ConfigModule.IsGlobal, user.UserId);
130
+ if (!XDDictionary.GetValue<bool>(result.GetValueOrDefault(), "success")) return false;
79
131
  }
132
+ await AgreementModule.SignAgreement(user.UserId);
133
+ AliyunTrack.LoginSuccess();
134
+ return true;
135
+ }
136
+
137
+ private static async Task<XDGUser> FinishLogin(XDGUser user)
138
+ {
139
+ XDGCommonInternal.TrackUser(user.UserId);
140
+ var result = await InvokeXdgPaymentCheckRefundStatusWithUI(user);
141
+ return result;
80
142
  }
81
143
 
82
144
  // 向后兼容的便捷方法
@@ -243,41 +305,19 @@ namespace XD.SDK.Account.Internal.Standalone
243
305
 
244
306
  private async Task<XDGUser> LoginByTypeInternal(LoginType loginType)
245
307
  {
246
- if (!XDGCommonInternal.IsInitialized())
247
- {
248
- throw XDGErrorExtensions.NotInitError();
249
- }
250
-
251
- // 登录埋点
252
- AliyunTrack.LoginStart(loginType.ToString());
253
- XDCompliance.LogoutHandler = needNotify => InternalLogout(GlobalComplianceExit, needNotify);
308
+ PrepareLogin(loginType);
254
309
  try
255
310
  {
256
311
  var user = await UserModule.Login(loginType);
257
- AliyunTrack.LoginAntiAddictionStartup();
258
- var complianceResult = await XDGEventBus.PublishAsync<Dictionary<string, object>>(XDGEvents.TapSDKComplianceStartup, ConfigModule.IsGlobal, user.UserId);
259
- var compliance = complianceResult.GetValueOrDefault();
260
- if (XDDictionary.GetValue<bool>(compliance, "success"))
261
- {
262
- await AgreementModule.SignAgreement(user.UserId);
263
- AliyunTrack.LoginSuccess();
264
- return user;
265
- }
266
-
312
+ if (await CheckLoginAdmission(user)) return user;
267
313
  ClearUserCache();
268
314
  throw new XDGError("防沉迷校验失败");
269
315
  }
270
316
  catch (XDHttpException e)
271
317
  {
272
- if (XDCompliance.IsRequired(e))
273
- {
274
- InternalLogout(GlobalComplianceLogout, false);
275
- }
318
+ if (XDCompliance.IsRequired(e)) InternalLogout(GlobalComplianceLogout, false);
276
319
  else if ((e.HttpStatusCode == 401 && loginType == LoginType.Default) || e.Code == 40311 || e.Code == 40312)
277
- {
278
320
  InternalLogout("LOGOUT_API", false);
279
- }
280
-
281
321
  var errorMsg = e.Message;
282
322
  if (e.Code == ResponseCode.Account.TokenExpired)
283
323
  errorMsg = "XD_TOKEN_EXPIRED";
@@ -288,12 +328,8 @@ namespace XD.SDK.Account.Internal.Standalone
288
328
  {
289
329
  var originalException = e.OriginalException;
290
330
  AliyunTrack.LoginFail(originalException?.Message ?? e.ErrorMsg);
291
- InternalLogout(GlobalComplianceLogout, false);
292
- if (originalException != null)
293
- {
294
- throw originalException;
295
- }
296
-
331
+ CleanupComplianceLogin(e);
332
+ if (originalException != null) throw originalException;
297
333
  throw;
298
334
  }
299
335
  catch (Exception e)
@@ -306,12 +342,38 @@ namespace XD.SDK.Account.Internal.Standalone
306
342
  {
307
343
  AliyunTrack.LoginFail(e.Message);
308
344
  }
309
-
310
345
  AgreementModule.ClearLocalSignedAgreements();
311
346
  throw;
312
347
  }
313
348
  }
314
349
 
350
+ private void CleanupComplianceLogin(XDComplianceException error)
351
+ {
352
+ InternalLogout(GlobalComplianceLogout, false);
353
+ if (error.ExitGameRequested)
354
+ {
355
+ #if UNITY_EDITOR
356
+ UnityEditor.EditorApplication.isPlaying = false;
357
+ #else
358
+ UnityEngine.Application.Quit();
359
+ #endif
360
+ }
361
+ }
362
+
363
+ private void CleanupLogin(LoginType type, Exception failure)
364
+ {
365
+ var httpError = failure as XDHttpException;
366
+ if (failure is XDComplianceException complianceError)
367
+ CleanupComplianceLogin(complianceError);
368
+ else if (XDCompliance.IsRequired(httpError))
369
+ InternalLogout(GlobalComplianceLogout, false);
370
+ else if (httpError != null && ((httpError.HttpStatusCode == 401 && type == LoginType.Default)
371
+ || httpError.Code == 40311 || httpError.Code == 40312))
372
+ InternalLogout("LOGOUT_API", false);
373
+ else
374
+ InternalLogout("SWITCH_ACCOUNT", false, false);
375
+ }
376
+
315
377
  public void InternalLogout(string logoutType = "LOGOUT_API", bool needNotify = true, bool bShowAgreement = true)
316
378
  {
317
379
  // SDK 登陆成功
@@ -9,7 +9,6 @@ namespace XD.SDK.Account.Internal.Standalone
9
9
  {
10
10
  internal class AppleAuth : WebAuth
11
11
  {
12
- static List<HttpListener> servers = new List<HttpListener>();
13
12
 
14
13
  internal static Task<Dictionary<string, object>> GetAuthData()
15
14
  {
@@ -20,7 +19,7 @@ namespace XD.SDK.Account.Internal.Standalone
20
19
  { "state", LocalServerUtils.GenerateRandomDataBase64url(32) }
21
20
  };
22
21
 
23
- return StartListener(servers, LoginType.Apple, queryParams);
22
+ return StartListener(new List<HttpListener>(), LoginType.Apple, queryParams);
24
23
  }
25
24
  }
26
25
  }
@@ -1,4 +1,4 @@
1
- #if UNITY_EDITOR || UNITY_STANDALONE
1
+ #if UNITY_EDITOR || UNITY_STANDALONE
2
2
  using System.Collections.Generic;
3
3
  using System.Net;
4
4
  using System.Threading.Tasks;
@@ -8,7 +8,6 @@ namespace XD.SDK.Account.Internal.Standalone
8
8
  {
9
9
  public class FacebookAuth : WebAuth
10
10
  {
11
- static List<HttpListener> servers = new List<HttpListener>();
12
11
 
13
12
  internal static Task<Dictionary<string, object>> GetAuthData()
14
13
  {
@@ -19,7 +18,7 @@ namespace XD.SDK.Account.Internal.Standalone
19
18
  { "state", LocalServerUtils.GenerateRandomDataBase64url(32) }
20
19
  };
21
20
 
22
- return StartListener(servers, LoginType.Facebook, queryParams);
21
+ return StartListener(new List<HttpListener>(), LoginType.Facebook, queryParams);
23
22
  }
24
23
  }
25
24
  }
@@ -9,7 +9,6 @@ namespace XD.SDK.Account.Internal.Standalone
9
9
  {
10
10
  internal class GoogleAuth : WebAuth
11
11
  {
12
- static List<HttpListener> servers = new List<HttpListener>();
13
12
 
14
13
  internal static Task<Dictionary<string, object>> GetAuthData()
15
14
  {
@@ -20,7 +19,7 @@ namespace XD.SDK.Account.Internal.Standalone
20
19
  { "state", LocalServerUtils.GenerateRandomDataBase64url(32) }
21
20
  };
22
21
 
23
- return StartListener(servers, LoginType.Google, queryParams);
22
+ return StartListener(new List<HttpListener>(), LoginType.Google, queryParams);
24
23
  }
25
24
  }
26
25
  }
@@ -10,7 +10,6 @@ namespace XD.SDK.Account.Internal.Standalone
10
10
  {
11
11
  public class SteamAuth : WebAuth
12
12
  {
13
- static readonly List<HttpListener> servers = new List<HttpListener>();
14
13
 
15
14
  internal static async Task<Dictionary<string, object>> GetAuthData()
16
15
  {
@@ -28,7 +27,7 @@ namespace XD.SDK.Account.Internal.Standalone
28
27
  { "state", LocalServerUtils.GenerateRandomDataBase64url(32) },
29
28
  { "console_type", "steam" },
30
29
  };
31
- return await StartListener(servers, LoginType.Steam, queryParams);
30
+ return await StartListener(new List<HttpListener>(), LoginType.Steam, queryParams);
32
31
  }
33
32
 
34
33
  public static async Task<Dictionary<string, object>> GetAuthDataFromSDK()
@@ -11,18 +11,20 @@ namespace XD.SDK.Account.Internal.Standalone
11
11
  {
12
12
  internal class TapAuth
13
13
  {
14
- internal static async Task<Dictionary<string, object>> GetAuthData()
14
+ internal static async Task<Dictionary<string, object>> GetAuthData(
15
+ bool showAuthorizationLoading = true)
15
16
  {
16
- return await RequestTapToken();
17
+ return await RequestTapToken(showAuthorizationLoading);
17
18
  }
18
19
 
19
- private static async Task<Dictionary<string, object>> RequestTapToken()
20
+ private static async Task<Dictionary<string, object>> RequestTapToken(bool showAuthorizationLoading)
20
21
  {
22
+ var ownsLoading = showAuthorizationLoading && ConfigModule.TapConfig != null && ConfigModule.UsingTapPC;
21
23
  try
22
24
  {
23
25
  AliyunTrack.LoginAuthorize();
24
26
 
25
- if (ConfigModule.TapConfig != null && ConfigModule.UsingTapPC)
27
+ if (ownsLoading)
26
28
  {
27
29
  UIManager.ShowLoading(timeout: 3);
28
30
  }
@@ -32,10 +34,6 @@ namespace XD.SDK.Account.Internal.Standalone
32
34
  var authData = authDataResult.GetValueOrThrow();
33
35
  authData.Add("type", (int)LoginType.TapTap);
34
36
  authData.Add("scope", string.Join(",", permissions?.ToArray()));
35
- if (ConfigModule.TapConfig != null && ConfigModule.UsingTapPC)
36
- {
37
- UIManager.DismissLoading();
38
- }
39
37
  AliyunTrack.LoginAuthorizeSuccess();
40
38
  return authData;
41
39
  }
@@ -57,9 +55,14 @@ namespace XD.SDK.Account.Internal.Standalone
57
55
  {
58
56
  AliyunTrack.LoginAuthorizeFail(e.ErrorMsg);
59
57
  XDGLogger.Warn($"Tap 登录失败:{e.ErrorMsg}",XDGLoggerTag.Common);
58
+ if (e.Code == ResponseCode.Common.Cancelled) throw;
60
59
  throw new XDGError(ResponseCode.Common.Failed, e.ErrorMsg);
61
60
  }
61
+ finally
62
+ {
63
+ if (ownsLoading) UIManager.DismissLoading();
64
+ }
62
65
  }
63
66
  }
64
67
  }
65
- #endif
68
+ #endif
@@ -137,10 +137,13 @@ namespace XD.SDK.Account.Internal.Standalone
137
137
 
138
138
  XDGLogger.Debug("[Auth] Auth timeout (2min)", XDGLoggerTag.Account);
139
139
  StopAllListeners();
140
- return new Dictionary<string, object> { { "type", (int)loginType } };
140
+ throw new XDGError("LOGIN_AUTHORIZATION_TIMEOUT");
141
141
  }
142
142
  finally
143
143
  {
144
+ StopAllListeners();
145
+ _ = httpTask.ContinueWith(t => { var ignored = t.Exception; },
146
+ TaskContinuationOptions.OnlyOnFaulted);
144
147
  if (Interlocked.CompareExchange(ref cleaned, 1, 0) == 0)
145
148
  {
146
149
  #if UNITY_STANDALONE_WIN && !UNITY_EDITOR
@@ -2,7 +2,6 @@
2
2
  using System;
3
3
  using System.Collections.Generic;
4
4
  using System.Net;
5
- using System.Threading;
6
5
  using System.Threading.Tasks;
7
6
  using UnityEngine;
8
7
  using XD.SDK.Common;
@@ -93,39 +92,41 @@ namespace XD.SDK.Account.Internal.Standalone
93
92
 
94
93
  // 弹出授权页
95
94
  XDGLogger.Debug($"[Auth] url: {url}", XDGLoggerTag.Account);
96
- XDGLogger.Debug($"[Auth] state: {state}", XDGLoggerTag.Account);
97
95
  XDGLogger.Debug($"[Auth] urlSchemeRedirect: {urlSchemeRedirect}", XDGLoggerTag.Account);
98
96
  XDGLogger.Debug($"[Auth] redirectUri(http): {redirectUri}", XDGLoggerTag.Account);
99
- XDGLogger.Debug($"[Auth] authRequest: {authRequest}", XDGLoggerTag.Account);
100
97
  AliyunTrack.LoginAuthorize();
101
98
  // authRequest 的 query 已经过 XDUrlUtils.ToQueryString 编码,避免二次转义导致参数异常
102
- Application.OpenURL(authRequest);
103
99
 
104
100
  // 启动监听
105
101
  HttpListener server = new HttpListener();
106
102
  server.Prefixes.Add($"{redirectUri}/");
107
- server.Start();
108
-
109
- servers.Add(server);
110
103
 
111
104
  // UrlScheme 竞速需要同时满足:平台支持 + scheme 可用 + state 存在(用于会话隔离)
112
105
  // state 为空时直接走 HttpListener 兜底(UrlSchemeAuth 内部也会检查并回退)
113
106
  Task<Dictionary<string, object>> HttpFallback()
114
107
  {
115
- return WaitForHttpCallbackAsync(servers, server, loginType);
108
+ return WaitForHttpCallbackAsync(servers, server, loginType, state);
116
109
  }
117
110
 
118
- return await UrlSchemeAuth.WaitForFirstCallbackAsync(
119
- servers,
120
- loginType,
121
- state,
122
- HttpFallback);
111
+ try
112
+ {
113
+ server.Start();
114
+ servers.Add(server);
115
+ Application.OpenURL(authRequest);
116
+ return await UrlSchemeAuth.WaitForFirstCallbackAsync(
117
+ servers, loginType, state, HttpFallback);
118
+ }
119
+ finally
120
+ {
121
+ server.Close();
122
+ servers.Remove(server);
123
+ }
123
124
  }
124
125
 
125
126
  private static async Task<Dictionary<string, object>> WaitForHttpCallbackAsync(
126
127
  List<HttpListener> servers,
127
128
  HttpListener server,
128
- LoginType loginType)
129
+ LoginType loginType, string state)
129
130
  {
130
131
  Dictionary<string, object> authData = new Dictionary<string, object>
131
132
  {
@@ -138,7 +139,6 @@ namespace XD.SDK.Account.Internal.Standalone
138
139
  {
139
140
  HttpListenerContext context = await server.GetContextAsync();
140
141
 
141
- XDGLogger.Debug($"Request url: {context.Request.RawUrl}", XDGLoggerTag.Account);
142
142
  XDGLogger.Debug($"Request method: {context.Request.HttpMethod}", XDGLoggerTag.Account);
143
143
 
144
144
  context.Response.StatusCode = 200;
@@ -149,6 +149,14 @@ namespace XD.SDK.Account.Internal.Standalone
149
149
  continue;
150
150
  }
151
151
 
152
+ string[] urlSegments = context.Request.RawUrl.Split('?');
153
+ var dict = urlSegments.Length < 2 ? new Dictionary<string, object>()
154
+ : ParseQueryStringToDict(urlSegments[1]);
155
+ object callbackState;
156
+ if (!string.IsNullOrEmpty(state)
157
+ && (!dict.TryGetValue(StateKey, out callbackState) || (string)callbackState != state))
158
+ continue;
159
+
152
160
  foreach (HttpListener svr in servers)
153
161
  {
154
162
  svr.Stop();
@@ -156,13 +164,6 @@ namespace XD.SDK.Account.Internal.Standalone
156
164
 
157
165
  servers.Clear();
158
166
 
159
- string[] urlSegments = context.Request.RawUrl.Split('?');
160
- if (urlSegments.Length < 2)
161
- {
162
- return authData;
163
- }
164
-
165
- var dict = ParseQueryStringToDict(urlSegments[1]);
166
167
  foreach (var kv in dict)
167
168
  {
168
169
  authData[kv.Key] = kv.Value;
@@ -174,14 +175,11 @@ namespace XD.SDK.Account.Internal.Standalone
174
175
  catch (Exception e)
175
176
  {
176
177
  XDGLogger.Debug(e.Message, XDGLoggerTag.Account);
177
- // 异常结果则一直 pending(保持原行为)
178
178
  AliyunTrack.LoginAuthorizeFail(e.Message);
179
- TaskCompletionSource<Dictionary<string, object>> pending_tcs =
180
- new TaskCompletionSource<Dictionary<string, object>>();
181
- return await pending_tcs.Task;
179
+ throw;
182
180
  }
183
181
  }
184
182
  }
185
183
  }
186
184
  }
187
- #endif
185
+ #endif
@@ -2,8 +2,9 @@
2
2
  using System;
3
3
  using System.Collections.Generic;
4
4
  using System.Threading.Tasks;
5
- using XD.SDK.Common;
6
5
  using XD.SDK.Common.Internal;
6
+ using Newtonsoft.Json.Linq;
7
+ using XD.SDK.Common;
7
8
  using XD.SDK.Common.Internal.Standalone;
8
9
 
9
10
  namespace XD.SDK.Account.Internal.Standalone
@@ -13,6 +14,26 @@ namespace XD.SDK.Account.Internal.Standalone
13
14
  private const int RequiredKr = 40313;
14
15
  private const int RequiredGlobal = 40314;
15
16
  internal static Action<bool> LogoutHandler;
17
+ internal static bool UsesXdProvider { get; private set; }
18
+
19
+
20
+ internal static bool IsCnXd(XDHttpException error)
21
+ {
22
+ if (ConfigModule.IsGlobal || error == null || error.Code != RequiredGlobal || error.ExtraData == null) return false;
23
+ var data = JObject.FromObject(error.ExtraData);
24
+ return (string)(data["extra"]?["realNameProvider"] ?? data["realNameProvider"]) == "XD";
25
+ }
26
+
27
+ internal static void SetProvider(string provider)
28
+ {
29
+ if (!ConfigModule.IsGlobal && !string.IsNullOrEmpty(provider) && provider != "XD" && provider != "TAPSDK")
30
+ throw new XDComplianceException("CN_COMPLIANCE_PROVIDER_UNSUPPORTED");
31
+ if (!ConfigModule.IsGlobal && UsesXdProvider && string.IsNullOrEmpty(provider))
32
+ throw new XDComplianceException("CN_COMPLIANCE_PROVIDER_MISSING");
33
+ var usesXd = !ConfigModule.IsGlobal && provider == "XD";
34
+ if (UsesXdProvider != usesXd) XDComplianceCountdownService.Cancel();
35
+ UsesXdProvider = usesXd;
36
+ }
16
37
 
17
38
  private static bool _isTimeLimitDialogVisible;
18
39
  private static int _timeLimitDialogVersion;
@@ -27,9 +48,9 @@ namespace XD.SDK.Account.Internal.Standalone
27
48
  return exception != null && IsRequired(exception.Code);
28
49
  }
29
50
 
30
- internal static async Task RunOnLogin(string url)
51
+ internal static async Task<XDComplianceCloseResult> RunOnLogin(string url, bool cnXd = false)
31
52
  {
32
- if (!ConfigModule.IsGlobal)
53
+ if (!ConfigModule.IsGlobal && !cnXd)
33
54
  {
34
55
  XDGLogger.Warn("[Compliance] Compliance required code received in non-Global region. The server should only issue 40313/40314 to Global compliance clients.",
35
56
  XDGLoggerTag.Account);
@@ -42,13 +63,12 @@ namespace XD.SDK.Account.Internal.Standalone
42
63
  }
43
64
 
44
65
  var result = await XDComplianceWebOpener.OpenAsync(url);
45
- if (!result.IsPassed)
66
+ if (!result.IsPassed && !cnXd)
46
67
  {
47
68
  throw new XDComplianceException(result.Reason ?? "Compliance cancelled");
48
69
  }
49
70
 
50
- // Web close payload only indicates whether the compliance flow passed.
51
- // The retried /account/v2/info response is the authoritative countdown source.
71
+ return result;
52
72
  }
53
73
 
54
74
  internal static void ApplyRemainingSeconds(long? remainingSeconds)
@@ -65,6 +85,7 @@ namespace XD.SDK.Account.Internal.Standalone
65
85
 
66
86
  internal static void Stop()
67
87
  {
88
+ UsesXdProvider = false;
68
89
  XDComplianceCountdownService.Cancel();
69
90
  _isTimeLimitDialogVisible = false;
70
91
  _timeLimitDialogVersion++;
@@ -7,6 +7,7 @@ namespace XD.SDK.Account.Internal.Standalone
7
7
  internal class XDComplianceException : XDGError
8
8
  {
9
9
  internal Exception OriginalException { get; }
10
+ internal bool ExitGameRequested { get; set; }
10
11
 
11
12
  internal XDComplianceException(string message)
12
13
  : base(ResponseCode.Common.Cancelled, message)
@@ -9,11 +9,13 @@ namespace XD.SDK.Account.Internal.Standalone
9
9
  internal static class XDComplianceWebOpener
10
10
  {
11
11
  private static TaskCompletionSource<XDComplianceCloseResult> _currentTcs;
12
+ private static UIElement _view;
12
13
 
13
14
  internal static bool IsActive => _currentTcs != null;
14
15
 
15
16
  internal static Task<XDComplianceCloseResult> OpenAsync(string url)
16
17
  {
18
+ if (IsActive) throw new XDComplianceException("COMPLIANCE_IN_PROGRESS");
17
19
  var tcs = new TaskCompletionSource<XDComplianceCloseResult>();
18
20
 
19
21
  if (string.IsNullOrEmpty(url))
@@ -23,13 +25,14 @@ namespace XD.SDK.Account.Internal.Standalone
23
25
  return tcs.Task;
24
26
  }
25
27
 
28
+
26
29
  _currentTcs = tcs;
27
- XDGLogger.Debug($"[Compliance] Open compliance web: {url}", XDGLoggerTag.Account);
30
+ XDGLogger.Debug("[Compliance] Open compliance web", XDGLoggerTag.Account);
28
31
 
29
32
  #if (UNITY_STANDALONE || (UNITY_EDITOR && !UNITY_ANDROID && !UNITY_IOS)) && !XDSDK_DISABLE_VUPLEX
30
33
  try
31
34
  {
32
- XDGCommon.OpenWebPage(url, (action, data) =>
35
+ WebRequest.OpenWebPage(url, (action, data) =>
33
36
  {
34
37
  if (action != WebActionEnum.CLOSE)
35
38
  {
@@ -37,7 +40,7 @@ namespace XD.SDK.Account.Internal.Standalone
37
40
  }
38
41
 
39
42
  Complete(tcs, XDComplianceCloseResult.Parse(data));
40
- });
43
+ }, null, view => { if (_currentTcs == tcs) _view = view; });
41
44
  }
42
45
  catch (Exception e)
43
46
  {
@@ -63,7 +66,7 @@ namespace XD.SDK.Account.Internal.Standalone
63
66
 
64
67
  try
65
68
  {
66
- UIManager.Dismiss();
69
+ if (_view != null) UIManager.Dismiss(_view);
67
70
  }
68
71
  catch (Exception e)
69
72
  {
@@ -81,6 +84,7 @@ namespace XD.SDK.Account.Internal.Standalone
81
84
  }
82
85
 
83
86
  _currentTcs = null;
87
+ _view = null;
84
88
  tcs.TrySetResult(result);
85
89
  }
86
90
  }
@@ -210,7 +210,9 @@ namespace XD.SDK.Account.Internal.Standalone
210
210
  return XDHttpClient.Client.PostAsync<BaseResponse>(XDG_UNBIND_INTERFACE, data: data);
211
211
  }
212
212
 
213
- public static async Task<XDGUser> Login(LoginType loginType)
213
+ public static async Task<XDGUser> Login(LoginType loginType,
214
+ XDGAccessToken authenticatedToken = null, Action onAuthenticated = null,
215
+ bool requireFreshInfo = false, bool showAuthorizationLoading = true)
214
216
  {
215
217
  if (XDGCommonInternal.IsCn() && loginType == LoginType.Email)
216
218
  {
@@ -218,6 +220,9 @@ namespace XD.SDK.Account.Internal.Standalone
218
220
  throw new XDGError(ResponseCode.Common.UnavailableService, "暂不支持的登录方式");
219
221
  }
220
222
 
223
+ if (loginType == LoginType.XD && authenticatedToken == null)
224
+ throw new XDGError(ResponseCode.Account.TypeNotAvailable, "LOGIN_CREDENTIAL_REQUIRED");
225
+
221
226
  if (loginType == LoginType.Console)
222
227
  {
223
228
  return await LoginByConsole();
@@ -232,7 +237,7 @@ namespace XD.SDK.Account.Internal.Standalone
232
237
  XDGLogger.Warn("自动登录缺少本地登录信息", XDGLoggerTag.Account);
233
238
  if (ConfigModule.UsingTapPC && !ConfigModule.DisableAutoLogin2Tap)
234
239
  {
235
- return await Login(LoginType.TapTap);
240
+ return await Login(LoginType.TapTap, null, onAuthenticated, requireFreshInfo, showAuthorizationLoading);
236
241
  }
237
242
 
238
243
  throw new XDGError(ResponseCode.Common.Failed, XDLocalization.GetCurrentLocalizableString().LoginFailed);
@@ -257,36 +262,23 @@ namespace XD.SDK.Account.Internal.Standalone
257
262
  }
258
263
  }
259
264
 
260
- try
261
- {
262
- localUser = await FetchUserInfo();
263
- }
264
- catch (XDHttpException e)
265
- {
266
- if (e.HttpStatusCode == 401 || e.Code == 40311 || e.Code == 40312 || XDCompliance.IsRequired(e))
267
- {
268
- throw;
269
- }
270
- }
271
- catch (XDComplianceException)
272
- {
273
- throw;
274
- }
275
- catch (Exception e)
276
- {
277
- XDGLogger.Warn(e.Message, XDGLoggerTag.Account);
278
- }
279
-
265
+ localUser = await FetchUserInfoForAutoLogin(localUser, requireFreshInfo);
280
266
  _ = AccessTokenModule.Refresh();
281
267
 
282
268
  return localUser;
283
269
  }
284
270
 
271
+ var ownsLoading = false;
285
272
  try
286
273
  {
287
274
  AliyunTrack.LoginEnableAuthorizeTrack();
288
275
  // 单独处理手机号登录
289
- if (loginType == LoginType.Phone)
276
+ if (authenticatedToken != null)
277
+ {
278
+ onAuthenticated?.Invoke();
279
+ await AccessTokenModule.ImportAuthenticatedToken(authenticatedToken);
280
+ }
281
+ else if (loginType == LoginType.Phone)
290
282
  {
291
283
  AliyunTrack.ResetPhoneLoginData();
292
284
  AliyunTrack.LoginEnableSDKLoginTrack();
@@ -301,6 +293,7 @@ namespace XD.SDK.Account.Internal.Standalone
301
293
  await PhoneModuleIO.LoginOrBind(true);
302
294
  }
303
295
 
296
+ ownsLoading = true;
304
297
  UIManager.ShowLoading();
305
298
  #else
306
299
  throw new XDGError(ResponseCode.Common.Failed, "This function need vuplex enabled");
@@ -313,6 +306,7 @@ namespace XD.SDK.Account.Internal.Standalone
313
306
  #if ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) || ((UNITY_EDITOR_WIN || UNITY_EDITOR_OSX) && !UNITY_ANDROID && !UNITY_IOS))
314
307
  EnsureWebViewAvailable();
315
308
  await EmailModule.LoginOrBind(true);
309
+ ownsLoading = true;
316
310
  UIManager.ShowLoading();
317
311
  #else
318
312
  throw new XDGError(ResponseCode.Common.Failed, "This function need vuplex enabled");
@@ -320,14 +314,15 @@ namespace XD.SDK.Account.Internal.Standalone
320
314
  }
321
315
  else
322
316
  {
323
- Dictionary<string, object> loginParams = await GetLoginAuthData(loginType);
317
+ Dictionary<string, object> loginParams = await GetLoginAuthData(loginType, showAuthorizationLoading);
318
+ ownsLoading = true;
324
319
  UIManager.ShowLoading();
325
320
  Dictionary<string, object> cacheData = GetCacheData(loginType);
326
- await AccessTokenModule.Login(loginParams, cacheData);
321
+ await AccessTokenModule.Login(loginParams, cacheData, onAuthenticated);
327
322
  }
328
323
 
329
324
  AliyunTrack.LoginEnableSDKLoginTrack();
330
- var user = await FetchUserInfo();
325
+ var user = await FetchUserInfo(true);
331
326
  try
332
327
  {
333
328
  await SyncTdsUser(user.UserId);
@@ -337,12 +332,13 @@ namespace XD.SDK.Account.Internal.Standalone
337
332
  XDGLogger.Warn(e.ToString(), XDGLoggerTag.Account);
338
333
  }
339
334
 
335
+
340
336
  XDGLogger.Debug(string.Format($"xd userID: {user.UserId}"), XDGLoggerTag.Account);
341
337
  return user;
342
338
  }
343
339
  catch (XDGError e)
344
340
  {
345
- UIManager.DismissLoading();
341
+ if (ownsLoading) UIManager.DismissLoading();
346
342
  if (e.ExtraData != null)
347
343
  {
348
344
  LocalizableString localizableString = XDLocalization.GetCurrentLocalizableString();
@@ -400,7 +396,7 @@ namespace XD.SDK.Account.Internal.Standalone
400
396
  }
401
397
  finally
402
398
  {
403
- UIManager.DismissLoading();
399
+ if (ownsLoading) UIManager.DismissLoading();
404
400
  }
405
401
  }
406
402
 
@@ -422,7 +418,7 @@ namespace XD.SDK.Account.Internal.Standalone
422
418
  {
423
419
  try
424
420
  {
425
- user = await FetchUserInfo();
421
+ user = await FetchUserInfo(true);
426
422
  // 同自动登录一样,触发刷新 token
427
423
  _ = AccessTokenModule.Refresh();
428
424
  }
@@ -479,17 +475,18 @@ namespace XD.SDK.Account.Internal.Standalone
479
475
  Dictionary<string, object> cacheData = SteamAuth.GetCacheData();
480
476
  AliyunTrack.LoginEnableSDKLoginTrack();
481
477
  await AccessTokenModule.SignIn(authData, cacheData);
482
- return await FetchUserInfo();
478
+ return await FetchUserInfo(true);
483
479
  }
484
480
 
485
- internal static async Task<Dictionary<string, object>> GetLoginAuthData(LoginType loginType)
481
+ internal static async Task<Dictionary<string, object>> GetLoginAuthData(LoginType loginType,
482
+ bool showAuthorizationLoading = true)
486
483
  {
487
484
  switch (loginType)
488
485
  {
489
486
  case LoginType.Guest:
490
487
  return GuestAuth.GetAuthData();
491
488
  case LoginType.TapTap:
492
- return await TapAuth.GetAuthData();
489
+ return await TapAuth.GetAuthData(showAuthorizationLoading);
493
490
  case LoginType.Apple:
494
491
  return await AppleAuth.GetAuthData();
495
492
  case LoginType.Google:
@@ -529,16 +526,46 @@ namespace XD.SDK.Account.Internal.Standalone
529
526
  }
530
527
  }
531
528
 
529
+ private static async Task<XDGUser> FetchUserInfoForAutoLogin(XDGUser localUser, bool requireFreshInfo = false)
530
+ {
531
+ // 国内的合规分流依赖本次 info,不能在请求失败后猜测为 Tap。
532
+ if (!ConfigModule.IsGlobal && (requireFreshInfo || XDCompliance.UsesXdProvider))
533
+ return await FetchUserInfo(true);
534
+ try
535
+ {
536
+ return await FetchUserInfo(true);
537
+ }
538
+ catch (XDHttpException e)
539
+ {
540
+ if (e.HttpStatusCode == 401 || e.Code == 40311 || e.Code == 40312 || XDCompliance.IsRequired(e))
541
+ throw;
542
+ }
543
+ catch (XDComplianceException)
544
+ {
545
+ throw;
546
+ }
547
+ catch (Exception e)
548
+ {
549
+ XDGLogger.Warn(e.Message, XDGLoggerTag.Account);
550
+ }
551
+ return localUser;
552
+ }
553
+
532
554
  public static Task<XDGUser> FetchUserInfo()
533
555
  {
534
556
  return FetchUserInfo(true);
535
557
  }
536
558
 
537
- private static async Task<XDGUser> FetchUserInfo(bool allowComplianceRetry)
559
+ private static async Task<XDGUser> FetchUserInfo(bool allowComplianceRetry, bool requireXdProvider = false)
538
560
  {
539
561
  try
540
562
  {
541
563
  ProfileResponse response = await XDHttpClient.Client.GetAsync<ProfileResponse>(XDG_USER_PROFILE);
564
+ if (response == null || response.Code != 200 || response.User == null)
565
+ throw new XDComplianceException("ACCOUNT_INFO_INVALID");
566
+ if (requireXdProvider && response.RealNameProvider != "XD")
567
+ throw new XDComplianceException("CN_COMPLIANCE_PROVIDER_MISMATCH");
568
+ XDCompliance.SetProvider(response.RealNameProvider);
542
569
 
543
570
  if (current == null)
544
571
  {
@@ -557,16 +584,23 @@ namespace XD.SDK.Account.Internal.Standalone
557
584
  catch (XDHttpException xdException)
558
585
  {
559
586
  var isComplianceRequired = XDCompliance.IsRequired(xdException);
587
+ var cnXd = XDCompliance.IsCnXd(xdException);
560
588
  var complianceUrl = GetComplianceUrl(xdException.ExtraData);
561
589
  if (allowComplianceRetry
562
590
  && isComplianceRequired
591
+ && (ConfigModule.IsGlobal || cnXd)
563
592
  && !XDComplianceWebOpener.IsActive
564
593
  && !string.IsNullOrEmpty(complianceUrl))
565
594
  {
566
- XDGLogger.Debug($"[Compliance] Trigger login web. code={xdException.Code}, message={xdException.ErrorMsg}, detail={xdException.Detail}, global={ConfigModule.IsGlobal}, active={XDComplianceWebOpener.IsActive}, url={complianceUrl}", XDGLoggerTag.Account);
595
+ XDGLogger.Debug($"[Compliance] Open login compliance. code={xdException.Code}, cnXd={cnXd}", XDGLoggerTag.Account);
596
+ XDComplianceCloseResult closeResult;
567
597
  try
568
598
  {
569
- await XDCompliance.RunOnLogin(complianceUrl);
599
+ UIManager.DismissLoading();
600
+ closeResult = await XDCompliance.RunOnLogin(complianceUrl, cnXd);
601
+ if (cnXd && (closeResult.Reason == "switch_account" || closeResult.Reason == "exit_game"))
602
+ throw new XDComplianceException(closeResult.Reason)
603
+ { ExitGameRequested = closeResult.Reason == "exit_game" };
570
604
  }
571
605
  catch (Exception e)
572
606
  {
@@ -576,7 +610,9 @@ namespace XD.SDK.Account.Internal.Standalone
576
610
 
577
611
  try
578
612
  {
579
- return await FetchUserInfo(false);
613
+ var rechecked = await FetchUserInfo(false, cnXd);
614
+ if (cnXd && !closeResult.IsPassed) throw new XDComplianceException(closeResult.Reason ?? "user_canceled");
615
+ return rechecked;
580
616
  }
581
617
  // IL2CPP: keep explicit catch order; do not use catch filters.
582
618
  catch (XDComplianceException)
@@ -595,7 +631,7 @@ namespace XD.SDK.Account.Internal.Standalone
595
631
 
596
632
  if (isComplianceRequired)
597
633
  {
598
- XDGLogger.Warn($"[Compliance] Login web not opened. code={xdException.Code}, message={xdException.ErrorMsg}, detail={xdException.Detail}, global={ConfigModule.IsGlobal}, allowRetry={allowComplianceRetry}, active={XDComplianceWebOpener.IsActive}, hasExtraData={xdException.ExtraData != null}, url={complianceUrl}, extraData={SerializeComplianceExtraData(xdException.ExtraData)}", XDGLoggerTag.Account);
634
+ XDGLogger.Warn($"[Compliance] Login blocked. code={xdException.Code}, cnXd={cnXd}, allowRetry={allowComplianceRetry}, hasUrl={!string.IsNullOrEmpty(complianceUrl)}", XDGLoggerTag.Account);
599
635
  }
600
636
 
601
637
  if (xdException.Code == 40312 && xdException.ExtraData != null)
@@ -0,0 +1,37 @@
1
+ #if ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) || ((UNITY_EDITOR_WIN || UNITY_EDITOR_OSX) && !UNITY_ANDROID && !UNITY_IOS))
2
+ using System;
3
+ using System.Globalization;
4
+ using Newtonsoft.Json.Linq;
5
+ using XD.SDK.Common;
6
+ using XD.SDK.Common.Internal;
7
+ using XD.SDK.Common.Internal.Standalone;
8
+
9
+ namespace XD.SDK.Account.Internal.Standalone
10
+ {
11
+ internal static class LoginBridgeProtocol
12
+ {
13
+ internal static string ReadRequiredString(JObject data, string key)
14
+ {
15
+ var value = data?[key];
16
+ if (value?.Type != JTokenType.String || string.IsNullOrWhiteSpace((string)value))
17
+ throw new XDGError(ResponseCode.Common.InvalidParam, "LOGIN_REQUEST_INVALID");
18
+ return (string)value;
19
+ }
20
+
21
+ internal static XDGError ToError(Exception error) => error as XDGError ?? error.ParseToError();
22
+
23
+ internal static WebBridgeResponse.Failed Failure(XDGError error)
24
+ {
25
+ return new WebBridgeResponse.Failed
26
+ {
27
+ Msg = error.ErrorMsg,
28
+ Error = new
29
+ {
30
+ code = error.Code.ToString(CultureInfo.InvariantCulture),
31
+ cancelled = error.Code == ResponseCode.Common.Cancelled
32
+ }
33
+ };
34
+ }
35
+ }
36
+ }
37
+ #endif
@@ -0,0 +1,2 @@
1
+ fileFormatVersion: 2
2
+ guid: 7d334e6e883f57405a1bf487d74f23d4
@@ -0,0 +1,36 @@
1
+ #if ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) || ((UNITY_EDITOR_WIN || UNITY_EDITOR_OSX) && !UNITY_ANDROID && !UNITY_IOS))
2
+ using System;
3
+ using Newtonsoft.Json.Linq;
4
+ using XD.SDK.Common;
5
+ using XD.SDK.Common.Internal;
6
+ using XD.SDK.Common.Internal.Standalone;
7
+
8
+ namespace XD.SDK.Account.Internal.Standalone
9
+ {
10
+ public sealed class LoginByTypeWebFunction : IWebFunction
11
+ {
12
+ public string GetName() => "loginByType";
13
+ public void Handler(IBridgeWebView web, string data, Action<object> callback)
14
+ {
15
+ try
16
+ {
17
+ var request = JObject.Parse(data);
18
+ var value = request["loginType"];
19
+ if (value != null && value.Type == JTokenType.String
20
+ && (string.Equals(value.ToString(), "qq", StringComparison.OrdinalIgnoreCase)
21
+ || string.Equals(value.ToString(), "wechat", StringComparison.OrdinalIgnoreCase)))
22
+ throw new XDGError(ResponseCode.Account.TypeNotAvailable, "LOGIN_METHOD_UNAVAILABLE");
23
+ LoginType type;
24
+ if (value == null || (value.Type != JTokenType.String && value.Type != JTokenType.Integer)
25
+ || !Enum.TryParse(value.ToString(), true, out type) || !Enum.IsDefined(typeof(LoginType), type))
26
+ throw new XDGError(ResponseCode.Common.InvalidParam, "LOGIN_TYPE_INVALID");
27
+ Action<XDGUser> success = user => callback?.Invoke(new WebBridgeResponse.Success
28
+ { Data = user });
29
+ Action<XDGError> failed = error => callback?.Invoke(LoginBridgeProtocol.Failure(error));
30
+ AccountFeaturesImpl.Instance.LoginByType(type, success, failed);
31
+ }
32
+ catch (Exception e) { callback?.Invoke(LoginBridgeProtocol.Failure(LoginBridgeProtocol.ToError(e))); }
33
+ }
34
+ }
35
+ }
36
+ #endif
@@ -0,0 +1,2 @@
1
+ fileFormatVersion: 2
2
+ guid: a5da0d940ffd3107a9a9d98b8ebc52a7
@@ -0,0 +1,92 @@
1
+ #if ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) || ((UNITY_EDITOR_WIN || UNITY_EDITOR_OSX) && !UNITY_ANDROID && !UNITY_IOS))
2
+ using System;
3
+ using System.Collections.Generic;
4
+ using Newtonsoft.Json.Linq;
5
+ using XD.SDK.Common;
6
+ using XD.SDK.Common.Internal;
7
+ using XD.SDK.Common.Internal.Standalone;
8
+ using XD.SDK.WebView;
9
+
10
+ namespace XD.SDK.Account.Internal.Standalone
11
+ {
12
+ /// <summary>打开登录页面,并将页面最终结果交付给调用方一次。</summary>
13
+ internal sealed class LoginPanelController
14
+ {
15
+ private const string LoginPath = "/login?xdBgColor=00000000&xdClose=0&xdNav=0";
16
+ private static LoginPanelController Current;
17
+ private static bool IsActive => Current != null;
18
+ private readonly Action<XDGUser> _success;
19
+ private readonly Action<XDGError> _failure;
20
+ private bool _ended;
21
+
22
+ private LoginPanelController(Action<XDGUser> success, Action<XDGError> failure)
23
+ {
24
+ _success = success;
25
+ _failure = failure;
26
+ }
27
+
28
+ internal static void Open(Action<XDGUser> success, Action<XDGError> failure)
29
+ {
30
+ LoginPanelController panel = null;
31
+ try
32
+ {
33
+ if (!XDGCommonInternal.IsInitialized()) throw XDGErrorExtensions.NotInitError();
34
+ if (IsActive) throw new XDGError(ResponseCode.Common.Failed, "LOGIN_IN_PROGRESS");
35
+ if (!XDWebViewService.IsAvailable) throw new XDGError("WEBVIEW_UNAVAILABLE");
36
+ panel = new LoginPanelController(success, failure);
37
+ Current = panel;
38
+ WebRequest.OpenWebPage(AuthConstants.CN_PERSONAL_INFO + LoginPath, panel.OnWebAction);
39
+ }
40
+ catch (Exception error)
41
+ {
42
+ if (panel != null) panel.Finish(null, LoginBridgeProtocol.ToError(error));
43
+ else failure?.Invoke(LoginBridgeProtocol.ToError(error));
44
+ }
45
+ }
46
+
47
+ private void OnWebAction(WebActionEnum action, Dictionary<string, object> data)
48
+ {
49
+ if (action != WebActionEnum.CLOSE || _ended) return;
50
+ try
51
+ {
52
+ var payload = data == null ? new JObject() : JObject.FromObject(data);
53
+ var errorCode = payload["errorCode"]?.ToString();
54
+ if (!string.IsNullOrEmpty(errorCode))
55
+ {
56
+ int numericCode;
57
+ Finish(null, int.TryParse(errorCode, out numericCode)
58
+ ? new XDGError(numericCode, payload["errorMessage"]?.ToString() ?? errorCode)
59
+ : new XDGError(errorCode));
60
+ return;
61
+ }
62
+ if (payload["user"] != null)
63
+ {
64
+ var userData = payload["user"] as JObject;
65
+ if (userData == null || userData["userId"]?.Type != JTokenType.String
66
+ || string.IsNullOrWhiteSpace((string)userData["userId"]))
67
+ throw new XDGError("LOGIN_RESULT_INVALID");
68
+ var user = userData.ToObject<XDGUser>();
69
+ Finish(user, null);
70
+ return;
71
+ }
72
+ Finish(null, XDGErrorExtensions.CancelledError());
73
+ }
74
+ catch (Exception error) { Finish(null, LoginBridgeProtocol.ToError(error)); }
75
+ }
76
+
77
+ private void Finish(XDGUser user, XDGError error)
78
+ {
79
+ if (_ended) return;
80
+ _ended = true;
81
+ if (Current == this) Current = null;
82
+ // 回调方异常不能导致第二次结果交付。
83
+ try
84
+ {
85
+ if (error != null) _failure?.Invoke(error);
86
+ else _success?.Invoke(user);
87
+ }
88
+ catch { }
89
+ }
90
+ }
91
+ }
92
+ #endif
@@ -0,0 +1,2 @@
1
+ fileFormatVersion: 2
2
+ guid: d8bb3e916b923942298d2ee9a9ce321c
@@ -0,0 +1,61 @@
1
+ #if ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) || ((UNITY_EDITOR_WIN || UNITY_EDITOR_OSX) && !UNITY_ANDROID && !UNITY_IOS))
2
+ using System;
3
+ using System.Globalization;
4
+ using Newtonsoft.Json.Linq;
5
+ using XD.SDK.Common;
6
+ using XD.SDK.Common.Internal;
7
+ using XD.SDK.Common.Internal.Standalone;
8
+
9
+ namespace XD.SDK.Account.Internal.Standalone
10
+ {
11
+ /// <summary>Web 凭据交接通过本次调用回调,等待 SDK 完整后处理。</summary>
12
+ public sealed class LoginWithAuthWebFunction : IWebFunction
13
+ {
14
+ public string GetName() => "loginWithAuth";
15
+ public async void Handler(IBridgeWebView web, string data, Action<object> callback)
16
+ {
17
+ var started = System.Diagnostics.Stopwatch.StartNew();
18
+ XDGLogger.Debug("[loginWithAuth] Received credential login request.", XDGLoggerTag.Account);
19
+ object response;
20
+ try
21
+ {
22
+ var payload = JObject.Parse(data);
23
+ var loginType = LoginBridgeProtocol.ReadRequiredString(payload, "loginType");
24
+ if (loginType != "xd" && loginType != "phone") throw new XDGError("LOGIN_METHOD_UNAVAILABLE");
25
+ var type = loginType == "xd" ? LoginType.XD : LoginType.Phone;
26
+ var credentialData = payload["credential"] as JObject;
27
+ if (credentialData == null) throw new XDGError("LOGIN_CREDENTIAL_INVALID");
28
+ var credential = ParseCredential(credentialData);
29
+ XDGLogger.Debug($"[loginWithAuth] Credential validated, loginType={type}; starting SDK login.", XDGLoggerTag.Account);
30
+ var user = await AccountFeaturesImpl.Instance.LoginWithAuth(type, credential);
31
+ XDGLogger.Debug($"[loginWithAuth] SDK login succeeded, elapsedMs={started.ElapsedMilliseconds}.", XDGLoggerTag.Account);
32
+ response = new WebBridgeResponse.Success { Data = user };
33
+ }
34
+ catch (Exception e)
35
+ {
36
+ var error = LoginBridgeProtocol.ToError(e);
37
+ XDGLogger.Warn($"[loginWithAuth] Failed, code={error.Code}, exceptionType={e.GetType().Name}, elapsedMs={started.ElapsedMilliseconds}.", XDGLoggerTag.Account);
38
+ response = LoginBridgeProtocol.Failure(error);
39
+ }
40
+ XDGLogger.Debug($"[loginWithAuth] Returning bridge result, callbackAvailable={callback != null}.", XDGLoggerTag.Account);
41
+ callback?.Invoke(response);
42
+ }
43
+
44
+ private static XDGAccessToken ParseCredential(JObject credential)
45
+ {
46
+ if (!long.TryParse(LoginBridgeProtocol.ReadRequiredString(credential, "expireIn"),
47
+ NumberStyles.None, CultureInfo.InvariantCulture, out var expiry))
48
+ throw new XDGError("LOGIN_CREDENTIAL_INVALID");
49
+ return new XDGAccessToken
50
+ {
51
+ Kid = LoginBridgeProtocol.ReadRequiredString(credential, "kid"),
52
+ MacKey = LoginBridgeProtocol.ReadRequiredString(credential, "macKey"),
53
+ MacAlgorithm = credential["macAlgorithm"]?.Type == JTokenType.String
54
+ ? (string)credential["macAlgorithm"] : null,
55
+ TokenType = LoginBridgeProtocol.ReadRequiredString(credential, "tokenType"),
56
+ ExpireIn = expiry
57
+ };
58
+ }
59
+ }
60
+ }
61
+ #endif
@@ -0,0 +1,2 @@
1
+ fileFormatVersion: 2
2
+ guid: 50b6dc920b3b4d8944bb7c766a5f4b62
@@ -17,7 +17,7 @@ namespace XD.SDK.Account
17
17
  {
18
18
  #if UNITY_IOS || UNITY_ANDROID
19
19
  _platformWrapper = XD.SDK.Account.Internal.Mobile.AccountFeaturesImpl.Instance;
20
- #elif UNITY_STANDALONE
20
+ #elif UNITY_STANDALONE || UNITY_EDITOR
21
21
  _platformWrapper = XD.SDK.Account.Internal.Standalone.AccountFeaturesImpl.Instance;
22
22
  #endif
23
23
  if (_platformWrapper == null)
@@ -31,6 +31,17 @@ namespace XD.SDK.Account
31
31
  _platformWrapper.AddUserStatusChangeCallback(callback);
32
32
  }
33
33
 
34
+ internal static void Login(Action<XDGUser> successCallback, Action<XDGError> errorCallback)
35
+ {
36
+ if (_platformWrapper == null)
37
+ {
38
+ errorCallback?.Invoke(new XDGError(ResponseCode.Common.UnavailableService,
39
+ "Login is not supported on this platform."));
40
+ return;
41
+ }
42
+ _platformWrapper.Login(successCallback, errorCallback);
43
+ }
44
+
34
45
  internal static void LoginByType(LoginType loginType, Action<XDGUser> callback, Action<XDGError> errorCallback)
35
46
  {
36
47
  _platformWrapper.LoginByType(loginType, callback, errorCallback);
@@ -32,6 +32,16 @@ namespace XD.SDK.Account
32
32
  XDGAccountInternal.LoginByType(loginType, successCallback, errorCallback);
33
33
  }
34
34
 
35
+ /// <summary>
36
+ /// 开始登录:Web 先尝试 Default,失败后展示登录面板;成功、关闭或致命失败只回调一次。
37
+ /// Windows/macOS 打开内置面板;Android/iOS 通过原生账号桥接执行。
38
+ /// </summary>
39
+ public static void Login(Action<XDGUser> successCallback,
40
+ Action<XDGError> errorCallback)
41
+ {
42
+ XDGAccountInternal.Login(successCallback, errorCallback);
43
+ }
44
+
35
45
  public static void LoginByConsole(Action<XDGUser> successCallback, Action failCallback,
36
46
  Action<XDGError> errorCallback)
37
47
  {
@@ -102,4 +112,4 @@ namespace XD.SDK.Account
102
112
  XDGAccountInternal.BindByType(loginType, callback);
103
113
  }
104
114
  }
105
- }
115
+ }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "com.xd.sdk.account",
3
3
  "displayName": "XDGSDK Account",
4
- "version": "7.9.2",
4
+ "version": "7.10.0-beta.1",
5
5
  "description": "XDGSDK",
6
6
  "unity": "2019.3",
7
7
  "license": "MIT",
8
8
  "dependencies": {
9
- "com.xd.sdk.common": "7.9.2"
9
+ "com.xd.sdk.common": "7.10.0-beta.1"
10
10
  }
11
11
  }