Esempio n. 1
0
        /// <summary>
        /// 根据微信小程序平台提供的解密算法解密数据,推荐直接使用此方法
        /// </summary>
        /// <param name="loginInfo">登陆信息</param>
        /// <returns>用户信息</returns>
        public WeChatUserInfo Decrypt(WeChatLoginInfo loginInfo)
        {
            if (loginInfo == null)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(loginInfo.code))
            {
                return(null);
            }

            OpenIdAndSessionKey oiask = DecodeOpenIdAndSessionKey(loginInfo);

            if (oiask == null)
            {
                return(null);
            }

            if (!VaildateUserInfo(loginInfo, oiask))
            {
                return(null);
            }

            WeChatUserInfo userInfo = Decrypt(loginInfo.encryptedData, loginInfo.iv, oiask.session_key);

            return(userInfo);
        }
        /// <summary>
        /// 微信开放平台拉取用户信息(需scope为 snsapi_userinfo)
        /// </summary>
        /// <param name="access_token">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>
        /// <param name="openid">用户的唯一标识</param>
        /// <returns></returns>
        public static WeChatUserInfo GetWeChatUserInfo(string access_token, string openid)
        {
            WeChatUserInfo uinfo      = new WeChatUserInfo();
            string         url        = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);
            string         jsonResult = HttpUtils.Ins.GET(url);

            ClassLoger.Info("WeChatAPIHelper.GetWeChatUserInfo", url, jsonResult);
            if (!jsonResult.IsNull())
            {
                if (jsonResult.Contains("errcode"))
                {
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatUserInfo", url);
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatUserInfo", jsonResult);
                }
                else
                {
                    Dictionary <string, object> resultDic = JsonHelper.DeserializeObject(jsonResult);
                    uinfo.city       = resultDic["city"].TryToString();
                    uinfo.country    = resultDic["country"].TryToString();
                    uinfo.headimgurl = resultDic["headimgurl"].TryToString();
                    uinfo.nickname   = resultDic["nickname"].TryToString();
                    uinfo.openid     = resultDic["openid"].TryToString();
                    uinfo.privilege  = resultDic["privilege"].TryToString();
                    uinfo.province   = resultDic["province"].TryToString();
                    uinfo.sex        = resultDic["sex"].TryToInt(0);
                    if (resultDic.ContainsKey("unionid"))
                    {
                        uinfo.unionid = resultDic["unionid"].TryToString();
                    }
                }
            }
            return(uinfo);
        }
Esempio n. 3
0
 /// <summary>
 /// 获取用户信息
 /// </summary>
 /// <returns></returns>
 public static WeChatUserInfo GetUserInfo(string token, string userid)
 {
     try
     {
         Dictionary <string, object> dic = new Dictionary <string, object>
         {
             { "access_token", token },
             { "userid", userid }
         };
         string         resultJson = HttpHelper.GetData(GetUserInfoUrl, dic);
         WeChatUserInfo userIdInfo = resultJson.ToObject <WeChatUserInfo>();
         if (userIdInfo.errcode != "0")
         {
             LogHelper.WriteLog_LocalTxt(resultJson);
             logger?.LogWarning(resultJson);
             return(null);
         }
         return(userIdInfo);
     }
     catch (Exception e)
     {
         LogHelper.WriteLog_LocalTxt(e.Message);
         return(null);
     }
 }
