/// <summary>
 /// 通过API获取APP的可见范围, 判断该User是否在其中
 /// </summary>
 /// <param name="appId"></param>
 /// <returns></returns>
 private bool ValidateUserInApp(int?appId)
 {
     if (null != appId)
     {
         SysAddressBookMember user = GetCropUser();
         if (null != user && null != user.AccountManageId)
         {
             return(WeChatCommonService.IsValidateUser((int)appId, user, (int)user.AccountManageId));
         }
     }
     return(false);
 }
示例#2
0
        ///// <summary>
        ///// 判断用户是否在APP的可见范围内
        ///// </summary>
        ///// <param name="appId"></param>
        ///// <param name="currentUserId"></param>
        ///// <param name="AccountManageID"></param>
        ///// <returns></returns>
        //public bool IsValidateUser(string appId, string currentUserId, int AccountManageID)
        //{


        //    if (HttpRuntime.Cache.Get("validateUsers") != null)
        //    {

        //        var obj = HttpRuntime.Cache.Get("validateUsers");
        //        List<String> allVisiblePerson = (List<String>)obj;
        //        return allVisiblePerson.Contains(currentUserId);

        //    }
        //    else
        //    {
        //        var appInfo = lstSysWeChatConfig.SingleOrDefault(a => a.AccountManageId == AccountManageID);

        //        var token = CommonApi.GetToken(appInfo.WeixinCorpId, appInfo.WeixinCorpSecret);
        //        var results = AppApi.GetAppInfo(token.access_token, Int32.Parse(appId));
        //        List<string> allVisiblePerson = new List<string>();
        //        foreach (var user in results.allow_userinfos.user)
        //        {
        //            allVisiblePerson.Add(user.userid);
        //        }
        //        foreach (var groupId in results.allow_partys.partyid)
        //        {
        //            var members = MailListApi.GetDepartmentMemberInfo(token.access_token, groupId, 1, 1);

        //            foreach (var user in members.userlist)
        //            {
        //                allVisiblePerson.Add(user.userid);
        //            }
        //        }

        //        HttpRuntime.Cache.Insert("validateUsers", allVisiblePerson, null, DateTime.Now.AddHours(2), TimeSpan.Zero);

        //        return allVisiblePerson.Contains(currentUserId);
        //    }
        //}

        /// <summary>
        ///  判断用户是否在APP的可见范围内
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="objUser"></param>
        /// <param name="AccountManageID"></param>
        /// <returns></returns>
        public static bool IsValidateUser(int appId, SysAddressBookMember objUser, int AccountManageID)
        {
            var AppInfo = cacheManager.Get <GetAppInfoResult>(string.Format("APP_{0}_{1}", AccountManageID, appId), () =>
            {
                Logger.Debug("cache is empty, creating cache....");
                var appInfo = GetWeChatConfigByID(appId);

                var token   = CommonApi.GetToken(appInfo.WeixinCorpId, appInfo.WeixinCorpSecret);
                var results = AppApi.GetAppInfo(token.access_token, int.Parse(appInfo.WeixinAppId));

                return(results);
            });

            //部门
            if (!string.IsNullOrWhiteSpace(objUser.Department))
            {
                string strParty = objUser.Department.Insert(objUser.Department.Length - 1, ",").Insert(1, ",");
                if (AppInfo.allow_partys.partyid.Count(a => strParty.IndexOf("," + a.ToString() + ",") >= 0) > 0)
                {
                    return(true);
                }
                var        departments    = lstDepartment(AccountManageID);
                List <int> allDepartments = new List <int>();
                FindAllParentDepartments(strParty, departments, allDepartments);
                if (AppInfo.allow_partys.partyid.Any(a => allDepartments.Contains(a)))
                {
                    return(true);
                }
            }
            //tag
            if (!string.IsNullOrWhiteSpace(objUser.TagList))
            {
                string strTag = objUser.TagList.Insert(objUser.TagList.Length - 1, ",").Insert(1, ",");
                if (AppInfo.allow_tags.tagid.Count(a => strTag.IndexOf("," + a.ToString() + ",") >= 0) > 0)
                {
                    return(true);
                }
            }
            //user
            if (AppInfo.allow_userinfos.user.Exists(a => objUser.UserId == a.userid))
            {
                return(true);
            }

            return(false);
        }
        /// <summary>
        /// 同步企业号用户
        /// </summary>
        /// <param name="strUserID"></param>
        /// <param name="user"></param>
        /// <param name="config"></param>
        public static void SyncUserFromWechat(string strUserID, ref SysAddressBookMember user, SysWechatConfig config)
        {
            var token     = WeChatCommonService.GetWeiXinToken(config.Id);
            var apiResult = MailListApi.GetMember(token, strUserID);
            IAddressBookService _addressBookServie = EngineContext.Current.Resolve <IAddressBookService>();
            var Nowtime = System.DateTime.Now;

            //没找到用户,直接新建
            if (user == null || user.Id == 0)
            {
                user = new SysAddressBookMember()
                {
                    Avatar          = apiResult.avatar,
                    AccountManageId = config.AccountManageId,
                    // CompanyID = apiResult.
                    Gender         = apiResult.gender,
                    UserId         = apiResult.userid,
                    WeiXinId       = apiResult.weixinid,
                    UserName       = apiResult.name,
                    Status         = 1,
                    Department     = JsonConvert.SerializeObject(apiResult.department),
                    EmployeeStatus = Innocellence.WeChat.Domain.ModelsView.AddressBookMemberView.EmployeeStatusEnum.U.ToString(),
                    Mobile         = apiResult.mobile,
                    Position       = apiResult.position,
                    Email          = apiResult.email,
                    CreateTime     = DateTime.Now,
                    DeleteFlag     = 0,
                    SubscribeTime  = Nowtime
                };

                _addressBookServie.Repository.Insert(user);
            }
            else
            {
                if (apiResult.errcode == ReturnCode_QY.请求成功)
                {
                    user.Avatar = apiResult.avatar;
                }

                user.Status        = 1;
                user.SubscribeTime = Nowtime;
                _addressBookServie.UpdateMember(user);
            }
        }
