/// <summary> /// 缓存微信部门用户 /// </summary> private static void SaveWeiXinUserListCache(string key, WeiXinUserList token) { var data = token.ToJSON(); RedisHelper.SetForever(key, data); }
/// <summary> /// 服务器获取微信access_token /// </summary> private static void GetWeiXinUserList(bool init = false) { var nKey = nUserListLockKey + NotifyPlatformEnum.WorkWeiXin; if (init || ServerConfig.IsAnalysis && RedisHelper.SetIfNotExist(nKey, ServerConfig.GetLockValue)) { RedisHelper.SetExpireAt(nKey, DateTime.Now.AddMinutes(30)); var now = DateTime.Now; var weiXin = Configs.Where(x => !x.IsChat && x.Platform == NotifyPlatformEnum.WorkWeiXin).Where(x => !x.CorpId.IsNullOrEmpty() && !x.CorpSecret.IsNullOrEmpty() && !x.AgentId.IsNullOrEmpty()); var weiXinGroups = weiXin.GroupBy(x => new { x.CorpId, x.AgentId }).ToDictionary(x => x.Key); foreach (var(key, value) in weiXinGroups) { var corpId = key.CorpId; var agentId = key.AgentId; var tKey = $"{nRedisPre}:Token_{corpId}_{agentId}"; var token = GetWeiXinAccessToken(tKey); if (token.IsNullOrEmpty()) { continue; } var uKey = $"{nRedisPre}:UserList_{corpId}_{agentId}"; var userList = GetWeiXinUserListCache(uKey); var get = false; var refresh = false; if (userList != null) { if (userList.refreshed >= _interval) { refresh = true; } } else { get = true; } if (!get && !refresh) { continue; } var depIds = value.GroupBy(x => x.DepId).Select(x => x.Key); var nList = new WeiXinUserList(now); foreach (var depId in depIds) { try { //var url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist"; var url = "https://qyapi.weixin.qq.com/cgi-bin/user/list"; var f = HttpServer.Get(url, new Dictionary <string, string> { { "access_token", token }, { "department_id", depId.ToString() }, { "fetch_child", 0.ToString() }, }); if (f == "fail") { Log.Error($"GetWeiXinUserList 请求失败,url:{url}"); } else { f = HttpUtility.UrlDecode(f, Encoding.UTF8); var res = JsonConvert.DeserializeObject <WeiXinUserList>(f); if (res.errcode != 0) { Log.Error($"GetWeiXinUserList 返回失败,url:{url},返回码:{res.errcode},原因:{res.errmsg}"); } else { foreach (var user in res.userlist) { var u = nList.userlist.FirstOrDefault(x => x.userid == user.userid); if (u != null) { u.name = user.name; u.open_userid = user.open_userid; u.department = u.department.Concat(user.department).Distinct().OrderBy(x => x).ToList(); u.mobile = user.mobile; u.gender = user.gender; u.email = user.email; } else { nList.userlist.Add(user); } } } } } catch (Exception e) { Log.Error($"GetWeiXinUserList 失败,原因:{e.Message},错误:{e.StackTrace}"); } } //nList.userlist = nList.userlist.OrderBy(x => x.userid).ThenBy(x => x.name).ToList(); if (get) { SaveWeiXinUserListCache(uKey, nList); } else { userList.refresh = nList.refresh; SaveWeiXinUserListCache(uKey, userList); } } RedisHelper.Remove(nKey); } }