Esempio n. 4
0
        public async Task TimedRefreshDepartment()
        {
            string token = WeChatOperation.GetToken(EnumWeChatAppType.Food);

            if (token == null)
            {
                throw new BusException("获取授权token失败!");
            }
            var query = GetList();

            foreach (var item in query)
            {
                WeChatUserInfo       weChatUserInfo       = WeChatOperation.GetUserInfo(token, item.WeCharUserId);
                WeChatDepartmentList weChatDepartmentList = null;
                string departmentPath = string.Empty;
                string departmentId   = string.Empty;
                string department     = string.Empty;
                if (weChatUserInfo == null)
                {
                    continue;
                }
                //底层部门
                weChatDepartmentList = WeChatOperation.GetDepartment(token, weChatUserInfo.main_department);
                if (weChatDepartmentList == null)
                {
                    continue;
                }
                departmentId   = weChatDepartmentList?.department?.FirstOrDefault()?.parentid;
                departmentPath = weChatDepartmentList?.department?.FirstOrDefault()?.name;
                department     = weChatDepartmentList?.department?.FirstOrDefault()?.name;

                //倒数第二
                weChatDepartmentList = WeChatOperation.GetDepartment(token, departmentId);
                if (weChatDepartmentList == null)
                {
                    continue;
                }
                departmentPath = weChatDepartmentList?.department?.Where(a => a.id == departmentId)?.FirstOrDefault()?.name + "/" + departmentPath;
                departmentId   = weChatDepartmentList?.department?.Where(a => a.id == departmentId)?.FirstOrDefault()
                                 ?.parentid;
                //倒数第三
                weChatDepartmentList = WeChatOperation.GetDepartment(token, departmentId);
                if (weChatDepartmentList == null)
                {
                    continue;
                }
                departmentPath = weChatDepartmentList?.department?.Where(a => a.id == departmentId)?.FirstOrDefault()?.name + "/" + departmentPath;

                item.FullDepartment = departmentPath;
                item.Department     = department;
                item.UpdateTime     = DateTime.Now;
                item.UpdateName     = "Job";
                item.UpdateId       = "Job";
                await Service.UpdateAnyAsync(item,
                                             new List <string>() { "Department", "FullDepartment", "UpdateTime", "UpdateName", "UpdateId" });
            }
        }
Esempio n. 5
0
        public Customer GetUser(WeChatUserInfo userInfo)
        {
            var parameters = new OAuthAuthenticationParameters(Provider.SystemName)
            {
                ExternalIdentifier        = userInfo.openid,
                ExternalDisplayIdentifier = userInfo.unionid,
            };

            return(_openAuthenticationService.GetUser(parameters));
        }
Esempio n. 6
0
        private AuthorizeState VerifyAuthentication(string returnUrl)
        {
            var            returnString = _httpContext.Request.QueryString;
            var            sortedStr    = returnString.AllKeys;
            WeChatUserInfo userInfo     = null;
            SortedDictionary <string, string> sortedDic = new SortedDictionary <string, string>();

            for (int i = 0; i < sortedStr.Length; i++)
            {
                sortedDic.Add(sortedStr[i], returnString[sortedStr[i]]);
            }
            if (sortedDic.Keys.Contains("code"))
            {
                var code = sortedDic["code"];
                userInfo = GetUserInfo(code);
            }
            if (userInfo == null)
            {
                var currentCustomerId = _workContext.CurrentCustomer.Id;
                if (currentCustomerId != 0)
                {
                    var key = string.Format(WEIXIN_USER_CUSTOMERID, currentCustomerId);
                    userInfo = _cacheManager.Get <WeChatUserInfo>(key);
                    _cacheManager.Remove(key);
                }
            }
            var email = _httpContext.Request.Form["Email"]; //获取注册邮箱

            if (userInfo != null)
            {
                var parameters = new OAuthAuthenticationParameters(Provider.SystemName)
                {
                    ExternalIdentifier        = userInfo.openid,
                    ExternalDisplayIdentifier = userInfo.unionid
                };
                // if (_externalAuthenticationSettings.AutoRegisterEnabled)
                ParseClaims(userInfo, parameters, email);
                var result = _authorizer.Authorize(parameters);
                return(new AuthorizeState(returnUrl, result));
            }
            else
            {
                var state = new AuthorizeState(returnUrl, OpenAuthenticationStatus.Error);
                var error = "获取用户信息失败";
                state.AddError(error);
                return(state);
            }
        }
        public async Task <WeChatUserInfo> GetWechatUserId(string code, string token)
        {
            try
            {
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
                httpClient.Timeout = TimeSpan.FromMinutes(3);
                var urlGetUserInfo = $"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={token}&code={code}";
                var ResultUserInfo = await httpClient.GetStringAsync(urlGetUserInfo);

                WeChatUserInfo wXUserInfo = JsonConvert.DeserializeObject <WeChatUserInfo>(ResultUserInfo);
                return(wXUserInfo);
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException("获取微信UserInfo失败" + ex.Message);
            }
        }
