Пример #1
0
        protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync()
        {
            var query  = Request.Query;
            var jsCode = query[Options.WeChatJsCodeQueryString];

            if (string.IsNullOrEmpty(jsCode))
            {
                return(HandleRequestResult.Fail("没有找到客户端所提供的JsCode供微信服务器进行验证。"));
            }

            using var tokens = await ExchangeCodeAsync(jsCode);

            if (tokens.Error != null)
            {
                return(HandleRequestResult.Fail(tokens.Error));
            }

            var completedContext = new WeChatServerCompletedContext(Context, Scheme, Options, tokens.OpenId, tokens.SessionKey, tokens.UnionId, tokens.ErrCode, tokens.ErrMsg);
            await Options.Events?.OnWeChatServerCompleted(completedContext);

            if (string.IsNullOrEmpty(tokens.OpenId) || string.IsNullOrEmpty(tokens.SessionKey))
            {
                return(HandleRequestResult.Fail("没有接收到微信服务器所返回的OpenID和SessionKey。"));
            }

            if (Options.CustomerLoginState == null)
            {
                Logger.LogWarning("当前没有提供微信小程序自定义登录态的逻辑。");
            }
            else
            {
                string sessionInfoKey = null;

                if (Options.SaveSessionKeyToCache)
                {
                    var sessionStore = Context.RequestServices.GetService <IWeChatSessionInfoStore>();
                    if (sessionStore != null)
                    {
                        sessionInfoKey = await sessionStore.StoreAsync(new WeChatSessionInfo(tokens.OpenId, tokens.SessionKey), Options);
                    }
                }

                var exceptions = new List <Exception>();
                try
                {
                    var customerLoginStateContext = new CustomerLoginStateContext(Context, Scheme, Options, tokens.OpenId, tokens.SessionKey, tokens.UnionId, tokens.ErrCode, tokens.ErrMsg, sessionInfoKey);
                    await Options.CustomerLoginState?.Invoke(customerLoginStateContext);
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }

                if (exceptions.Count > 0)
                {
                    return(HandleRequestResult.Fail(new AggregateException(exceptions)));
                }
            }

            return(HandleRequestResult.Handle());;
        }
 /// <summary>
 /// 当调用微信服务端进行验证完成后将调用该方法.
 /// </summary>
 public virtual Task WeChatServerCompleted(WeChatServerCompletedContext context) => OnWeChatServerCompleted(context);