Beispiel #1
0
        /// <summary>
        /// 订阅(关注)事件。关注时需要把用户信息导入到数据库中
        /// </summary>
        /// <returns></returns>
        public override List <IResponseMessageBase> OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            //responseMessage.Content = GetWelcomeInfo();
            //Add user to local database
            if (!string.IsNullOrEmpty(WeixinOpenId))
            {
                // SycUserFromWeixin(WeixinOpenId);

                //同步用户
                var weChatConfig = GetWechatConfig();

                lock (objLockUser) //不lock的话,会插入多次
                {
                    WechatMPUser objUser = wechatMPUserService.Repository.Entities.FirstOrDefault(u => u.OpenId.Equals(WeixinOpenId));
                    if (null != objUser)
                    {
                        log.Debug("user :{0}, {1}", objUser.Id, objUser.IsCanceled);
                    }
                    WeChatCommonService.SycUserFromWeixinMP(WeixinOpenId, ref objUser, weChatConfig);
                }

                log.Debug("EventKey:{0}  Event:{1}", requestMessage.EventKey, requestMessage.Event);

                #region 通过扫码关注
                int    orCodeSceneId;
                string prefix = "qrscene_";
                if (!string.IsNullOrEmpty(requestMessage.EventKey) &&
                    requestMessage.EventKey.StartsWith(prefix) &&
                    int.TryParse(requestMessage.EventKey.Substring(prefix.Length), out orCodeSceneId))
                {
                    var entity = new FocusHistory()
                    {
                        CreatedTime     = DateTime.Now,
                        QrCodeSceneId   = orCodeSceneId,
                        UserId          = requestMessage.FromUserName,
                        PeopleCount     = 1,
                        PurePeopleCount = 1,
                        Status          = 1,
                    };
                    focusHistoryService.Repository.Insert(entity);
                    //添加关联标签,分组,
                    log.Debug("SubscribeWithScan :{0}", orCodeSceneId.ToString());
                    return(CreateResponseMessage(orCodeSceneId.ToString(), (int)AutoReplyMPKeywordEnum.SubscribeWithScan));
                }
                #endregion

                return(CreateResponseMessage(string.Empty, (int)AutoReplyMPKeywordEnum.SubscribeEvent));
            }
            log.Error("WeixinOpenId is null");
            return(null);
        }
        /// <summary>
        /// 同步微信用户
        /// </summary>
        /// <param name="WeixinOpenId"></param>
        /// <param name="userInfo"></param>
        /// <param name="config"></param>
        public static void SycUserFromWeixinMP(string WeixinOpenId, ref WechatMPUser userInfo, SysWechatConfig config)
        {
            Logger.Debug("SycUserFromWeixin");
            Innocellence.Weixin.MP.AdvancedAPIs.User.BatchGetUserInfoData user = new Innocellence.Weixin.MP.AdvancedAPIs.User.BatchGetUserInfoData
            {
                openid = WeixinOpenId,
                lang   = Language.zh_CN.ToString()
            };
            var result = Innocellence.Weixin.MP.AdvancedAPIs.UserApi.BatchGetUserInfo(config.WeixinAppId,
                                                                                      config.WeixinCorpSecret,
                                                                                      new List <Innocellence.Weixin.MP.AdvancedAPIs.User.BatchGetUserInfoData> {
                user
            });

            Logger.Debug("SycUserFromWeixin result");
            if (result != null && result.user_info_list != null)
            {
                Logger.Debug("result count :{0}", result.user_info_list.Count);
                var objuserInfo = result.user_info_list.Select(a => WechatMPUserView.ConvertWeChatUserToMpUser(a, config.AccountManageId.Value, config.Id)).ToList().FirstOrDefault();
                if (userInfo == null)
                {
                    userInfo = objuserInfo;
                }
                if (objuserInfo != null)
                {
                    Logger.Debug("SycUserFromWeixin userInfo: " + userInfo.OpenId + userInfo.NickName);
                    objuserInfo.AccountManageId = config.AccountManageId;
                    if (objuserInfo.SubScribe == 0) //未关注
                    {
                        objuserInfo.Id         = userInfo.Id;
                        objuserInfo.IsCanceled = true;
                        userInfo = objuserInfo;
                    }
                    else
                    {
                        objuserInfo.Id = userInfo.Id;
                    }
                    Logger.Debug("SycUserFromWeixin userInfo id: {0}, SubScribe: {1}", objuserInfo.Id, objuserInfo.SubScribe);
                    IWechatMPUserService wechatMPUserService = EngineContext.Current.Resolve <IWechatMPUserService>();
                    wechatMPUserService.RegistToWeiXin(objuserInfo);
                    Logger.Debug("SycUserFromWeixin userInfo updated.");
                }
                else
                {
                    Logger.Debug("SycUserFromWeixin Error objuserInfo=null.{0}", WeixinOpenId);
                }
            }
        }
        public async Task <ActionResult> BackLogin()
        {
            string returnUrl = Session["ReturnUrl"] as string;

            try
            {
                log.Error("Entering BackLogin, returnUrl=" + returnUrl);
                //ViewBag.ReturnUrl = returnUrl;
                if (Request["code"] != null)
                {
                    string code     = Request["code"].ToString();
                    string wechatid = Request["wechatid"].ToString();

                    log.Debug("code:" + code + " wechatid:" + wechatid);

                    SysUser user = null;

                    var weChatConfig = WeChatCommonService.GetWeChatConfigByID(int.Parse(wechatid));

                    if (weChatConfig.IsCorp.HasValue && !weChatConfig.IsCorp.Value)
                    {
                        var code1 = Innocellence.Weixin.MP.AdvancedAPIs.OAuthApi.GetAccessToken(weChatConfig.WeixinCorpId, weChatConfig.WeixinCorpSecret, code);

                        IWechatMPUserService ser = EngineContext.Current.Resolve <IWechatMPUserService>();

                        WechatMPUser objUser = null;

                        objUser = ser.Repository.Entities.Where(a => a.OpenId == code1.openid).FirstOrDefault();

                        log.Debug("MP objUser:"******"N" : "U") + " OpenID:" + code1.openid);

                        //如果用户不存在就添加用户

                        if (objUser == null)
                        {
                            // var userinfo = Innocellence.Weixin.MP.AdvancedAPIs.UserApi.Info(weChatConfig.WeixinCorpId, weChatConfig.WeixinCorpSecret, code1.openid);
                            // objUser = WechatMPUserView.ConvertWeChatUserToMpUser(userinfo, weChatConfig.AccountManageId.Value, weChatConfig.Id);
                            // ser.Repository.Insert(objUser);
                            lock (StaticLockObj)                                                                         //防止插入多条数据
                            {
                                objUser = ser.Repository.Entities.Where(a => a.OpenId == code1.openid).FirstOrDefault(); //为什么要重新查一次??因为有lock
                                if (objUser == null)
                                {
                                    WeChatCommonService.SycUserFromWeixinMP(code1.openid, ref objUser, weChatConfig);
                                }
                            }
                        }


                        if (objUser == null || objUser.IsCanceled == true || objUser.SubScribe == 0) //未关注
                        {
                            log.Debug("未关注 OpenID:{0}", code1.openid);
                            user = new SysUser()
                            {
                                UserName     = code1.openid,
                                WeChatUserID = "",
                                Id           = 0,
                                Apps         = new System.Collections.Generic.List <int>()
                                {
                                    int.Parse(wechatid)
                                }
                            };
                        }
                        else //已关注
                        {
                            user = new SysUser()
                            {
                                UserName     = objUser.NickName,
                                WeChatUserID = objUser.OpenId,
                                Id           = objUser.Id,
                                Apps         = new System.Collections.Generic.List <int>()
                                {
                                    int.Parse(wechatid)
                                }
                            };
                        }


                        //var user = UserManager.Entities.FirstOrDefault(a => a.UserName == code1.UserId);
                    }
                    else
                    {
                        var Token = AccessTokenContainer.TryGetToken(weChatConfig.WeixinCorpId, weChatConfig.WeixinCorpSecret);
                        log.Error("Token:" + Token);
                        var code1 = OAuth2Api.GetUserId(Token, code);

                        // BaseService<SysAddressBookMember> ser = new BaseService<SysAddressBookMember>();
                        IAddressBookService ser = EngineContext.Current.Resolve <IAddressBookService>();

                        if (string.IsNullOrEmpty(code1.UserId)) //没关注
                        {
                            user = new SysUser()
                            {
                                UserName     = code1.OpenId,
                                WeChatUserID = "",
                                Id           = 0,
                                Apps         = new System.Collections.Generic.List <int>()
                                {
                                    int.Parse(wechatid)
                                }
                            };
                        }
                        else //已经关注
                        {
                            var objUser = ser.Repository.Entities.Where(a => a.UserId == code1.UserId && a.DeleteFlag != 1).FirstOrDefault();

                            log.Debug("objUser:{1} UserID:{0} Status:{2}", code1.UserId, (objUser == null ? "N" : "U"), objUser == null ? "" : objUser.EmployeeStatus);

                            if (objUser != null && (objUser.EmployeeStatus == "D" || objUser.EmployeeStatus == "U")) //离职或状态不明
                            {
                                user = new SysUser()
                                {
                                    UserName     = objUser.UserId,
                                    WeChatUserID = "",
                                    Id           = 0,
                                    Apps         = new System.Collections.Generic.List <int>()
                                    {
                                        int.Parse(wechatid)
                                    }
                                };
                            }
                            else  //已经关注
                            {
                                //objUser = new SysAddressBookMember() { UserId = code1.UserId, Id = 0 };
                                if (objUser == null)
                                {
                                    lock (StaticLockObjMP)   //防止插入多条数据
                                    {
                                        if (objUser == null) //lock后,重新查一次
                                        {
                                            objUser = ser.Repository.Entities.Where(a => a.UserId == code1.UserId).FirstOrDefault();
                                        }


                                        WeChatCommonService.SyncUserFromWechat(code1.UserId, ref objUser, weChatConfig);
                                    }
                                }
                                user = new SysUser()
                                {
                                    UserName     = objUser.UserName,
                                    WeChatUserID = objUser.UserId,
                                    Id           = objUser.Id,
                                    Apps         = new System.Collections.Generic.List <int>()
                                    {
                                        int.Parse(wechatid)
                                    }
                                };
                            }
                        }



                        //var user = UserManager.Entities.FirstOrDefault(a => a.UserName == code1.UserId);
                    }

                    log.Debug("SignInNoDB UserID:{0} User:{1}", user.Id, user.UserName);


                    await _authenticationService.SignInNoDB(user, true);

                    //return Redirect(returnUrl);

                    ////////登录日志
                    //////BaseService<Logs> objServLogs = new BaseService<Logs>();
                    //////objServLogs.Insert(new Logs() { LogCate = "WechatLogin", LogContent = "登录成功", CreatedUserID = objUser.WeChatUserID, CreatedUserName = objUser.WeChatUserID });
                }

                //LogManager.GetLogger(this.GetType()).Error("strUrl:" + strUrl);

                var Ret = returnUrl + (returnUrl.IndexOf("?") > 0 ? "&_Callback=1" : "?_Callback=1");
                log.Debug("Ret URL:{0}", Ret);

                return(Redirect(Ret));
            }
            catch (Exception ex)
            {
                LogManager.GetLogger(this.GetType()).Error(ex, ex.Message);
                return(Redirect("/noCropPermission.html"));
            }

            //  View();
        }