Esempio n. 8
0
        public WeChatUserInfo GetUserInfo(string code)
        {
            var accessToken = this.GetAccessToken(code);
            var userInfo    = new WeChatUserInfo();

            if (accessToken != null)
            {
                userInfo = GetUserInfo(accessToken.access_token, accessToken.openid);
                var currentCustomerId = _workContext.CurrentCustomer.Id;
                if (currentCustomerId != 0)
                {
                    var key = string.Format(WEIXIN_USER_CUSTOMERID, currentCustomerId);
                    _cacheManager.Set(key, userInfo, 5); //保存5分钟
                }
                return(userInfo);
            }
            return(null);
        }
Esempio n. 9
0
 public static WxUser CreateWxUser(this WeChatUserInfo userInfo, RegistryTypes type, string appid)
 {
     return(new WxUser()
     {
         AppId = appid,
         AvatarUrl = userInfo.AvatarUrl,
         City = userInfo.City,
         Country = userInfo.Country,
         CreatedTime = DateTime.Now.ToUnixStampDateTime(),
         LastActivityTime = DateTime.Now.ToUnixStampDateTime(),
         Mobile = string.Empty,
         NickName = userInfo.NickName,
         OpenId = userInfo.OpenId,
         Province = userInfo.Province,
         RegistryType = RegistryTypes.Miniprogram,
         UnionId = userInfo.UnionId
     });
 }
Esempio n. 10
0
        protected override void ParseJson()
        {
            if (this.Json == null)
            {
                return;
            }
            if (this.UserInfo == null)
            {
                this.UserInfo = new WeChatUserInfo();
            }
            IDictionary <string, JToken> userAsDictionary = this.Json;

            UserInfo.UnionId  = PropertyValueIfExists("unionid", userAsDictionary);
            UserInfo.Name     = PropertyValueIfExists("nickname", userAsDictionary);
            UserInfo.City     = PropertyValueIfExists("city", userAsDictionary);
            UserInfo.Province = PropertyValueIfExists("province", userAsDictionary);
            UserInfo.Gendar   = PropertyValueIfExists("sex", userAsDictionary) != null?int.Parse(PropertyValueIfExists("sex", userAsDictionary)) : 0;

            UserInfo.Country  = PropertyValueIfExists("country", userAsDictionary);
            UserInfo.AvtorUrl = PropertyValueIfExists("headimgurl", userAsDictionary);
        }
        public override async Task <ExternalAuthUserInfo> GetUserInfo(string Code)
        {
            // 1. 获取企业微信ToKen
            WeChatToken weChatToken = await this.GetWechatToKen();

            // 2. 获取用户信息
            WeChatUserInfo weChatUserInfo = await this.GetWechatUserId(Code, weChatToken.access_token);

            // 3. 通过获取的的微信用户UserId并判断是否存在自己的服务器中。
            WXUser wXUser = await _wXUserManager.FindByUserId(weChatUserInfo.UserId);

            var t = wXUser == null ? new ExternalAuthUserInfo() : new ExternalAuthUserInfo
            {
                EmailAddress = wXUser.Email,
                Surname      = wXUser.AbpUser.Surname,
                ProviderKey  = weChatUserInfo.UserId,
                Provider     = ProviderName,
                Name         = wXUser.AbpUser.Name
            };

            return(t);
        }
Esempio n. 12
0
        private void ParseClaims(WeChatUserInfo userInfo, OAuthAuthenticationParameters parameters
                                 , string email)
        {
            Random random = new Random();
            var    claims = new UserClaims();

            claims.Contact = new ContactClaims()
            {
                Email = email
            };
            claims.Contact.Address = new AddressClaims()
            {
                City    = userInfo.city,
                State   = userInfo.province,
                Country = userInfo.country,
            };
            claims.Name = new NameClaims()
            {
                Nickname = userInfo.nickname,
            };

            parameters.AddClaim(claims);
        }
