Esempio n. 1
0
        /// <summary>
        /// 授权作用于平台用户登录(openId直接为平台登录用户)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_AcquireRequestStateForOpenIdLogin(object sender, EventArgs e)
        {
            try
            {
                HttpContext context = HttpContext.Current;
                ZentCloud.BLLJIMP.BLLUser userBll = new ZentCloud.BLLJIMP.BLLUser("");
                SystemSet systemSet = userBll.Get <SystemSet>("");
                ZentCloud.BLLJIMP.Model.WebsiteInfo currWebsiteInfoModel = (ZentCloud.BLLJIMP.Model.WebsiteInfo)context.Session["WebsiteInfoModel"];
                ZentCloud.BLLJIMP.Model.UserInfo    currWebsiteOwner     = userBll.GetUserInfo(currWebsiteInfoModel.WebsiteOwner);
                string currPath = context.Request.Path.ToLower();
                if (!context.Request.UserAgent.ToLower().Contains("micromessenger"))
                {
                    return;//非微信浏览器进入不执行授权
                }
                //验证aspx、ashx、chtml页面
                if (!ZentCloud.Common.IOHelper.GetExtraName(currPath).Equals("aspx") && !ZentCloud.Common.IOHelper.GetExtraName(currPath).Equals("chtml") && !ZentCloud.Common.IOHelper.GetExtraName(currPath).Equals("ashx"))
                {
                    return;
                }

                ZentCloud.BLLJIMP.Model.UserInfo userInfo = new ZentCloud.BLLJIMP.Model.UserInfo();
                string WeixinAppId     = currWebsiteOwner.WeixinAppId;
                string WeixinAppSecret = currWebsiteOwner.WeixinAppSecret;
                if (!currWebsiteOwner.WeixinIsAdvancedAuthenticate.Equals(1))//未开通微信高级认证的不处理
                {
                    return;
                }
                #region CallBack处理阶段
                //ToLog("判断是不是callback");
                if (currPath.StartsWith("/wxcallback.aspx"))
                {
                    //ToLog("正在处理callback");
                    //接收Code及state
                    string code  = context.Request["code"];
                    string state = context.Session["state"].ToString(); //context.Request["state"];//如果state太长微信的userInfo会报错,解决方案为将改字段放到session里可以了
                    WXOAuthCallBackStateEntity callBackStateInfo = new WXOAuthCallBackStateEntity();
                    if (!string.IsNullOrWhiteSpace(state))
                    {
                        callBackStateInfo = ZentCloud.Common.JSONHelper.JsonToModel <WXOAuthCallBackStateEntity>(ZentCloud.Common.Base64Change.DecodeBase64ByUTF8(state));
                    }
                    else
                    {
                        ToLog("context.Session[state] is null");
                        return;
                    }
                    //如果传入code为空,跳过处理
                    if (string.IsNullOrWhiteSpace(code))
                    {
                        ToLog("context.Request[code] is null");
                        return;
                    }
                    string getTokenUrl =
                        string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
                                      WeixinAppId,     //systemset.WeixinAppId,
                                      WeixinAppSecret, //systemset.WeixinAppSecret,
                                      code);


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

                    WXOAuthAccessTokenEntity accessTokenModel = ZCJson.JsonConvert.DeserializeObject <WXOAuthAccessTokenEntity>(accessTokenSource);
                    if (accessTokenModel == null)
                    {
                        ToLog("ZCJson.JsonConvert.DeserializeObject<WXOAuthAccessTokenEntity>(accessTokenSource) is null");
                        return;
                    }
                    //ToLog("callback accessTokenModel:" + accessTokenModel);

                    //存储当前accessTokenModel到Session
                    context.Session[systemSet.WXOAuthAccessTokenEntityKey] = accessTokenModel;

                    //存储当前微信OpenID到Session,一旦存储有OpenID值和已登录标识,则不会再进行授权处理
                    context.Session[systemSet.WXCurrOpenerOpenIDKey] = accessTokenModel.OpenId;

                    //获取用户当前的openid-判断用户是否已注册-如果未注册则自动生成一个随机userId进行注册
                    userInfo = new ZentCloud.BLLJIMP.BLLUser("").GetUserInfoByOpenId(accessTokenModel.OpenId);

                    if (userInfo == null)
                    {
                        //ToLog("callback注册新用户");
                        //注册用户
                        userInfo                 = new ZentCloud.BLLJIMP.Model.UserInfo();
                        userInfo.UserID          = string.Format("WXUser{0}{1}", ZentCloud.Common.StringHelper.GetDateTimeNum(), ZentCloud.Common.Rand.Str(5));//WXUser+时间字符串+随机5位数字
                        userInfo.Password        = ZentCloud.Common.Rand.Str_char(12);
                        userInfo.UserType        = 2;
                        userInfo.WebsiteOwner    = currWebsiteOwner.UserID;
                        userInfo.Regtime         = DateTime.Now;
                        userInfo.WXAccessToken   = accessTokenModel.AccessToken;
                        userInfo.WXRefreshToken  = accessTokenModel.RefreshToken;
                        userInfo.WXOpenId        = accessTokenModel.OpenId;
                        userInfo.WXScope         = accessTokenModel.Scope;
                        userInfo.RegIP           = ZentCloud.Common.MySpider.GetClientIP();
                        userInfo.LastLoginIP     = ZentCloud.Common.MySpider.GetClientIP();
                        userInfo.LastLoginDate   = DateTime.Now;
                        userInfo.LoginTotalCount = 1;
                        userBll.Add(userInfo);
                        //List<ZentCloud.BLLPermission.Model.UserPmsGroupRelationInfo> userPmsGroupList = new List<ZentCloud.BLLPermission.Model.UserPmsGroupRelationInfo>() {
                        //    new ZentCloud.BLLPermission.Model.UserPmsGroupRelationInfo()//分配用户组为基本用户组
                        //    {
                        //        UserID = userInfo.UserID,
                        //        GroupID = 110578
                        //    },
                        //    new ZentCloud.BLLPermission.Model.UserPmsGroupRelationInfo()//分配用户组为教育普通用户组
                        //    {
                        //        UserID = userInfo.UserID,
                        //        GroupID = 130334
                        //    }
                        //};

                        //userBll.AddList<ZentCloud.BLLPermission.Model.UserPmsGroupRelationInfo>(userPmsGroupList);

                        //userInfo.HFPmsGroupStr = userInfo.HFUserPmsGroup;
                        //userBll.Update(userInfo);
                    }
                    else
                    {
                        //ToLog("老用户登录");

                        //更新用户信息
                        //userInfo.WXAccessToken = accessTokenModel.AccessToken;
                        //userInfo.WXRefreshToken = accessTokenModel.RefreshToken;
                        //userInfo.WXOpenId = accessTokenModel.OpenId;
                        //userInfo.WXScope = accessTokenModel.Scope;
                        //userInfo.LastLoginIP = ZentCloud.Common.MySpider.GetClientIP();
                        //userInfo.LastLoginDate = DateTime.Now;
                        //userInfo.LoginTotalCount++;

                        //userBll.Update(userInfo);
                    }


                    try
                    {
                        //如果是UserInfo方式,拉区微信用户信息并存储到会话,待后续页面使用
                        if (accessTokenModel.Scope.Contains("snsapi_userinfo"))
                        {
                            //ToLog("Callback正在拉取信息");

                            string userInfoSource = ZentCloud.Common.MySpider.GetPageSourceForUTF8(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}",
                                                                                                                 accessTokenModel.AccessToken,
                                                                                                                 accessTokenModel.OpenId
                                                                                                                 ));

                            if (!string.IsNullOrWhiteSpace(userInfoSource))
                            {
                                ZentCloud.BLLJIMP.Model.Weixin.WeixinUserInfo weixinUserInfo = ZCJson.JsonConvert.DeserializeObject <ZentCloud.BLLJIMP.Model.Weixin.WeixinUserInfo>(userInfoSource);
                                context.Session[systemSet.WXCurrOpenerUserInfoKey] = weixinUserInfo;

                                //更新用户微信信息
                                userInfo.WXCity       = weixinUserInfo.City;
                                userInfo.WXCountry    = weixinUserInfo.Country;
                                userInfo.WXHeadimgurl = weixinUserInfo.HeadImgUrl;
                                ////当用户是从无昵称变为有昵称,则认为是注册用户,且当前为正式注册时间
                                //if (string.IsNullOrWhiteSpace(userInfo.WXNickname) && !string.IsNullOrWhiteSpace(weixinUserInfo.NickName))
                                //{
                                //   // userInfo.RegIP = ZentCloud.Common.MySpider.GetClientIP();
                                //    //userInfo.Regtime = DateTime.Now;
                                //}
                                userInfo.WXNickname  = weixinUserInfo.NickName;
                                userInfo.WXPrivilege = ZentCloud.Common.JSONHelper.ObjectToJson(weixinUserInfo.Privilege);
                                userInfo.WXProvince  = weixinUserInfo.Province;
                                userInfo.WXSex       = weixinUserInfo.Sex;
                                userBll.Update(userInfo);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //ToLog("更新userInfo异常:" + ex.Message);
                        //如果拉区信息异常,则后续网页自行判断处理(可以自行根据accessToken拉取)
                    }


                    /*
                     * -- 2014.1.7
                     * 1.添加授权判断,如果没有昵称则返回重新用userInfo授权;
                     * 2.只有页面类型是userInfo授权类型的才执行该操作,本身是Base的不处理;
                     * 3.如果是userInfo页面类型,新用户也必须重新执行userInfo授权;
                     *
                     * 进入场景
                     * 1.新用户访问base页面;
                     * 2.新用户访问userinfo页面;
                     * 3.老用户访问base页面;
                     * 4.老用户访问userinfo页面;
                     *
                     * 首次进入都是base授权,
                     *
                     * userinfo页面下,判断是不是有微信昵称,没有微信昵称则需要进行userinfo授权
                     * 由base页面进入userinfo页面,再次进行base授权,然后由该阶段进行判断是否是需要重定向到userinfo授权
                     *
                     *
                     *
                     */

                    if (context.Session["weixinscope"] == null)
                    {
                        context.Session["weixinscope"] = "";
                    }
                    //context.Session["PageMatchModel"]

                    //ToLog("开始进行正式用户判断");

                    if (context.Session["PageMatchModel"] != null)
                    {
                        ModuleFilterInfo pageMatchModel = (ModuleFilterInfo)context.Session["PageMatchModel"];
                        if (pageMatchModel.Ex1 == "snsapi_userinfo" && string.IsNullOrWhiteSpace(userInfo.WXNickname) && context.Session["weixinscope"].ToString() != "snsapi_userinfo")
                        {
                            //ToLog("不是正式用户");

                            context.Session[systemSet.WXCurrOpenerOpenIDKey] = "";
                            context.Session["weixinscope"] = "snsapi_userinfo";

                            context.Session["isRedoOath"] = "1";

                            //再次访问目标链接(未取到CurrOpenID,会重新进行UserInfo授权)
                            context.Response.Redirect(callBackStateInfo.Path);
                            return;
                        }
                        //ToLog("是正式用户");
                    }



                    //设置用户ID
                    context.Session[ZentCloud.Common.SessionKey.UserID] = userInfo.UserID;
                    //修改登录标识
                    context.Session[ZentCloud.Common.SessionKey.LoginStatu] = 1;
                    context.Response.Redirect(callBackStateInfo.Path);
                    return;
                }
                #endregion

                #region 判断阶段及开始授权处理阶段
                List <ModuleFilterInfo> FilterList = userBll.GetList <ModuleFilterInfo>(" FilterType = 'WXOAuth' ");
                currOpenIDSession = context.Session[systemSet.WXCurrOpenerOpenIDKey] == null ? "" : context.Session[systemSet.WXCurrOpenerOpenIDKey].ToString();
                if (context.Session[ZentCloud.Common.SessionKey.LoginStatu] == null)
                {
                    context.Session[ZentCloud.Common.SessionKey.LoginStatu] = 0;
                }

                ModuleFilterInfo matchModel = new ModuleFilterInfo();

                //判断是否是返回重新进行userInfo 授权
                string isRedoOath = context.Session["isRedoOath"] == null ? "" : context.Session["isRedoOath"].ToString();

                //检查如果已登录且openId也存在,则跳过授权处理,扫一扫登录也需要重新验证
                if (context.Session[ZentCloud.Common.SessionKey.LoginStatu].ToString().Equals("1") && !string.IsNullOrWhiteSpace(currOpenIDSession))
                {
                    //增加判断,如果是在base授权区进入到UserInfo授权区,则需要重新授权,否则跳过-2013.12.26
                    //添加逻辑:并且用户没有昵称的时候才会去授权
                    if (context.Session["weixinscope"] != null)
                    {
                        string tmpscope = context.Session["weixinscope"].ToString();

                        if (tmpscope == "snsapi_base")
                        {
                            if (CheckIsToWXOAuth(currPath, out matchModel))
                            {
                                //ToLog("matchModel.Ex1:" + matchModel.Ex1);
                                userInfo = new ZentCloud.BLLJIMP.BLLUser("").GetUserInfoByOpenId(context.Session[systemSet.WXCurrOpenerOpenIDKey] == null ? "" : context.Session[systemSet.WXCurrOpenerOpenIDKey].ToString());
                                if (userInfo == null)
                                {
                                    userInfo = new ZentCloud.BLLJIMP.Model.UserInfo();
                                }
                                if (matchModel.Ex1 == "snsapi_userinfo" && string.IsNullOrWhiteSpace(userInfo.WXNickname))
                                {
                                    //不跳出而进行重新授权
                                }
                                else
                                {
                                    return;
                                }
                            }
                            else
                            {
                                return;
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        return;
                    }
                }



                if (isRedoOath == "1")
                {
                    context.Session["weixinscope"] = "snsapi_userinfo";
                    context.Session["isRedoOath"]  = "0";
                }
                else
                {
                    context.Session["weixinscope"] = "snsapi_base";
                }



                string scope = "snsapi_base";
                if (context.Session["weixinscope"] != null)
                {
                    scope = context.Session["weixinscope"].ToString();
                }

                if (string.IsNullOrWhiteSpace(scope))
                {
                    context.Session["weixinscope"] = "snsapi_base";
                    scope = "snsapi_base";
                }



                //查询不在授权区则跳出处理
                if (!CheckIsToWXOAuth(currPath, out matchModel))
                {
                    //ToLog("不在授权区");
                    return;
                }
                //ToLog("在授权区");

                //保存当前页面匹配实体
                context.Session["PageMatchModel"] = matchModel;

                //构造callBackUrl
                string callBackUrl = string.Format("http://{0}/wxcallback.aspx", context.Request.Url.Host);

                //构造返回参数
                WXOAuthCallBackStateEntity stateInfo = new WXOAuthCallBackStateEntity()
                {
                    Path = context.Request.Url.AbsoluteUri
                };


                string oauthUrl = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect",
                                                WeixinAppId,
                                                callBackUrl,
                                                scope,
                                                "STATE"
                                                );



                //防止state过长微信的userInfo类型会报错,将该字段目前存session,后面有必要可以再改为其他映射关系
                context.Session["state"] = ZentCloud.Common.Base64Change.EncodeBase64ByUTF8(ZentCloud.Common.JSONHelper.ObjectToJson(stateInfo));


                //访问授权链接
                context.Response.Redirect(oauthUrl);
                #endregion

                /*
                 * 判断阶段:
                 *
                 * (判断是否需拦截(CallBack回来,结尾带上标签#WxCallBack)----该方式不成立,如果转发分享这个链接到朋友圈之类的就不行了)
                 * 获取用户名,获取Session中存储的CurrOpenID及UserID
                 * 判断当前用户是否已进行微信认证,只有微信认证过的用户才允许使用网页授权
                 * 判断Session,是否已有CurrOpenID,判断新的用户名是否等于旧的用户名:如果已有CurrOpenID但是新的用户名跟旧的用户名不一致,则重新授权获取当前的OpenID
                 * (这样判断解决问题:比如有两张页面,第一张页面是张三发的报名,第二张页面是李四发的报名,而openID在张三和李四这边都不一样)
                 *
                 * 判断是否符合拦截条件
                 *
                 * 最后不管符合不符合拦截条件,如果UserID存在有并是数据库用户,都存储用户ID
                 *
                 * --------------------------------------
                 *
                 * 开始授权处理阶段:
                 *
                 * 获取配置的高级接口参数
                 * 构造CallBackUrl
                 * 构造返回参数:目前传递Path(当前路径),UserID
                 * 构造授权链接
                 * 访问授权链接
                 *
                 * ---------------------------------------
                 * CallBack处理阶段:
                 * 接收参数 code,Path,UserId,CurrOpenId
                 * 构造授权API
                 * 获取OpenID
                 * 构造目标链接:Path + UserID
                 * 存储当前微信OpenID到Session
                 * 访问最终目标链接(已取到CurrOpenID)
                 *
                 * 2013.12.06修改逻辑:自动判断授权模式
                 * callback回来后,根据openId查询获取是不是会员,如果不是会员,则重新返回授权用userInfo方式
                 * 注册会员那边自动添加拉取到的微信会员信息
                 *
                 *
                 * 2013.12.19
                 * 更改后的方法升级:1.直接授权后登录;2.不是会员的则会自动注册会员;3.openId直接是登录凭据;
                 *
                 * 判断是否授权依据是登录标识为登出,登出状态才进行授权登录,openId为空也进行登录
                 *
                 * 获取用户当前的openid-判断用户是否已注册-如果未注册则自动生成一个随机userId进行注册
                 *
                 * 登录标识标为已登录,并获取openId及其他信息
                 *
                 *
                 *
                 */
            }
            catch (Exception ex)
            {
                //ToLog(ex.Message);
            }
        }
