Beispiel #1
0
        private bool WXCallbackAction(HttpContext context)
        {
            ZentCloud.BLLJIMP.Model.Other.WxAutoLoginToken wxAutoLoginToken = new ZentCloud.BLLJIMP.Model.Other.WxAutoLoginToken()
            {
                IsUAuth = 0
            };
            ToLog("callback处理");
            //接收微信授权返回参数
            string code  = context.Request["code"];
            string appId = context.Request["appid"]; //授权给开放平台时返回此参数 默认授权无此参数
            string state = context.Request["state"]; //state 原样返回

            // state = HttpUtility.UrlDecode(state);//state
            ToLog(" into module /wxcallback.aspx code: " + code);
            string redirectUrl = state;//授权完成跳转的链接

            ToLog(" state: " + state);
            try
            {
                redirectUrl = RedisHelper.RedisHelper.StringGet(state);//默认用Redis
            }
            catch (Exception)
            {
                redirectUrl = ZentCloud.Common.DataCache.GetCache(state).ToString();//通过state的cachekey读取链接
            }
            ToLog(" redirectUrl: " + redirectUrl);

            //if (context.Session["redirectUrl"] != null)
            //{
            //    redirectUrl = context.Session["redirectUrl"].ToString();//默认授权用
            //}
            //else
            //{
            //    ToLog("context.Session[redirectUrl] is null");
            //    return;
            //}
            //如果传入code为空,跳过处理
            if (string.IsNullOrWhiteSpace(code))
            {
                ToLog("context.Request[code] is null");
                return(false);
            }
            string getAccessTokenUrl = "";

            ToLog("appid:" + appId);
            if (!string.IsNullOrEmpty(appId))
            {
                isAuthToOpen = true;
            }
            else
            {
                isAuthToOpen            = false;
                currentWebsiteInfo      = bllUser.GetWebsiteInfoModelFromDataBase(); //当前站点信息
                currentWebsiteOwnerInfo = bllUser.GetCurrWebSiteUserInfo();          //当前站点所有者信息
                ToLog("currentWebsiteOwnerInfo" + currentWebsiteOwnerInfo.UserID);
                weixinAppId = currentWebsiteOwnerInfo.WeixinAppId;
                ToLog("weixinAppId" + weixinAppId);
                weixinAppSecret = currentWebsiteOwnerInfo.WeixinAppSecret;
                ToLog("weixinAppSecret" + weixinAppSecret);
            }

            #region 默认授权
            if (!isAuthToOpen)//默认授权
            {
                getAccessTokenUrl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
                                                  weixinAppId,
                                                  weixinAppSecret,
                                                  code);
            }
            #endregion

            #region 开放平台授权
            else
            {
                //todo:
                currentWebsiteInfo      = bllUser.Get <ZentCloud.BLLJIMP.Model.WebsiteInfo>(string.Format(" AuthorizerAppId='{0}'", appId));
                currentWebsiteOwnerInfo = bllUser.GetUserInfo(currentWebsiteInfo.WebsiteOwner, currentWebsiteInfo.WebsiteOwner);

                //开放平台多两个参数  component_appid,component_access_token
                getAccessTokenUrl =
                    string.Format("https://api.weixin.qq.com/sns/oauth2/component/access_token?appid={0}&code={1}&grant_type=authorization_code&component_appid={2}&component_access_token={3}",
                                  appId,
                                  code,
                                  bllWeixinOpen.ComponentAppId, bllWeixinOpen.GetComponentAccessToken());
            }
            #endregion
            ToLog("tokenmodel:" + getAccessTokenUrl);

            //获取OpenID及Access_token
            string accessTokenSource = ZentCloud.Common.MySpider.GetPageSourceForUTF8(getAccessTokenUrl);
            if (string.IsNullOrWhiteSpace(accessTokenSource))
            {
                ToLog("ZentCloud.Common.MySpider.GetPageSourceForUTF8(getTokenUrl) is null");
                context.Response.Redirect(redirectUrl);
                return(false);
            }
            ToLog("accessTokenSource:" + accessTokenSource);

            WXOAuthAccessTokenEntity accessTokenModel = ZCJson.JsonConvert.DeserializeObject <WXOAuthAccessTokenEntity>(accessTokenSource);

            ToLog("start accessTokenSource process");

            if (accessTokenModel == null)
            {
                ToLog("ZCJson.JsonConvert.DeserializeObject<WXOAuthAccessTokenEntity>(accessTokenSource) is null");
                context.Response.Redirect(redirectUrl);
                return(false);
            }
            if (string.IsNullOrEmpty(accessTokenModel.OpenId))
            {
                ToLog("accessTokenModel.OpenId is null");
                context.Response.Redirect(redirectUrl);
                return(false);
            }
            else
            {
                context.Session["currWXOpenId"] = accessTokenModel.OpenId;
                ToLog("currWXOpenId:" + context.Session["currWXOpenId"].ToString());
            }
            if (accessTokenModel.Scope.Contains("snsapi_userinfo"))
            {
                ToLog("获取用户头像昵称 start ");
                string wxUserInfoSourceJson = ZentCloud.Common.MySpider.GetPageSourceForUTF8(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}",
                                                                                                           accessTokenModel.AccessToken,
                                                                                                           accessTokenModel.OpenId
                                                                                                           ));
                ZentCloud.BLLJIMP.Model.Weixin.WeixinUserInfo wxUserInfo = ZCJson.JsonConvert.DeserializeObject <ZentCloud.BLLJIMP.Model.Weixin.WeixinUserInfo>(wxUserInfoSourceJson);
                accessTokenModel.UnionId = wxUserInfo.UnionID;
                wxAutoLoginToken.IsUAuth = 1;
            }
            if (string.IsNullOrEmpty(appId))//默认授权
            {
                currentUserInfo = bllUser.GetUserInfoByOpenId(accessTokenModel.OpenId);
            }
            else//开放平台
            {
                //var websiteInfo = bllUser.Get<ZentCloud.BLLJIMP.Model.WebsiteInfo>(string.Format(" AuthorizerAppId='{0}'", appId));
                currentUserInfo = bllUser.GetUserInfoByOpenId(accessTokenModel.OpenId, currentWebsiteInfo.WebsiteOwner);
            }
            if (currentUserInfo == null && !string.IsNullOrWhiteSpace(accessTokenModel.UnionId))
            {
                currentUserInfo = bllUser.GetUserInfoByWXUnionID(accessTokenModel.UnionId);
            }
            if (currentUserInfo == null)
            {
                //判断当前站点是否不允许微信自动注册新用户
                if (!CheckNotAutoRegNewWxUser(context, redirectUrl))
                {
                    ToLog("不自动注册:" + accessTokenModel.OpenId);
                    //context.Response.Redirect(redirectUrl);
                    //if (!isAuthToOpen)//默认授权
                    //{

                    //}
                    //else//微信开放平台授权
                    //{
                    //    string signKey = ZentCloud.Common.ConfigHelper.GetConfigString("WeixinOpenWebOAuthKey");// 开放平台网页授权Md5 Key
                    //    string sign = ZentCloud.Common.DEncrypt.GetMD5(currentUserInfo.WXOpenId + signKey);//签名
                    //    //开放平台授权,跳到统一处理Handler
                    context.Response.Redirect(string.Format("http://{0}/WeixinOpen/WebOAuthNotLogin.ashx?openid={1}&redirecturl={2}", ZentCloud.Common.MyRegex.GetDoMainByUrl(redirectUrl), accessTokenModel.OpenId, HttpUtility.UrlEncode(redirectUrl)));


                    //}
                    return(false);
                }
                else
                {
                    ToLog("自动注册:" + accessTokenModel.OpenId);
                    #region 注册用户
                    //注册用户
                    currentUserInfo              = new ZentCloud.BLLJIMP.Model.UserInfo();
                    currentUserInfo.UserID       = string.Format("WXUser{0}", Guid.NewGuid().ToString());//Guid
                    currentUserInfo.Password     = ZentCloud.Common.Rand.Str_char(12);
                    currentUserInfo.UserType     = 2;
                    currentUserInfo.WebsiteOwner = currentWebsiteOwnerInfo.UserID;
                    //if (isAuthToOpen)//开放平台授权
                    //{
                    //    var websiteInfo = bllUser.Get<ZentCloud.BLLJIMP.Model.WebsiteInfo>(string.Format(" AuthorizerAppId='{0}'", appId));
                    //    currentUserInfo.WebsiteOwner = websiteInfo.WebsiteOwner;

                    //}
                    currentUserInfo.Regtime = DateTime.Now;
                    //currentUserInfo.WXAccessToken = accessTokenModel.AccessToken;
                    //currentUserInfo.WXRefreshToken = accessTokenModel.RefreshToken;
                    currentUserInfo.WXOpenId = accessTokenModel.OpenId;
                    //currentUserInfo.WXScope = accessTokenModel.Scope;
                    currentUserInfo.RegIP           = ZentCloud.Common.MySpider.GetClientIP();
                    currentUserInfo.LastLoginIP     = ZentCloud.Common.MySpider.GetClientIP();
                    currentUserInfo.LastLoginDate   = DateTime.Now;
                    currentUserInfo.LoginTotalCount = 1;
                    currentUserInfo.WXUnionID       = accessTokenModel.UnionId;
                    if (!new BLLCommRelation().ExistRelation(ZentCloud.BLLJIMP.Enums.CommRelationType.WebsiteIsNotAutoRegNewWxUser, currentUserInfo.WebsiteOwner, ""))
                    {
                        ToLog(string.Format("---自动注册,openid:{0},currentWebsiteInfo.WebsiteOwner:{1}", accessTokenModel.OpenId, currentUserInfo.WebsiteOwner));
                        bllUser.Add(currentUserInfo);
                    }
                    #endregion
                }
            }
            if (currentUserInfo != null)
            {
                if ((!string.IsNullOrEmpty(accessTokenModel.UnionId)) && (string.IsNullOrEmpty(currentUserInfo.WXUnionID)))//如果有 UnionId 则更新
                {
                    currentUserInfo.WXUnionID = accessTokenModel.UnionId;
                    bllUser.Update(currentUserInfo, string.Format("WXUnionID='{0}'", currentUserInfo.WXUnionID), string.Format(" UserId='{0}' ", currentUserInfo.UserID));
                }
                if ((!string.IsNullOrEmpty(accessTokenModel.OpenId)) && (string.IsNullOrEmpty(currentUserInfo.WXOpenId)))
                {
                    currentUserInfo.WXOpenId = accessTokenModel.OpenId;
                    bllUser.Update(currentUserInfo, string.Format("WXOpenId='{0}'", currentUserInfo.WXOpenId), string.Format(" UserId='{0}' ", currentUserInfo.UserID));
                }
            }

            ToLog("用户名:" + currentUserInfo.UserID + "WebsiteOwner=" + currentWebsiteOwnerInfo.UserID);

            // if (!BLL.GetCheck()) return false;

            #region 获取用户头像昵称
            if (accessTokenModel.Scope.Contains("snsapi_userinfo"))
            {
                ToLog("获取用户头像昵称 start ");
                string wxUserInfoSourceJson = ZentCloud.Common.MySpider.GetPageSourceForUTF8(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}",
                                                                                                           accessTokenModel.AccessToken,
                                                                                                           accessTokenModel.OpenId
                                                                                                           ));

                ToLog("wxUserInfoSourceJson:" + wxUserInfoSourceJson);
                if (!string.IsNullOrWhiteSpace(wxUserInfoSourceJson))
                {
                    ZentCloud.BLLJIMP.Model.Weixin.WeixinUserInfo wxUserInfo = ZCJson.JsonConvert.DeserializeObject <ZentCloud.BLLJIMP.Model.Weixin.WeixinUserInfo>(wxUserInfoSourceJson);
                    //context.Session["currWeixinUserInfo"] = wxUserInfo;
                    if (currentUserInfo != null)
                    {
                        //ToLog("处理下,头像都取132的");
                        //if (wxUserInfo.HeadImgUrl.EndsWith("/0"))
                        //{
                        //    ToLog(wxUserInfo.HeadImgUrl);
                        //    wxUserInfo.HeadImgUrl = wxUserInfo.HeadImgUrl.Substring(0, wxUserInfo.HeadImgUrl.Length - 2);
                        //    ToLog(wxUserInfo.HeadImgUrl);
                        //    wxUserInfo.HeadImgUrl += "/132";
                        //    ToLog(wxUserInfo.HeadImgUrl);
                        //}

                        if (string.IsNullOrWhiteSpace(wxUserInfo.NickName))
                        {
                            //context.Response.Redirect(redirectUrl);//高级授权没拿到头像,重新授权
                        }
                        //else
                        //{

                        //}


                        ToLog("开始更新用户微信信息");

                        //更新用户微信信息
                        currentUserInfo.WXCity       = wxUserInfo.City;
                        currentUserInfo.WXCountry    = wxUserInfo.Country;
                        currentUserInfo.WXHeadimgurl = wxUserInfo.HeadImgUrl;
                        currentUserInfo.WXNickname   = wxUserInfo.NickName;
                        currentUserInfo.WXPrivilege  = ZentCloud.Common.JSONHelper.ObjectToJson(wxUserInfo.Privilege);
                        currentUserInfo.WXProvince   = wxUserInfo.Province;
                        currentUserInfo.WXSex        = wxUserInfo.Sex;

                        ToLog("数据库用户AutoId:" + currentUserInfo.AutoID);
                        ToLog("数据库用户信息:" + JsonConvert.SerializeObject(currentUserInfo));
                        ToLog("微信头像 wxUserInfo.HeadImgUrl:" + wxUserInfo.HeadImgUrl);

                        var updateResult = bllUser.Update(currentUserInfo, string.Format(" WXHeadimgurl='{0}',WXNickname='{1}',WXProvince='{2}',WXCity='{3}'", wxUserInfo.HeadImgUrl, wxUserInfo.NickName.Replace("'", ""), wxUserInfo.Province.Replace("'", ""), wxUserInfo.City.Replace("'", "")), string.Format(" UserId='{0}' ", currentUserInfo.UserID));

                        //currentUserInfo.Province

                        ToLog("更新结果:" + updateResult.ToString());
                    }
                }
                else
                {
                    ToLog("WxUserInfoSource is null");
                }
            }
            #endregion

            ToLog("登陆成功,设置session和跳转");
            ToLog("isAuthToOpen:" + isAuthToOpen);
            //ToLog("有无redirectUrl的session:" + (context.Session["redirectUrl"] != null));
            //if (context.Session["redirectUrl"] != null)
            //{
            //    ToLog("redirectUrl:" + context.Session["redirectUrl"].ToString());
            //}

            wxAutoLoginToken.Uid     = currentUserInfo.UserID;
            wxAutoLoginToken.Oid     = currentUserInfo.WXOpenId;
            wxAutoLoginToken.IsUAuth = string.IsNullOrWhiteSpace(currentUserInfo.WXNickname) ? 0 : 1;

            //创建key 存入redis
            var key = "ltk:" + ZentCloud.Common.DEncrypt.ZCEncrypt(currentUserInfo.UserID);

            //key 加上微信appid
            var wxAppidKey = bllWebSite.GetWebsiteWXAppIdKey(currentWebsiteInfo.WebsiteOwner);

            if (!string.IsNullOrWhiteSpace(wxAppidKey))
            {
                key += wxAppidKey;
            }

            try
            {
                //过滤掉异常,防止redis缓存异常导致授权登陆失败

                ToLog("开始设置自动登陆tiken到redis和cookie,key:" + key);

                HttpCookie cookie = new HttpCookie(ZentCloud.Common.SessionKey.LoginCookie);
                cookie.Value   = key;
                cookie.Expires = DateTime.Now.AddDays(30);
                context.Response.Cookies.Add(cookie);

                ToLog("自动登陆cookie设置成功");
                RedisHelper.RedisHelper.StringSetSerialize(key, wxAutoLoginToken, new TimeSpan(30, 0, 0, 0));
                ToLog("自动登陆Redis设置成功");
            }
            catch (Exception ex)
            {
                ToLog("设置自动登陆tiken到redis和cookie异常:" + ex.Message);
            }

            //redirectUrl 加上一个时间戳



            #region 默认授权
            if (!isAuthToOpen)//默认授权
            {
                //设置用户会话ID
                context.Session[ZentCloud.Common.SessionKey.UserID]     = currentUserInfo.UserID;
                context.Session[ZentCloud.Common.SessionKey.LoginStatu] = 1; //设置登录状态
                context.Session["currWXOpenId"] = accessTokenModel.OpenId;
                context.Response.Redirect(redirectUrl);
                return(false);
            }
            #endregion

            #region 微信开放平台授权
            else
            {
                string signKey = ZentCloud.Common.ConfigHelper.GetConfigString("WeixinOpenWebOAuthKey"); // 开放平台网页授权Md5 Key
                string sign    = ZentCloud.Common.DEncrypt.GetMD5(currentUserInfo.WXOpenId + signKey);   //签名
                //开放平台授权,跳到统一处理Handler
                context.Response.Redirect(string.Format("http://{0}/WeixinOpen/WebOAuth.ashx?openid={1}&redirecturl={2}&sign={3}&websiteowner={4}&autologinkey={5}", ZentCloud.Common.MyRegex.GetDoMainByUrl(redirectUrl), currentUserInfo.WXOpenId, HttpUtility.UrlEncode(redirectUrl), sign, currentUserInfo.WebsiteOwner, HttpUtility.UrlEncode(key)));
                //ZentCloud.BLLJIMP.Model.WeixinOpenOAuthTemp tokenRecord = bllUser.Get<ZentCloud.BLLJIMP.Model.WeixinOpenOAuthTemp>(string.Format(" Token='{0}'", state));
                //if (tokenRecord != null)
                //{
                //    context.Response.Redirect(string.Format("http://{0}/WeixinOpen/WebOAuth.ashx?openid={1}&token={2}&sign={3}", ZentCloud.Common.MyRegex.GetDoMainByUrl(tokenRecord.Url), currentUserInfo.WXOpenId, state, sign));

                //}
                //else
                //{
                //    ToLog("tokenRecord null");
                //}

                return(false);
            }
            #endregion
        }