Esempio n. 13
0
        public string POST(string signature, string token, string timestamp, string nonce, string echostr)
        {
            try
            {
                Stream requestStream = System.Web.HttpContext.Current.Request.InputStream;
                byte[] requestByte   = new byte[requestStream.Length];
                requestStream.Read(requestByte, 0, (int)requestStream.Length);
                string requestStr = Encoding.UTF8.GetString(requestByte);

                ClassLoger.Info("checkWeChatSignatureController接收到的信息:", requestStr);
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(requestStr);

                var msg = WeChatXMLMessageHelper.GetWeChatMsg(xd);
                if (msg != null)
                {
                    WxTextMsg msgs = new WxTextMsg();
                    msgs.ToUserName   = msg.FromUserName;
                    msgs.FromUserName = msg.ToUserName;
                    msgs.CreateTime   = DateTime.Now.Ticks;
                    msgs.MsgType      = "text";
                    //订阅服务号
                    if (msg.Event.Equals(MsgTypeEvent.subscribe))
                    {
                        WeChatUserInfo uinfo  = WeChatUserInfoAPI.GetWeChatUserInfo(msg.FromUserName);
                        WeChatUser     weuser = userbll.GetWeChatUserByUnionID(uinfo.unionid);
                        if (weuser == null)
                        {
                            weuser = new WeChatUser();
                        }
                        weuser.ServiceOpenID = uinfo.openid;
                        weuser.UnionID       = uinfo.unionid;
                        userbll.UpdateWeChatUser(weuser);

                        UserInfo      user       = ubll.GetUserInfoByOpenID(uinfo.unionid);
                        List <string> openIDList = new List <string>(1)
                        {
                            weuser.ServiceOpenID
                        };
                        if (user == null)
                        {
                            user            = new UserInfo();
                            user.Openid     = uinfo.unionid;
                            user.CreateTime = DateTime.Now;
                            user.Headimgurl = uinfo.headimgurl;
                            user.Nickname   = uinfo.nickname;
                            user.Sex        = (SexEnum)uinfo.sex;
                            user.Name       = uinfo.nickname;
                            user.city       = uinfo.city;
                            user.province   = uinfo.province;
                            ubll.UpdateUserinfo(user);
                        }
                        else
                        {
                            if (user.IsAdmin)
                            {
                                WeChatTagsAPI.batchtagging(openIDList, SystemSet.AdminUserTagID);
                            }
                        }
                        msgs.Content = "感谢您关注【....】";
                    }
                    return(XmlEntityExchange <WxTextMsg> .ConvertEntity2Xml(msgs));
                }
            } catch (Exception ex)
            {
                ClassLoger.Error("WeChatSig.POST", ex);
            }
            return(string.Empty);
        }