示例#4
0
        /// <summary>
        /// 根据指定id, 返回该id 对应的user的前后各10条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetUserHistory(int id, int appId, int pageSize, int pageNumber, bool hiddenAutoReply)
        {
            try
            {
                _Logger.Debug("get user {0}'s history in {1} between {2} and {3}", id, appId, pageSize, pageNumber);
                var list = _requestMessageLogService.GetRecords <WechatUserRequestMessageLogView>(id, appId, pageSize, pageNumber);
                foreach (var a in list)
                {
                    if (a.ContentType == 106)
                    {
                        //var  a.Content
                        Regex listRegex = new Regex("\"Url\":\"((http[s]?://.*?)/.*?wxdetail/(\\d+).*?)\"", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                        //得到匹配的数据集合
                        MatchCollection mc = listRegex.Matches(a.Content);
                        foreach (Match mt in mc)
                        {
                            a.Content = a.Content.Replace(mt.Groups[1].Value, string.Format("{0}/WechatMain/Message/GetNews?id={1}&subid=0&code=0", mt.Groups[2].Value, mt.Groups[3].Value));
                        }
                    }
                }


                var accountManage = WeChatCommonService.GetWeChatConfigByID(appId);
                var config        = WeChatCommonService.GetWeChatConfigByID(appId);
                if (accountManage != null)
                {
                    //企业号
                    if (accountManage.IsCorp.HasValue && accountManage.IsCorp.Value)
                    {
                        SysAddressBookMember user = null;
                        list.ForEach(r =>
                        {
                            r.IsCrop = true;
                            if (user == null)
                            {
                                user = _addressBookService.GetMemberByUserId(r.UserID, true);
                            }
                            if (user != null)
                            {
                                //此处需要获取user的其他信息,因此头像直接从user中获取即可,可能会导致两处头像不一致
                                r.UserName            = user.UserName;
                                r.PhotoUrl            = user.Avatar;
                                r.Mobile              = user.Mobile;
                                r.EmployeeNo          = string.IsNullOrEmpty(user.EmployeeNo) ? string.Empty : user.EmployeeNo;
                                List <int> departMent = JsonConvert.DeserializeObject <int[]>(user.Department).ToList();
                                string[] departMents  = WeChatCommonService.lstDepartment(config.AccountManageId.Value).Where(d => departMent.Contains(d.id)).Select(d => d.name).ToArray();
                                r.Department          = string.Join(",", departMents);
                                r.AppLogo             = config.CoverUrl;
                            }
                        });
                    }
                    else //服务号
                    {
                        WechatMPUserView user = null;
                        list.ForEach(r =>
                        {
                            r.IsCrop = false;
                            if (user == null)
                            {
                                user = _wechatMPUserService.GetUserByOpenId(r.UserID);
                            }
                            if (user != null)
                            {
                                r.PhotoUrl = user.HeadImgUrl;
                            }
                            r.AppLogo = config.CoverUrl;
                        });
                    }
                }
                //if (hiddenAutoReply)
                //{
                //    list.RemoveAll(h => h.IsAutoReply == true);
                //}
                return(Json(
                           new
                {
                    list = list,
                    isFirst = pageNumber <0 ? pageSize> list.Count: false,
                    isLast = pageNumber > 0 ? pageSize > list.Count : false,
                },
                           JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                _Logger.Error(e);
                throw;
            }
        }
        private bool ValidateJustReceivedUser(string toDepartment, string toTag, string toUser, bool isCrop)
        {
            bool isVisible = false;

            try
            {
                if (isCrop)
                {
                    #region 企业号
                    SysAddressBookMember user = GetCropUser();
                    if (null != user)
                    {
                        if (!string.IsNullOrWhiteSpace(toDepartment))
                        {
                            if (!string.IsNullOrWhiteSpace(user.Department))
                            {
                                var userDepartment = JsonConvert.DeserializeObject <List <int> >(user.Department);
                                var newsDepartment = toDepartment.Split(',').ToList();
                                isVisible = newsDepartment.Any(x => userDepartment.Contains(int.Parse(x)));
                                log.Debug("user is {0} in department", isVisible ? string.Empty : "not");
                            }
                        }
                        if (!isVisible && !string.IsNullOrWhiteSpace(toTag))
                        {
                            if (!string.IsNullOrWhiteSpace(user.TagList))
                            {
                                var userTag = JsonConvert.DeserializeObject <List <int> >(user.TagList);
                                var newsTag = toTag.Split(',').ToList();
                                isVisible = newsTag.Any(x => userTag.Contains(int.Parse(x)));
                                log.Debug("user is {0} in tag", isVisible ? string.Empty : "not");
                            }
                        }
                        if (!isVisible && !string.IsNullOrWhiteSpace(toUser))
                        {
                            if (!string.IsNullOrWhiteSpace(user.UserId))
                            {
                                var newsDepartment = toUser.Split(',').ToList();
                                isVisible = newsDepartment.Contains(user.UserId);
                                log.Debug("user is {0} in sended user", isVisible ? string.Empty : "not");
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    #region  务号
                    var mpUser = GetMPUser();
                    if (null != mpUser)
                    {
                        if (!isVisible && !string.IsNullOrWhiteSpace(toTag))
                        {
                            if (!string.IsNullOrWhiteSpace(mpUser.TagIdList))
                            {
                                var userTag = mpUser.TagIdList.Split(',').ToList();
                                var newsTag = toTag.Split(',').ToList();
                                isVisible = newsTag.Any(x => userTag.Contains(x));
                                log.Debug("mpUser is {0} in tag", isVisible ? string.Empty : "not");
                            }
                        }
                        if (!isVisible && !string.IsNullOrWhiteSpace(toUser))
                        {
                            if (!string.IsNullOrWhiteSpace(mpUser.OpenId))
                            {
                                var newsDepartment = toUser.Split(',').ToList();
                                isVisible = newsDepartment.Contains(mpUser.OpenId);
                                log.Debug("mpUser is {0} in sended user", isVisible ? string.Empty : "not");
                            }
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return(isVisible);
        }