Esempio n. 2
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            try
            {
                // UserInfo distributionOffLineCommendUser = null;//分销推荐人
                //bool isDistributionOffLineApply = false;//是否线下分销申请
                dicPar = bll.GetRequestParameter();
                string weixinOpenID = null; //微信openid
                string activityId   = null; //活动编号
                dicPar.TryGetValue("ActivityID", out activityId);
                string spreadUserId = null;
                dicPar.TryGetValue("SpreadUserID", out spreadUserId);//推广用户的用户名
                string shareUserId = string.Empty;
                dicPar.TryGetValue("ShareUserID", out shareUserId);
                string shareId = string.Empty;
                dicPar.TryGetValue("ShareID", out shareId);
                string strDistinctKeys = null; //检查重复的字段,多个字段用,分隔, //没有此参数默认用手机检查
                dicPar.TryGetValue("DistinctKeys", out strDistinctKeys);
                string monitorPlanID = null;   //监测任务ID
                dicPar.TryGetValue("MonitorPlanID", out monitorPlanID);
                string name = null;            //姓名
                dicPar.TryGetValue("Name", out name);
                string phone = null;           //手机
                dicPar.TryGetValue("Phone", out phone);
                string isSaveUserInfo = string.Empty;
                dicPar.TryGetValue("IsSaveUserInfo", out isSaveUserInfo);

                //activity = bll.Get<ActivityInfo>(string.Format("ActivityID='{0}'", activityId));

                #region IP限制
                //获取用户IP;
                string userHostAddress = context.Request.UserHostAddress;
                var    count           = DataCache.GetCache(userHostAddress);
                if (count != null)
                {
                    int newCount = int.Parse(count.ToString()) + 1;
                    DataCache.SetCache(userHostAddress, newCount);
                    int limitCount = 1000;
                    //if (activity != null)
                    //{

                    //    //limitCount = activity.LimitCount;

                    //}
                    if (newCount >= limitCount)
                    {
                        resp.Status = 14;
                        resp.Msg    = "您的提交过于频繁,请稍后再试";
                        goto outoff;
                    }
                }
                else
                {
                    DataCache.SetCache(userHostAddress, 1, DateTime.MaxValue, new TimeSpan(4, 0, 0));
                }


                #endregion

                #region 判断必填项
                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(phone))
                {
                    resp.Status = 3;
                    resp.Msg    = "姓名和手机不能为空!";
                    goto outoff;
                }
                //if ((!Common.ValidatorHelper.PhoneNumLogicJudge(Phone))&&(!Phone.Equals("systemdefault")))//系统缺省手机号不检查
                //{
                //    resp.Status = 5;
                //    resp.Msg = "手机号码无效!";
                //    goto outoff;
                //}
                if (((!phone.StartsWith("1")) || (!phone.Length.Equals(11))) && (!phone.Equals("systemdefault")))//系统缺省手机号不检查
                {
                    resp.Status = 5;
                    resp.Msg    = "手机号码无效!";
                    goto outoff;
                }
                if (string.IsNullOrEmpty(activityId))
                {
                    resp.Status = 6;
                    resp.Msg    = "活动编号不能为空!";
                    goto outoff;
                }

                //手机注册的重复数据
                UserInfo dicUser = bllUser.Get <UserInfo>(string.Format(" WebsiteOwner='{0}' AND Phone='{1}' AND WXOpenId is null ", bllUser.WebsiteOwner, phone));
                if (dicUser != null)
                {
                    dicUser.Phone3 = phone;
                    dicUser.Phone  = "";
                    bllUser.Update(dicUser);
                }



                #endregion

                #region 活动权限验证
                //if (activity == null)
                //{
                //    resp.Status = 7;
                //    resp.Msg = "活动编号不存在!";
                //    goto outoff;
                //}
                //if (activity.ActivityStatus.Equals(0))
                //{
                //    resp.Status = 8;
                //    resp.Msg = "活动已关闭!";
                //    goto outoff;
                //}

                //if (activity.IsDelete.Equals(1))
                //{
                //    resp.Status = -1;
                //    resp.Msg = "活动已删除!";
                //    goto outoff;
                //}
                #endregion

                #region 是否可以报名
                if (bll.IsLogin)
                {
                    currentUserInfo = bll.GetCurrentUserInfo();
                    if (!string.IsNullOrEmpty(currentUserInfo.WXOpenId))
                    {
                        weixinOpenID = currentUserInfo.WXOpenId;
                    }
                }
                juActivityInfo = bll.Get <JuActivityInfo>(string.Format("SignUpActivityID={0}", dicPar["ActivityID"]));
                if (juActivityInfo != null)
                {
                    #region 活动已经停止
                    if (juActivityInfo.IsHide.Equals(1))
                    {
                        resp.Status = 14;
                        resp.Msg    = "活动已停止";
                        goto outoff;
                    }
                    #endregion

                    #region 检查报名人数
                    if (juActivityInfo.MaxSignUpTotalCount > 0)//检查报名人数
                    {
                        if (juActivityInfo.SignUpTotalCount > (juActivityInfo.MaxSignUpTotalCount - 1))
                        {
                            resp.Status = 15;
                            resp.Msg    = "报名人数已满";
                            goto outoff;
                        }
                    }
                    #endregion

                    #region 检查积分
                    if (juActivityInfo.ActivityIntegral > 0)
                    {
                        if (!bll.IsLogin)
                        {
                            resp.Status = 12;
                            resp.Msg    = "此活动必须登录才能报名";
                            goto outoff;
                        }
                        else
                        {
                            if (currentUserInfo.TotalScore < juActivityInfo.ActivityIntegral)
                            {
                                resp.Status = 13;
                                resp.Msg    = "您的积分不足,无法报名";
                                goto outoff;
                            }
                        }
                    }
                    #endregion

                    #region 指定标签的用户可以报名
                    if (!string.IsNullOrEmpty(juActivityInfo.Tags))
                    {
                        if (!bll.IsLogin)
                        {
                            resp.Status = 12;
                            resp.Msg    = "此活动必须登录才能报名";
                            goto outoff;
                        }
                        if (string.IsNullOrEmpty(currentUserInfo.TagName))
                        {
                            resp.Status = 12;
                            resp.Msg    = "此活动只接受特定用户的报名";
                            goto outoff;
                        }
                        bool checkResult = false;
                        foreach (string item in currentUserInfo.TagName.Split(','))
                        {
                            if (juActivityInfo.Tags.Contains(item))
                            {
                                checkResult = true;
                                break;
                            }
                        }
                        if (!checkResult)
                        {
                            resp.Status = 12;
                            resp.Msg    = "此活动只接受特定用户的报名";
                            goto outoff;
                        }
                    }
                    #endregion
                }
                #endregion

                #region 检查自定义必填项
                List <ActivityFieldMappingInfo> requiredFieldList = bll.GetList <ActivityFieldMappingInfo>(string.Format("ActivityID='{0}' And FieldIsNull=1", juActivityInfo.SignUpActivityID));
                if (requiredFieldList.Count > 0)
                {
                    foreach (var requiredField in requiredFieldList)
                    {
                        if (string.IsNullOrEmpty(dicPar.SingleOrDefault(p => p.Key.Equals(string.Format("K{0}", requiredField.ExFieldIndex))).Value))
                        {
                            resp.Status = 11;
                            resp.Msg    = string.Format(" {0} 必填", requiredField.MappingName);
                            goto outoff;
                        }
                    }
                }
                #endregion

                #region 检查数据格式
                //检查数据格式
                List <ActivityFieldMappingInfo> activityFieldMappingList = bll.GetList <ActivityFieldMappingInfo>(string.Format("ActivityID='{0}'", juActivityInfo.SignUpActivityID));
                foreach (var item in activityFieldMappingList)
                {
                    string value = dicPar.SingleOrDefault(p => p.Key.Equals(string.Format("K{0}", item.ExFieldIndex))).Value;

                    if (string.IsNullOrWhiteSpace(value))
                    {
                        continue;
                    }

                    //检查数据格式
                    if (item.FormatValiFunc == "email")//email检查
                    {
                        if (!Common.ValidatorHelper.EmailLogicJudge(value))
                        {
                            resp.Status = 12;
                            resp.Msg    = string.Format("{0}格式不正确", item.MappingName);
                            goto outoff;
                        }
                    }
                    if (item.FormatValiFunc == "url")                                                                                                             //url检查
                    {
                        System.Text.RegularExpressions.Regex regUrl = new System.Text.RegularExpressions.Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); //网址
                        System.Text.RegularExpressions.Match match  = regUrl.Match(value);
                        if (!match.Success)
                        {
                            resp.Status = 13;
                            resp.Msg    = string.Format("{0}格式不正确", item.MappingName);
                            goto outoff;
                        }
                    }
                }
                #endregion

                #region 检查是否已经报名

                //if (activityId != bllDis.GetDistributionOffLineApplyActivityID())//线下分销不检查
                //{
                if (!string.IsNullOrEmpty(strDistinctKeys))
                {
                    if (!strDistinctKeys.Equals("none"))//自定义检查重复
                    {
                        System.Text.StringBuilder sbWhere = new System.Text.StringBuilder("1=1 ");
                        string[] distinctKeys             = strDistinctKeys.Split(',');
                        foreach (var item in distinctKeys)
                        {
                            sbWhere.AppendFormat("And {0}='{1}' ", item, dicPar.Single(p => p.Key.Equals(item)).Value);
                        }
                        sbWhere.Append("  and IsDelete = 0  ");
                        if (bll.GetCount <ActivityDataInfo>(sbWhere.ToString()) > 0)
                        {
                            resp.Status = 1;
                            resp.Msg    = "重复的报名!";
                            goto outoff;
                        }
                    }
                    else//不检查重复
                    {
                    }
                }
                else//默认检查
                {
                    if (bll.GetCount <ActivityDataInfo>(string.Format("ActivityID='{0}' And Phone='{1}' and IsDelete = 0 ", activityId, phone)) > 0)
                    {
                        resp.Status = 1;
                        resp.Msg    = "已经报过名了!";
                        goto outoff;
                    }
                }
                //}



                #endregion

                //if (activityId == bllDis.GetDistributionOffLineApplyActivityID())//如果当前活动是分销
                //{
                //    if (bll.GetCount<ActivityDataInfo>(string.Format("ActivityID='{0}' And UserId='{1}' and IsDelete = 0 ", activityId, currentUserInfo.UserID)) > 0)
                //    {
                //        bll.Update(new ActivityDataInfo(), string.Format("IsDelete=1"), string.Format(" ActivityID='{0}' And UserId='{1}'", activityId, currentUserInfo.UserID));
                //    }
                //}

                //#region 检查手机验证码 特殊化
                ////if (ActivityID.Equals("186135"))
                ////{
                ////    string VerCode = HttpContext.Current.Session["SmsVerificationCode"] == null ? "" : HttpContext.Current.Session["SmsVerificationCode"].ToString();
                ////    if (string.IsNullOrEmpty(context.Request["SmsVerificationCode"]))
                ////    {
                ////        resp.Status = 12;
                ////        resp.Msg = "请输入手机验证码";
                ////        goto outoff;


                ////    }
                ////    if (!context.Request["SmsVerificationCode"].ToString().Equals(VerCode))
                ////    {
                ////            resp.Status = 13;
                ////            resp.Msg = "手机验证码不正确";
                ////            goto outoff;
                ////    }
                ////}
                //#endregion

                var newActivityUID       = 1001;
                var lastActivityDataInfo = bll.Get <ActivityDataInfo>(string.Format("ActivityID='{0}' order by UID DESC", activityId));
                if (lastActivityDataInfo != null)
                {
                    newActivityUID = lastActivityDataInfo.UID + 1;
                }
                ActivityDataInfo model = bll.ConvertRequestToModel <ActivityDataInfo>(new ActivityDataInfo());
                model.UID          = newActivityUID;
                model.WeixinOpenID = weixinOpenID;
                model.SpreadUserID = spreadUserId;
                if (spreadUserId == currentUserInfo.UserID)
                {
                    model.SpreadUserID = bll.WebsiteOwner;
                }
                if (!string.IsNullOrEmpty(monitorPlanID))
                {
                    model.MonitorPlanID = int.Parse(monitorPlanID);
                }
                model.ShareUserID  = string.IsNullOrWhiteSpace(shareUserId) ? "" : shareUserId;
                model.ShareID      = string.IsNullOrWhiteSpace(shareId) ? "" : shareId;
                model.WebsiteOwner = bll.WebsiteOwner;
                if (bll.IsLogin)
                {
                    model.UserId = bll.GetCurrUserID();
                }

                //保存分销推荐码
                // model.DistributionOffLineRecommendCode = context.Request["DistributionOffLineRecommendCode"];


                //if (!string.IsNullOrWhiteSpace(model.DistributionOffLineRecommendCode))
                //{
                //    bool isTrueCode = false;
                //    int userAutoId = 0;
                //    if (int.TryParse(model.DistributionOffLineRecommendCode, out userAutoId))
                //    {
                //        distributionOffLineCommendUser = bllUser.GetUserInfoByAutoID(userAutoId);

                //        if (distributionOffLineCommendUser != null)
                //        {
                //            //是站点用户或者是当前站点的分销员才有效
                //            if (bll.WebsiteOwner.ToLower() == distributionOffLineCommendUser.UserID.ToLower())
                //            {
                //                isTrueCode = true;
                //            }
                //            else if (distributionOffLineCommendUser.WebsiteOwner.ToLower() == bll.WebsiteOwner.ToLower() && !string.IsNullOrWhiteSpace(distributionOffLineCommendUser.DistributionOffLinePreUserId))
                //            {
                //                isTrueCode = true;
                //            }
                //        }
                //    }

                //    if (!isTrueCode)
                //    {
                //        resp.Status = 1;
                //        resp.Msg = "不是有效的推荐码";
                //        goto outoff;
                //    }
                //    else
                //    {
                //        isDistributionOffLineApply = true;
                //    }

                //    ToLog("isDistributionOffLineApply:" + isDistributionOffLineApply);

                //}


                if (bll.Add(model))
                {
                    try
                    {
                        //#region 业务分销员申请消息
                        ////发送模板消息跟系统微客服和他的上级
                        //ToLog("isDistributionOffLineApply:" + isDistributionOffLineApply);
                        //if (isDistributionOffLineApply)
                        //{
                        //    ToLog("申请成为财富会员,发送消息给系统管理员");

                        //    //发送消息给他上级
                        //    //bllWeixin.SendTemplateMessageNotifyComm(distributionOffLineCommendUser.WXOpenId, "财富伙伴申请", string.Format("姓名:{0}\\n手机号:{1}", model.Name, model.Phone));

                        //    //发送消息给系统管理员
                        //    // WXKeFu kefuInfo = bllWeixin.GetDefaultKefu();
                        //    //ToLog("客服实体:" + JSONHelper.ObjectToJson(kefuInfo));
                        //    bllWeixin.SendTemplateMessageToKefu(string.Format("用户“{0}”申请成为财富会员", model.Name), string.Format("姓名:{0}\\n手机号:{1}", model.Name, model.Phone));

                        //}
                        //#endregion

                        #region 个人资料补足
                        if (bll.IsLogin)
                        {
                            //个人资料补足
                            bool isEdit = false;
                            isSaveUserInfo = "1";
                            if (string.IsNullOrWhiteSpace(currentUserInfo.TrueName))
                            {
                                isEdit = true;
                                currentUserInfo.TrueName = model.Name;
                            }
                            if (string.IsNullOrWhiteSpace(currentUserInfo.Phone))
                            {
                                isEdit = true;
                                currentUserInfo.Phone = model.Phone;
                            }
                            List <BLLJIMP.Model.ActivityFieldMappingInfo> mapingList = this.bll.GetList <BLLJIMP.Model.ActivityFieldMappingInfo>(string.Format(" ActivityID = '{0}' ", model.ActivityID));

                            foreach (var item in mapingList)
                            {
                                string value = "";
                                if (item.MappingName.IndexOf("邮箱") > -1 || item.MappingName.IndexOf("邮件") > -1 || item.MappingName.ToLower().IndexOf("email") > -1)
                                {
                                    isEdit = true;

                                    value = dicPar.SingleOrDefault(p => p.Key.Equals(string.Format("K{0}", item.ExFieldIndex))).Value;
                                    if (string.IsNullOrWhiteSpace(currentUserInfo.Email))
                                    {
                                        currentUserInfo.Email = value;
                                    }
                                    continue;
                                }

                                if (item.MappingName.IndexOf("职位") > -1)
                                {
                                    isEdit = true;
                                    value  = dicPar.SingleOrDefault(p => p.Key.Equals(string.Format("K{0}", item.ExFieldIndex))).Value;
                                    if (string.IsNullOrWhiteSpace(currentUserInfo.Postion))
                                    {
                                        currentUserInfo.Postion = value;
                                    }
                                    continue;
                                }

                                if (item.MappingName.IndexOf("公司") > -1)
                                {
                                    isEdit = true;
                                    value  = dicPar.SingleOrDefault(p => p.Key.Equals(string.Format("K{0}", item.ExFieldIndex))).Value;
                                    if (value.Length >= 255)
                                    {
                                        resp.Status = 3;
                                        resp.Msg    = "公司名称过长!";
                                        goto outoff;
                                    }
                                    if (string.IsNullOrWhiteSpace(currentUserInfo.Company))
                                    {
                                        currentUserInfo.Company = value;
                                    }
                                    continue;
                                }
                            }


                            if (isEdit)
                            {
                                this.bll.Update(new UserInfo(),
                                                string.Format(" TrueName='{0}',Phone='{1}',Email='{2}',Postion='{3}',Company='{4}'  ",
                                                              currentUserInfo.TrueName,
                                                              currentUserInfo.Phone,
                                                              currentUserInfo.Email,
                                                              currentUserInfo.Postion,
                                                              currentUserInfo.Company
                                                              ),
                                                string.Format(" AutoID = {0} ", this.currentUserInfo.AutoID)
                                                );
                            }

                            //if (isEdit && !string.IsNullOrWhiteSpace(isSaveUserInfo))
                            //{
                            //    if (isSaveUserInfo == "1")
                            //    {
                            //        this.bll.Update(new UserInfo(),
                            //                string.Format(" TrueName='{0}',Phone='{1}',Email='{2}',Postion='{3}',Company='{4}'  ",
                            //                        currentUserInfo.TrueName,
                            //                        currentUserInfo.Phone,
                            //                        currentUserInfo.Email,
                            //                        currentUserInfo.Postion,
                            //                        currentUserInfo.Company
                            //                    ),
                            //                string.Format(" AutoID = {0} ", this.currentUserInfo.AutoID)
                            //            );
                            //    }
                            //}
                            //if (bll.IsLogin)
                            //{
                            //    var websiteInfo = bll.GetWebsiteInfoModelFromDataBase();
                            //    if (websiteInfo.IsSynchronizationData != null)
                            //    {
                            //        if (websiteInfo.IsSynchronizationData.Value == 1)
                            //        {

                            //            bllUser.Update(currentUserInfo);
                            //        }
                            //    }
                            //}
                        }
                        #endregion

                        #region 检查是否向微信客服号发送通知信息

                        if (juActivityInfo != null)
                        {
                            //if (!string.IsNullOrEmpty(juActivityInfo.ActivityNoticeKeFuId))
                            //{

                            //    WXKeFu keFuInfo = bll.Get<WXKeFu>(string.Format("AutoID={0}", juActivityInfo.ActivityNoticeKeFuId));
                            //    if (keFuInfo != null)
                            //    {

                            //        #region 发送模板消息给客服
                            //        if (juActivityInfo.ArticleType != "greetingcard")
                            //        {
                            //            bllWeixin.SendTemplateMessageNotifyComm(keFuInfo.WeiXinOpenID, string.Format("{0}有新的报名", juActivityInfo.ActivityName), string.Format("姓名:{0}\\n手机号:{1}", model.Name, model.Phone));
                            //        }
                            //        #endregion


                            //    }
                            //}

                            #region 发送模板消息给客服
                            if (juActivityInfo.ArticleType != "greetingcard")
                            {
                                bllWeixin.SendTemplateMessageToKefu(string.Format("{0}有新的报名", juActivityInfo.ActivityName), string.Format("姓名:{0}\\n手机号:{1}", model.Name, model.Phone));
                            }
                            #endregion

                            juActivityInfo.SignUpCount = juActivityInfo.SignUpTotalCount + 1;
                            bll.Update(juActivityInfo);
                        }



                        #endregion

                        #region 更新转发表报名数量
                        MonitorLinkInfo linkModel   = bll.Get <MonitorLinkInfo>(string.Format(" MonitorPlanID={0} AND LinkName='{1}' ", monitorPlanID, spreadUserId));
                        int             signupCount = bll.GetCount <ActivityDataInfo>(string.Format("MonitorPlanID={0} And SpreadUserID='{1}' And IsDelete=0", int.Parse(monitorPlanID), spreadUserId));
                        if (linkModel != null)
                        {
                            linkModel.ActivitySignUpCount = signupCount;
                            bll.Update(linkModel);
                        }
                        #endregion

                        //#region 向报名人发送公众号模板消息-仅五步会有效

                        //if (bll.WebsiteOwner == "wubuhui")
                        //{
                        //    if (bllWeixin.IsLogin)
                        //    {
                        //        string accessToken = bllWeixin.GetAccessToken();
                        //        if (accessToken != string.Empty)
                        //        {
                        //            BLLWeixin.TMSignupNotification notificaiton = new BLLWeixin.TMSignupNotification();

                        //            notificaiton.Url = string.Format("http://{0}/WuBuHui/MyCenter/Index.aspx", System.Web.HttpContext.Current.Request.Url.Host);

                        //            notificaiton.TemplateId = "-eJq0w8PEFQRLnWXwqKn73zWvAah6nJxYHgEK3L4Pek";
                        //            notificaiton.First = "恭喜您成功报名我们的活动";
                        //            notificaiton.Keynote1 = juActivityInfo.ActivityName;
                        //            notificaiton.Keynote2 = juActivityInfo.ActivityStartDate.ToString();
                        //            notificaiton.Keynote3 = juActivityInfo.ActivityAddress;
                        //            notificaiton.Remark = "欢迎您届时参加!";
                        //            bllWeixin.SendTemplateMessage(accessToken, currentUserInfo.WXOpenId, notificaiton);

                        //        }
                        //    }
                        //}



                        //#endregion

                        #region 发送模板消息给用户
                        if ((currentUserInfo != null))
                        {
                            if (juActivityInfo.ArticleType != "greetingcard" && juActivityInfo.IsFee == 0)
                            {
                                bllWeixin.SendTemplateMessageNotifyComm(currentUserInfo, string.Format("您已成功报名{0}", juActivityInfo.ActivityName), string.Format("姓名:{0}\\n手机号:{1}", model.Name, model.Phone));
                            }
                            if (juActivityInfo.IsFee == 1)//收费活动
                            {
                                if (model.Amount > 0)
                                {
                                    bllWeixin.SendTemplateMessageNotifyComm(currentUserInfo, string.Format("您已报名{0},该活动收费,请尽快完成支付。", juActivityInfo.ActivityName), "");
                                }
                            }
                        }
                        #endregion

                        #region 微转发自动成为线上分销员
                        if (!string.IsNullOrEmpty(model.SpreadUserID))
                        {
                            if (bll.IsLogin)
                            {
                                try
                                {
                                    WebsiteInfo websiteInfo = bll.GetWebsiteInfoModelFromDataBase();

                                    if (websiteInfo.DistributionRelationBuildSpreadActivity == 1)
                                    {
                                        UserInfo recommentUserInfo = bllUser.GetUserInfo
                                                                         (spreadUserId);
                                        //ActivityInfo disActivityInfo = bll.GetActivityInfoByActivityID(bllDis.GetDistributionOffLineApplyActivityID());
                                        //bllDis.AutoApply(currentUserInfo, activity, disActivityInfo, recommentUserInfo, model);
                                        if (bllUser.IsDistributionMember(recommentUserInfo) || (recommentUserInfo.UserID == websiteInfo.WebsiteOwner))
                                        {
                                            bllDisOnLine.SetUserDistributionOwner(currentUserInfo.UserID, recommentUserInfo.UserID, currentUserInfo.WebsiteOwner);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ToLog(ex.ToString());
                                }
                            }
                        }
                        #endregion

                        juActivityInfo = bllJuactivity.GetJuActivityByActivityID(activityId);
                    }
                    catch (Exception)
                    {
                    }
                    resp.Msg = "提交成功!";
                    //Dictionary<string, object> exObj = new Dictionary<string, object>();
                    //exObj.Add("Activity", Activity);
                    //exObj.Add("ActivityData", model);
                    //exObj.Add("ActivityFieldMapping", activityFieldMapping);
                    //resp.ExObj = exObj;
                    resp.ExInt = model.UID;
                    if (juActivityInfo != null)
                    {
                        resp.ExStr = juActivityInfo.ActivitySignuptUrl;
                    }

                    // 推荐报名活动加积分
                    if (!string.IsNullOrEmpty(spreadUserId))
                    {
                        if (spreadUserId != currentUserInfo.UserID)
                        {
                            UserInfo recommentUserInfo = bllUser.GetUserInfo(spreadUserId);
                            bllUser.AddUserScoreDetail(recommentUserInfo.UserID, CommonPlatform.Helper.EnumStringHelper.ToString(ZentCloud.BLLJIMP.Enums.ScoreDefineType.RecommendSignUpActivityAddScore), recommentUserInfo.WebsiteOwner, null, null);
                        }
                    }

                    #region MyRegion
                    if (!string.IsNullOrEmpty(context.Request["AutoSignIn"]))
                    {
                        if (context.Request["AutoSignIn"].ToString() == "1")
                        {
                            try
                            {
                                WXSignInInfo signInInfo = new WXSignInInfo();
                                signInInfo.SignInUserID = currentUserInfo.UserID;
                                signInInfo.Name         = model.Name;
                                signInInfo.Phone        = model.Phone;
                                signInInfo.JuActivityID = juActivityInfo.JuActivityID;
                                signInInfo.SignInOpenID = currentUserInfo.WXOpenId;
                                signInInfo.SignInTime   = DateTime.Now;
                                //判断是否已经签到过
                                if (!bllJuactivity.Exists(signInInfo, new List <string>()
                                {
                                    "SignInUserID", "JuActivityID"
                                }))
                                {
                                    if (bllJuactivity.Add(signInInfo))
                                    {
                                        bllUser.AddUserScoreDetail(currentUserInfo.UserID, CommonPlatform.Helper.EnumStringHelper.ToString(ZentCloud.BLLJIMP.Enums.ScoreDefineType.SignIn), currentUserInfo.WebsiteOwner, null, null);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    #endregion


                    goto outoff;
                }
                else
                {
                    resp.Status = 2;
                    resp.Msg    = "报名失败,请重试或联系管理员!";
                    goto outoff;
                }
            }
            catch (Exception ex)
            {
                //using (StreamWriter sw = new StreamWriter(@"C:\log.txt", true, System.Text.Encoding.GetEncoding("gb2312")))
                //{
                //    sw.WriteLine(ex.Data);
                //}
                resp.Status = 10;
                resp.Msg    = "报名失败:" + ex.ToString();
                goto outoff;
                //日志记录
            }
outoff:
            context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
        }
Esempio n. 3
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
        }
Esempio n. 4
0
        /// <summary>
        /// 收货
        /// </summary>
        private void ReceiptConfirm()
        {
            try
            {
                var orderList = bllMall.GetList <WXMallOrderInfo>(string.Format(" Status='已发货' And PayMentStatus=1 And DATEDIFF(day,DeliveryTime,GETDATE())>=8 And  WebSiteOwner='{0}'", websiteOwner));
                ToLog(string.Format("共获取到{0}笔订单,开始自动收货...", orderList.Count));
                DateTime dtNow        = DateTime.Now;
                int      index        = 1;
                int      successCount = 0;
                foreach (var orderInfo in orderList)
                {
                    ToLog(string.Format("正在处理第{0}笔订单,共{1}笔...", index, orderList.Count));
                    UserInfo orderUserInfo = bllUser.GetUserInfo(orderInfo.OrderUserID);
                    ZentCloud.ZCBLLEngine.BLLTransaction tran = new ZentCloud.ZCBLLEngine.BLLTransaction();
                    try
                    {
                        orderInfo.Status = "交易成功";
                        if (bllMall.Update(orderInfo, " Status='交易成功'", string.Format(" OrderId='{0}'", orderInfo.OrderID), tran) <= 0)
                        {
                            tran.Rollback();
                            continue;
                        }

                        //增加积分
                        ScoreConfig scoreConfig = bllScore.Get <ScoreConfig>(string.Format(" WebsiteOwner='{0}'", websiteOwner));
                        if (scoreConfig.OrderAmount == 0)
                        {
                            scoreConfig.OrderAmount = 1;
                        }
                        int addScore = (int)(orderInfo.PayableAmount / (scoreConfig.OrderAmount / scoreConfig.OrderScore));
                        if (addScore > 0)
                        {
                            WXMallScoreRecord scoreRecord = new WXMallScoreRecord();
                            scoreRecord.InsertDate   = DateTime.Now;
                            scoreRecord.Remark       = "微商城-交易完成获得积分";
                            scoreRecord.Score        = addScore;
                            scoreRecord.UserId       = orderInfo.OrderUserID;
                            scoreRecord.WebsiteOwner = websiteOwner;
                            scoreRecord.OrderID      = orderInfo.OrderID;
                            scoreRecord.Type         = 1;
                            if (!bllMall.Add(scoreRecord, tran))
                            {
                                tran.Rollback();
                                continue;
                            }
                            if (bllUser.Update(orderUserInfo, string.Format(" TotalScore+={0},HistoryTotalScore+={0}", addScore), string.Format(" AutoID={0}", orderUserInfo.AutoID), tran) <= 0)
                            {
                                tran.Rollback();
                                continue;
                            }
                            try
                            {
                                //驿氪同步
                                yiKeClient.BonusUpdate(orderUserInfo.Ex2, addScore, string.Format("订单交易成功获得{0}积分", addScore));
                                //驿氪同步
                                yiKeClient.ChangeStatus(orderInfo.OrderID, orderInfo.Status);
                            }
                            catch (Exception)
                            {
                            }
                        }

                        //

                        //更新订单明细表状态
                        List <WXMallOrderDetailsInfo> orderDetailList = bllMall.GetOrderDetailsList(orderInfo.OrderID);
                        foreach (var orderDetail in orderDetailList)
                        {
                            orderDetail.IsComplete = 1;
                            if (bllMall.Update(orderDetail, "IsComplete=1", string.Format(" OrderId='{0}'", orderInfo.OrderID)) <= 0)
                            {
                                tran.Rollback();
                                continue;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        continue;
                    }
                    tran.Commit();
                    successCount++;
                    //
                }

                ToLog("操作完成。耗时:" + (DateTime.Now - dtNow).TotalSeconds + "S");
                WriteLog(string.Format("自动收货完成.耗时{0}秒,自动收货订单数量{1}", (DateTime.Now - dtNow).TotalSeconds, successCount));
            }

            catch (Exception ex)
            {
                ToLog(ex.Message);
                WriteLog(ex.Message);
            }
        }