Esempio n. 14
0
        public async Task <string> Login(string code)
        {
            string token = WeChatOperation.GetToken(EnumWeChatAppType.Food);

            if (token == null)
            {
                throw new BusException("获取授权token失败!");
            }
            string userId = WeChatOperation.GetUserId(code, token);

            if (userId == null)
            {
                throw new BusException("获取授权userId失败");
            }
            //缓存token,不重复获取
            //查询用户信息
            var userInfo = GetIQueryable().Where(a => a.WeCharUserId == userId)?.FirstOrDefault();

            if (userInfo == null || string.IsNullOrEmpty(userInfo.Department))
            {
                WeChatUserInfo       weChatUserInfo       = WeChatOperation.GetUserInfo(token, userId);
                WeChatDepartmentList weChatDepartmentList = null;
                string departmentPath = string.Empty;
                string departmentId   = string.Empty;
                string department     = string.Empty;
                if (weChatUserInfo == null)
                {
                    throw new BusException("获取用户信息失败,登录失败!");
                }
                if (!string.IsNullOrEmpty(weChatUserInfo.main_department))
                {
                    //底层部门
                    weChatDepartmentList = WeChatOperation.GetDepartment(token, weChatUserInfo.main_department);
                    if (weChatDepartmentList != null)
                    {
                        departmentId   = weChatDepartmentList?.department?.FirstOrDefault()?.parentid;
                        departmentPath = weChatDepartmentList?.department?.FirstOrDefault()?.name;
                        department     = weChatDepartmentList?.department?.FirstOrDefault()?.name;
                    }
                    //倒数第二
                    weChatDepartmentList = WeChatOperation.GetDepartment(token, departmentId);
                    if (weChatDepartmentList != null)
                    {
                        departmentPath =
                            weChatDepartmentList?.department?.Where(a => a.id == departmentId)?.FirstOrDefault()?.name +
                            "/" + departmentPath;
                        departmentId = weChatDepartmentList?.department?.Where(a => a.id == departmentId)
                                       ?.FirstOrDefault()
                                       ?.parentid;
                    }
                    //倒数第三
                    weChatDepartmentList = WeChatOperation.GetDepartment(token, departmentId);
                    if (weChatDepartmentList != null)
                    {
                        departmentPath =
                            weChatDepartmentList?.department?.Where(a => a.id == departmentId)?.FirstOrDefault()?.name +
                            "/" + departmentPath;
                    }
                }
                if (userInfo == null)
                {
                    F_UserInfo fUserInfo = new F_UserInfo()
                    {
                        Id             = IdHelper.GetId(),
                        IsAdmin        = false,
                        ShopInfoId     = "",
                        UserName       = weChatUserInfo.name,
                        UserImgUrl     = weChatUserInfo.avatar,
                        WeCharUserId   = weChatUserInfo.userid,
                        Department     = department,
                        FullDepartment = departmentPath,
                        CreateTime     = DateTime.Now,
                        CreatorId      = "system",
                        CreatorName    = weChatUserInfo.name,
                    };
                    await InsertAsync(fUserInfo);
                }
                else if (string.IsNullOrEmpty(userInfo.Department) || string.IsNullOrEmpty(userInfo.FullDepartment))
                {
                    //更新部门//组合倒数第二级部门
                    userInfo.Department     = department;
                    userInfo.FullDepartment = departmentPath;
                    userInfo.UpdateTime     = DateTime.Now;
                    userInfo.UpdateName     = userInfo.UserName;
                    userInfo.UpdateId       = userInfo.UpdateId;
                    await Service.UpdateAnyAsync(userInfo,
                                                 new List <string>() { "Department", "UpdateTime", "UpdateName", "UpdateId" });
                }
            }

            //生成token,有效期一个月
            JWTPayload jWTPayload = new JWTPayload
            {
                UserId = userId,
                Expire = DateTime.Now.AddDays(30),
                AppId  = (int)EnumWeChatAppType.Food
            };
            string tk = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTClient);

            return(tk);
        }
Esempio n. 15
0
        public async Task <IActionResult> PublicAccountCallbackPost([FromQuery] string signature, [FromQuery] string timestamp, [FromQuery] string nonce, [FromQuery] string echostr)
        {
            try
            {
                CheckSignature checkSignature = new CheckSignature(_weChatSettings.Value.token);

                // Check if signature matches
                if (!checkSignature.IsValidSignature(timestamp, nonce, signature))
                {
                    // Unauthorized call
                    _logger.Warn("Unauthroized call!",
                                 Request.HttpContext.Connection.RemoteIpAddress?.ToString(),
                                 $"signature:{signature}, nonce:{nonce}, echostr:{echostr}");
                    return(Unauthorized());
                }


                // Authorized call
                using (var reader = new StreamReader(Request.Body))
                {
                    // Read message
                    var body = await reader.ReadToEndAsync();

                    // log original response
                    _logger.Info(body);

                    var messageXml = Formatting <MessageXml> .XmlToClass(body);


                    // Check access_token
                    if (!_cacheControl.IsCacheExist("access_token"))
                    {
                        // access token is not cached or expired, using wechat API to get a new one, then save it in cache
                        Task <string> taskGetAccessToken = _weChatAPI.GetAccessTokenAsync();
                        taskGetAccessToken.Wait();
                        _accessToken = Formatting <AccessToken> .JsonToClass(taskGetAccessToken.Result).access_token;

                        _cacheControl.SetCache("access_token", _accessToken, 60 * 60);
                    }
                    else
                    {
                        // access token is cached, retrieve it
                        _accessToken = _cacheControl.GetValueBykey("access_token").ToString();
                    }



                    // Different handlers for each type of message
                    if (messageXml.MsgType == "text")
                    {
                        TextMessageXml textMessageXml = Formatting <TextMessageXml> .XmlToClass(body);

                        _logger.Info($"User ({textMessageXml.FromUserName}) post text message {textMessageXml.Content}");



                        // fetch user information
                        // IF username is already existed in somewhere like a local database, then we do not need to get info every time.
                        // But it is a callback so performance wise it does not really matter so much.
                        Task <string> taskGetUserInfo = _weChatAPI.GetSubscriberInfo(_accessToken, textMessageXml.FromUserName);
                        taskGetUserInfo.Wait();
                        WeChatUserInfo weChatUserInfo = Formatting <WeChatUserInfo> .JsonToClass(taskGetUserInfo.Result);


                        // TODO: auto reply
                    }
                    else if (messageXml.MsgType == "voice")
                    {
                        VoiceMessageXml voiceMessageXml = Formatting <VoiceMessageXml> .XmlToClass(body);

                        _logger.Info($"User ({voiceMessageXml.FromUserName}) post voice message {voiceMessageXml.Recognition}. (Media Id:{voiceMessageXml.MediaId}, Format: {voiceMessageXml.Format})");
                    }
                    else if (messageXml.MsgType == "image")
                    {
                        ImageMessageXml imageMessageXml = Formatting <ImageMessageXml> .XmlToClass(body);

                        _logger.Info($"User ({imageMessageXml.FromUserName}) post image {imageMessageXml.PicUrl}. (Media Id:{imageMessageXml.MediaId})");
                    }
                }
                return(Ok(echostr));
            }
            catch (Exception e)
            {
                _logger.Error("************");
                _logger.Error(e.ToString());
                _logger.Error("************");
                return(Ok(echostr));
            }
        }
