示例#1
0
        public async Task <IActionResult> WeChatLogin(AccountWeChatOAuthInfo info, CancellationToken token)
        {
            string appId     = "Todo_AppId";
            string appSecret = "Todo_AppSecret";
            string code      = "Todo_Code";
            string grantType = "authorization_code";

            string url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type={grantType}";

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync(url, token);

                var accessToken = await response.Content.ReadAsAsync <OAuthTokenResponse>(token);

                if (accessToken != null && !string.IsNullOrEmpty(accessToken.AccessToken))
                {
                    var weChatAccountEntity = await this.Database.WeChatAccounts.GetSingleAsync(a => a.OpenId == accessToken.OpenId, token);

                    if (weChatAccountEntity == null)
                    {
                        weChatAccountEntity = new WeChatAccountEntity()
                        {
                            AccountId = info.AccountId,
                            AppId     = info.AppId,
                            OpenId    = accessToken.OpenId,
                            UnionId   = accessToken.UnionId
                        };
                        await this.Database.WeChatAccounts.InsertAsync(weChatAccountEntity, token);

                        var accountEntity = new AccountEntity()
                        {
                            Id            = Guid.NewGuid().ToString(),
                            AccountName   = Guid.NewGuid().ToString(),
                            AccountType   = AccountType.Guest,
                            AccountStatus = AccountStatus.Active,
                            Token         = EncryptHashManager.GenerateToken()
                        };
                        await this.Database.Accounts.InsertAsync(accountEntity, token);

                        return(this.CreateSuccessResult(accountEntity));
                    }
                    else
                    {
                        var accountEntity = await this.Database.Accounts.GetSingleAsync(a => a.Id == weChatAccountEntity.AccountId, token);
                        await AccountLoginAsync(accountEntity, token);

                        return(this.CreateSuccessResult(accountEntity));
                    }
                }
                throw new UCenterException(UCenterErrorCode.AccountOAuthTokenUnauthorized, "OAuth Token Unauthorized");
            }
        }
        //-------------------------------------------------------------------------
        public void wechatLogin(AccountWeChatOAuthInfo request, OnUCenterLogin handler)
        {
            if (WWWWechatLogin != null)
            {
                return;
            }

            WechatLoginHandler = new Action <UCenterResponseStatus, AccountLoginResponse, UCenterError>(handler);

            string http_url = _genUrl("wechatlogin");

            string param = EbTool.jsonSerialize(request);

            byte[] bytes = Encoding.UTF8.GetBytes(param);

            Dictionary <string, string> headers = _genHeader(bytes.Length);

            WWWWechatLogin = new WWW(http_url, bytes, headers);
        }
        public async Task <IActionResult> WeChatLogin([FromBody] AccountWeChatOAuthInfo info, CancellationToken token)
        {
            // info.AppId目前传值不正确,应等于settings.WechatAppId
            // 后续应当根据info.AppId去查找对应WechatAppSecret
            logger.LogInformation("WeChatLogin AppId=" + info.AppId);
            logger.LogInformation("WeChatLogin AppId=" + settings.WechatAppId);
            logger.LogInformation("WeChatLogin Code=" + info.Code);

            OAuthAccessTokenResult access_token_result = null;

            try
            {
                access_token_result = await OAuthApi.GetAccessTokenAsync(
                    settings.WechatAppId, settings.WechatAppSecret, info.Code);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());

                throw new UCenterException(UCenterErrorCode.AccountOAuthTokenUnauthorized);
            }

            if (access_token_result == null ||
                access_token_result.errcode != 0)
            {
                logger.LogError("GetAccessTokenAsync失败");

                throw new UCenterException(UCenterErrorCode.AccountOAuthTokenUnauthorized);
            }

            OAuthUserInfo user_info = null;

            try
            {
                user_info = await OAuthApi.GetUserInfoAsync(
                    access_token_result.access_token, access_token_result.openid);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());

                throw new UCenterException(UCenterErrorCode.AccountOAuthTokenUnauthorized);
            }

            if (user_info == null)
            {
                logger.LogError("OAuthUserInfo为空");

                throw new UCenterException(UCenterErrorCode.AccountOAuthTokenUnauthorized);
            }

            logger.LogInformation("OpenId=" + user_info.openid);
            logger.LogInformation("NickName=" + user_info.nickname);
            logger.LogInformation("Sex=" + user_info.sex);
            logger.LogInformation("Province=" + user_info.province);
            logger.LogInformation("City=" + user_info.city);
            logger.LogInformation("Country=" + user_info.country);
            logger.LogInformation("Headimgurl=" + user_info.headimgurl);
            logger.LogInformation("Unionid=" + user_info.unionid);
            if (user_info.privilege != null)
            {
                foreach (var i in user_info.privilege)
                {
                    if (i != null)
                    {
                        logger.LogInformation("Privilege=" + i);
                    }
                }
            }

            bool need_update_nickname = false;
            bool need_update_icon     = false;

            // 查找AccountWechat
            var acc_wechat = await this.Database.AccountWechat.GetSingleAsync(
                a => a.Unionid == user_info.unionid &&
                a.OpenId == user_info.openid &&
                a.AppId == settings.WechatAppId,
                token);

            // 创建AccountWechat
            if (acc_wechat == null)
            {
                acc_wechat = new AccountWechatEntity()
                {
                    Id         = Guid.NewGuid().ToString(),
                    AccountId  = Guid.NewGuid().ToString(),
                    Unionid    = user_info.unionid,
                    OpenId     = user_info.openid,
                    AppId      = settings.WechatAppId,
                    NickName   = user_info.nickname,
                    Gender     = (Gender)user_info.sex,
                    Province   = user_info.province,
                    City       = user_info.city,
                    Country    = user_info.country,
                    Headimgurl = user_info.headimgurl
                };

                await this.Database.AccountWechat.InsertAsync(acc_wechat, token);

                need_update_nickname = true;
                need_update_icon     = true;
            }
            else
            {
                if (acc_wechat.Headimgurl != user_info.headimgurl)
                {
                    acc_wechat.Headimgurl = user_info.headimgurl;
                    need_update_icon      = true;
                }

                if (acc_wechat.NickName != user_info.nickname)
                {
                    acc_wechat.NickName  = user_info.nickname;
                    need_update_nickname = true;
                }

                if (need_update_icon || need_update_nickname)
                {
                    await this.Database.AccountWechat.UpsertAsync(acc_wechat, token);
                }
            }

            // 查找Account
            var acc = await this.Database.Accounts.GetSingleAsync(
                acc_wechat.AccountId, token);

            // 创建Account
            if (acc == null)
            {
                acc = new AccountEntity()
                {
                    Id            = acc_wechat.AccountId,
                    AccountName   = Guid.NewGuid().ToString(),
                    AccountType   = AccountType.NormalAccount,
                    AccountStatus = AccountStatus.Active,
                    //Password = EncryptHelper.ComputeHash(info.Password),
                    //SuperPassword = EncryptHelper.ComputeHash(info.SuperPassword),
                    Token    = EncryptHashManager.GenerateToken(),
                    Gender   = acc_wechat.Gender,
                    Identity = string.Empty,
                    Phone    = string.Empty,
                    Email    = string.Empty
                };

                await this.Database.Accounts.InsertAsync(acc, token);

                need_update_nickname = true;
                need_update_icon     = true;
            }

            // 微信头像覆盖Acc头像
            if (need_update_icon &&
                !string.IsNullOrEmpty(user_info.headimgurl))
            {
                //logger.LogInformation("微信头像覆盖Acc头像,Headimgurl={0}", acc_wechat.Headimgurl);

                await DownloadWechatHeadIcon(user_info.headimgurl, acc.Id, token);

                acc.ProfileImage = user_info.headimgurl;
                await this.Database.Accounts.UpsertAsync(acc, token);
            }

            string current_nickname = string.Empty;
            var    app          = UCenterContext.Instance.CacheAppEntity.GetAppEntityByWechatAppId(settings.WechatAppId);
            var    data_id      = $"{app.Id}_{acc.Id}";
            var    account_data = await this.Database.AppAccountDatas.GetSingleAsync(data_id, token);

            if (account_data != null)
            {
                var m = JsonConvert.DeserializeObject <Dictionary <string, string> >(account_data.Data);
                if (m.ContainsKey("nick_name"))
                {
                    current_nickname = m["nick_name"];
                }

                // 微信昵称覆盖Acc昵称
                if (current_nickname != acc_wechat.NickName && !string.IsNullOrEmpty(acc_wechat.NickName))
                {
                    m["nick_name"]    = acc_wechat.NickName;
                    account_data.Data = JsonConvert.SerializeObject(m);

                    await this.Database.AppAccountDatas.UpsertAsync(account_data, token);
                }
            }
            else
            {
                Dictionary <string, string> m = new Dictionary <string, string>();
                m["nick_name"] = acc_wechat.NickName;

                account_data = new AppAccountDataEntity
                {
                    Id        = data_id,
                    AppId     = app.Id,
                    AccountId = acc.Id,
                    Data      = JsonConvert.SerializeObject(m)
                };

                await this.Database.AppAccountDatas.UpsertAsync(account_data, token);
            }

            return(this.CreateSuccessResult(this.ToResponse <AccountLoginResponse>(acc)));
        }