Esempio n. 16
0
 public async Task <MessageModel <WeChatResponseUserInfo> > UnBind([FromQuery] WeChatUserInfo info)
 {
     return(await _weChatConfigServices.UnBind(info));
 }
Esempio n. 17
0
        public ActionResult CallBackRedirect()
        {
            //网络授权有有效期,最好用redis缓存
            //获取用户网络授权
            string code  = Request["code"].TryToString();
            string state = Request["state"].TryToString();

            ClassLoger.Info("WeixinRedirectController.CallBackRedirect", state, code);
            string access_token = string.Empty;
            string openid       = string.Empty;

            if (RedisBase.ContainsKey(code))
            {
                Access_tokenResult accResult = RedisBase.Item_Get <Access_tokenResult>(code);
                access_token = accResult.access_token;
                openid       = accResult.openid;
            }
            else
            {
                Access_tokenResult accResult = WeChatAccessTokenAPI.GetWeChatServiceAccess_token(code);
                RedisBase.Item_Set(code, accResult);
                RedisBase.ExpireEntryAt(code, DateTime.Now.AddSeconds(accResult.expires_in));
                access_token = accResult.access_token;
                openid       = accResult.openid;
            }

            //获取用户信息
            WeChatUserInfo userinfo = null;
            string         userkey  = getWeChatUserKey(access_token, openid);

            if (RedisBase.ContainsKey(userkey))
            {
                userinfo = RedisBase.Item_Get <WeChatUserInfo>(userkey);
            }
            else
            {
                userinfo = WeChatUserInfoAPI.GetWeChatUserInfo(access_token, openid);
                if (userinfo != null)
                {
                    RedisBase.Item_Set(userkey, userinfo);
                    RedisBase.ExpireEntryAt(userkey, DateTime.Now.AddDays(2));
                }
            }
            UserInfo _user = userbll.GetUserInfoByOpenID(userinfo.unionid);

            if (_user == null)
            {
                _user            = new UserInfo();
                _user.Openid     = userinfo.unionid;
                _user.CreateTime = DateTime.Now;
                _user.Headimgurl = userinfo.headimgurl;
                _user.Nickname   = userinfo.nickname;
                _user.Sex        = (SexEnum)userinfo.sex;
                _user.Name       = userinfo.nickname;
                _user.city       = userinfo.city;
                _user.province   = userinfo.province;
                userbll.UpdateUserinfo(_user);
            }
            ClassLoger.Info("CallBackRedirect", userkey);
            RedisSession <UserInfo> redissession = new Models.RedisSession <UserInfo>(HttpContext, true, 120);

            redissession["UserCode"] = _user;
            switch (state)
            {
            //普通用户个人中心
            case "UserCore":
                return(RedirectToAction("Index", "UserCore"));

            case "AdminCore":
            //return RedirectToAction("Index", "AdminCore");
            default:
                string url = HttpUtils.Ins.UrlDecode(state);
                if (RedisBase.ContainsKey(state))
                {
                    url = RedisBase.Item_Get <string>(state);
                }
                return(Redirect(url));
            }
        }
Esempio n. 18
0
        public int AddWeChatUser(WeChatUserInfo info)
        {
            var user  = UserRepository.GetUserByOpenId(info.openid);
            var isAdd = user == null;

            var subscribed = info.subscribe.HasValue ?
                             (YesNo)Enum.Parse(typeof(YesNo), info.subscribe.Value.ToString()) :
                             (user != null && user.SUBSCRIBED == YesNo.Y.ToString() ? YesNo.Y : YesNo.N);

            if (isAdd)
            {
                var rolePrivilege = UserRepository.GetRolePrivilege(UserRoles.USER.ToString());
                user = new DUOJU_USERS
                {
                    ACCOUNT = string.Format(CommonSettings.USERACCOUNT_WECHAT_FORMAT, info.openid),
                    SOURCE  = (int)UserSources.WECHAT,
                    DUOJU_ROLE_PRIVILEGES = rolePrivilege,
                    PRIVILEGES            = rolePrivilege.PRIVILEGES,
                    OPEN_ID     = info.openid,
                    CREATE_BY   = CommonSettings.OPERATOR_SYSTEM_ID,
                    CREATE_TIME = DateTime.Now
                };
            }

            user.SUBSCRIBED = subscribed.ToString();
            if (subscribed == YesNo.Y)
            {
                if (info.subscribe_time.HasValue)
                {
                    user.SUBSCRIBE_TIME = WeChat.ConvertDateTime(info.subscribe_time.Value);
                }
                user.NICK_NAME = info.nickname;
                if (info.sex.HasValue)
                {
                    user.SEX = ((UserSexes)Enum.Parse(typeof(UserSexes), info.sex.Value.ToString())).ToString();
                }
                user.HEAD_IMG_URL = info.headimgurl;
                if (!string.IsNullOrEmpty(info.country))
                {
                    var country = AreaRepository.GetCountryInfoByName(info.country);
                    if (country != null)
                    {
                        user.DUOJU_COUNTRIES = country;
                    }
                }
                if (!string.IsNullOrEmpty(info.province))
                {
                    var province = AreaRepository.GetProvinceInfoByName(info.province);
                    if (province != null)
                    {
                        user.DUOJU_PROVINCES = province;
                    }
                }
                if (!string.IsNullOrEmpty(info.city))
                {
                    var city = AreaRepository.GetCityInfoByName(info.city);
                    if (city != null)
                    {
                        user.DUOJU_CITIES = city;
                    }
                }
            }
            user.ENABLED          = YesNo.Y.ToString();
            user.LAST_UPDATE_BY   = CommonSettings.OPERATOR_SYSTEM_ID;
            user.LAST_UPDATE_TIME = DateTime.Now;

            if (isAdd)
            {
                user.DUOJU_USER_FINANCES.Add(new DUOJU_USER_FINANCES
                {
                    COIN_COUNT       = CommonSettings.USERREGISTER_DEFAULT_COIN_COUNT,
                    CREATE_BY        = CommonSettings.OPERATOR_SYSTEM_ID,
                    CREATE_TIME      = DateTime.Now,
                    LAST_UPDATE_BY   = CommonSettings.OPERATOR_SYSTEM_ID,
                    LAST_UPDATE_TIME = DateTime.Now
                });

                UserRepository.AddUser(user);
            }
            UserRepository.SaveChanges();

            return(user.USER_ID);
        }
        /// <summary>
        /// 用户确认授权
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        private void getUserinfo(string code, string state)
        {
            try
            {
                //网络授权有有效期,最好用redis缓存
                //获取用户网络授权

                string access_token = string.Empty;
                string openid       = string.Empty;
                if (RedisBase.ContainsKey(code))
                {
                    Access_tokenResult accResult = RedisBase.Item_Get <Access_tokenResult>(code);
                    access_token = accResult.access_token;
                    openid       = accResult.openid;
                }
                else
                {
                    Access_tokenResult accResult = WeChatAccessTokenAPI.GetWeChatAccess_token(code);
                    RedisBase.Item_Set(code, accResult);
                    RedisBase.ExpireEntryAt(code, DateTime.Now.AddSeconds(accResult.expires_in));
                    access_token = accResult.access_token;
                    openid       = accResult.openid;
                }

                //获取用户信息
                WeChatUserInfo userinfo = null;
                string         userkey  = getWeChatUserKey(access_token, openid);
                if (RedisBase.ContainsKey(userkey))
                {
                    userinfo = RedisBase.Item_Get <WeChatUserInfo>(userkey);
                }
                else
                {
                    userinfo = WeChatUserInfoAPI.GetWeChatUserInfo(access_token, openid);
                    if (userinfo != null)
                    {
                        RedisBase.Item_Set(userkey, userinfo);
                        RedisBase.ExpireEntryAt(userkey, DateTime.Now.AddDays(2));
                    }
                }
                WeChatUser wuser = userbll.GetWeChatUserByUnionID(userinfo.unionid);
                if (wuser == null)
                {
                    wuser = new WeChatUser();
                    wuser.PlatformOpenID = userinfo.openid;
                    wuser.UnionID        = userinfo.unionid;
                    userbll.AddWeChatUser(wuser);
                }
                else
                {
                    if (string.IsNullOrEmpty(wuser.PlatformOpenID))
                    {
                        wuser.PlatformOpenID = userinfo.openid;
                        wuser.UnionID        = userinfo.unionid;
                        userbll.UpdateWeChatUser(wuser);
                    }
                }
                UserInfoBll ubll  = new UserInfoBll();
                UserInfo    _user = ubll.GetUserInfoByOpenID(userinfo.unionid);
                // 用户绑定微信
                string bindkey = string.Format("bind_{0}", state);
                string msg     = MqttAgreement.GetWeChatLoginMA(state, true);
                if (RedisBase.ContainsKey(bindkey))
                {
                    //用户之前已经关注过微信公共号,需要把之前微信公共号账户中的信息更新到这个账户中
                    if (_user != null)
                    {
                        _user.Openid = "";
                        ubll.UpdateUserinfo(_user);
                    }
                    UserInfo binduser = RedisBase.Item_Get <UserInfo>(bindkey);
                    binduser.Openid = userinfo.unionid;
                    ubll.UpdateUserinfo(binduser);
                }
                else
                {
                    WeChatLogin login = loginbll.GetWeChatLoginByUUID(state);
                    if (login == null)
                    {
                        login            = new WeChatLogin();
                        login.UUID       = state;
                        login.CreateTime = DateTime.Now;
                        login.LoginData  = DateTime.Now.ToString("yyyy-MM-dd");
                    }
                    login.Headimgurl = userinfo.headimgurl;
                    login.Nickname   = userinfo.nickname;
                    login.Openid     = userinfo.unionid;
                    login.Sex        = userinfo.sex.TryToString();
                    login.State      = 1;
                    login.LoginData  = DateTime.Now.ToString("yyyy-MM-dd");
                    login.CreateTime = DateTime.Now;
                    loginbll.UpdateWeChatLogin(login);

                    if (_user == null)
                    {
                        _user            = new UserInfo();
                        _user.Openid     = userinfo.unionid;
                        _user.CreateTime = DateTime.Now;
                        _user.Headimgurl = userinfo.headimgurl;
                        _user.Nickname   = userinfo.nickname;
                        _user.Sex        = (SexEnum)userinfo.sex;
                        _user.Name       = userinfo.nickname;
                        _user.city       = userinfo.city;
                        _user.province   = userinfo.province;
                        ubll.UpdateUserinfo(_user);
                    }
                    //向客户端推送消息
                    MqttPublishClient.Ins.PublishOneClient(login.LockCode, msg);
                }
                MqttPublishClient.Ins.PublishAllClient(msg);
            }
            catch (Exception ex)
            {
                ClassLoger.Error("WeChatLoginCallBackController.getUserinfo", ex);
            }
        }