/**
* 获取所有部门列表
* @param accessToken
* @param id
* @return 部门列表
*/
@SneakyThrows
public List<WeChatDeptDto> getDeptList(String accessToken, String id) {
List<WeChatDeptDto> list = null;
/**
* redis中为获取到accessToken,从企业微信服务器获取
*/
//https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN&id=ID
String path = "/cgi-bin/department/list";
String method = "GET";
Map<String, String> headers = new HashMap<String, String>();
Map<String, String> querys = new HashMap<String, String>();
querys.put("access_token", accessToken);
if(!StringUtil.isEmpty(id)){
querys.put("id", id);//部门id。获取指定部门及其下的子部门(以及及子部门的子部门等等,递归)。 如果不填,默认获取全量组织架构
}
host = getCurrentHost();
HttpResponse httpResponse = HttpUtil.doGet(host, path, method, headers, querys);
String response = EntityUtils.toString(httpResponse.getEntity());
if (StringUtils.isEmpty(response)) {
throw new RuntimeException("企业微信AccessToken获取失败!");
}
JSONObject json = JSON.parseObject(response);
try {
String errcode = json.getString("errcode");
String department = json.getString("department");
logger.info("errcode = {}, department = {}", errcode, department);
list = JSONUtil.toList(JSONUtil.parseArray(department), WeChatDeptDto.class);
} catch (Exception e) {
String error = String.format("获取token失败 errcode: %s ,errmsg: %s", json.getInteger("errcode"),
json.getString("errmsg"));
logger.info(error);
throw new RuntimeException(e);
}
return list;
}
/**
* 异步更新微信同步用户部门信息,最好分页处理,目前采用全部处理方式
* @param deptList 部门列表
* @param userIdList 用户ID列表
*/
private void asynBatchUserDeptPath(List<WeChatDeptDto> deptList, List<String> userIdList){
long st = System.currentTimeMillis();
//int count = userMapper.findAllUserCount();
LOGGER.info("开始更新同步企业微信人员部门信息---------->>>,用户总数:{} , 部门总数: {}", userIdList.size(), deptList.size());
//获取用户详情
//List<String> list = userMapper.findAllUserId();
String accessToken = weiChatService.getAccessToken(true);
for (int i = 0; i < userIdList.size(); i++) {
if(i % 500 == 0){
accessToken = weiChatService.getAccessToken(false);
}
String userId = userIdList.get(i);
WeChatDeptUserInfoDto userInfoDto = weiChatService.getDeptUserInfo(accessToken, userId);
if(null != userInfoDto) {
String deptPath = "";
List<Integer> ids = userInfoDto.getDepartment();
//Collections.sort(ids);
for (Integer id : ids) {//如果是多个,需要改为只取最大值,目前沟通得知此处只有一个值
try{
deptPath = getdmptNames(deptList, id, userInfoDto.getName());
break;
}catch (Exception e){
e.printStackTrace();
}
}
LOGGER.info("更新人员部门信息,name = {}, userId = {}, deptPath = {}, ids.size = {}", userInfoDto.getName(), userId, deptPath, ids.size());
if(null != deptPath && !StringUtil.isEmpty(userId)){
//更新用户部门信息,入库
}
}
}
//userIdList.forEach(userId -> { });
LOGGER.info("结束更新同步企业微信人员部门信息---------->>>,用户总数:{} ,共耗时: {} 秒", userIdList.size(), (System.currentTimeMillis() - st)/1000);
}
private String getdmptNames(List<WeChatDeptDto> deptList, Integer id, String userName) {
String str = "";
String name = null;
WeChatDeptDto department = null;
if(deptList.stream().filter(e -> id.equals(e.getId())).count() > 0){
department = deptList.stream().filter(e -> id.equals(e.getId())).findFirst().get();
}
if(null == department){
LOGGER.error("用户查询到的部门权限为空: userName = {}, dept = {}", userName, id);
return str;
}
Integer pid = department.getParentid();
name = department.getName();//根据id得到部门名称和父id
if (pid == 0 || pid == 1) {
str = name + "\\";
}
while (pid != 0 && pid != 1) { //当父id不为1时候,循环,父id为“1”时候表示已经取到最顶层“微信企业号”了
str = name + "\\" + str; //拼接部门:海康威视/维修工程部/生产计划与控制室 /
pid = department.getParentid(); //得到父id
final Integer currentId = pid;
if(deptList.stream().filter(e -> currentId.equals(e.getId())).count() > 0){
department = deptList.stream().filter(e -> currentId.equals(e.getId())).findFirst().get(); //根据父id再取上一层部门
name = department.getName(); //重新赋值给name
if(pid == 0 || pid == 1){
str = name + "\\" + str;
}
}else {
break;
}
}
str = str.substring(0, str.length() - 1); //去除最后一个“/”:海康威视/维修工程部/生产计划与控制室
return str;
}
//获取token
public String getAccessToken(boolean bool) {
String accessToken = null;
if(bool){//true表示从redis获取,false表示重新获取token
accessToken = redisTemplate.opsForValue().get("WeiChat_AccessToken");
if (!StringUtil.isEmpty(accessToken)) {
return accessToken;
}
}
// 发送http请求企业微信服务器,获取AccessToken
String path = "/cgi-bin/gettoken";
String method = "GET";
Map<String, String> headers = new HashMap<String, String>();
Map<String, String> querys = new HashMap<String, String>();
// 从数据库查询corpid、corpsecret
if (!redisTemplate.hasKey(SecurityConstant.EXT_APP_CONFIG)) {
throw new RuntimeException("第三方接入配置获取失败,请重新配置!");
}
ExternalAccessConfig config = JSONUtil.toBean(redisTemplate.opsForValue().get(SecurityConstant.EXT_APP_CONFIG), ExternalAccessConfig.class);
if (StringUtils.isEmpty(config.getExtAppId())) {
throw new RuntimeException("corpid获取失败,请重新配置!");
}
if (StringUtils.isEmpty(config.getExtSecret())) {
throw new RuntimeException("corpid获取失败,请重新配置!");
}
querys.put("corpid", config.getExtAppId().trim());
querys.put("corpsecret", config.getExtSecret().trim());
host = getCurrentHost();
HttpResponse httpResponse = HttpUtil.doGet(host, path, method, headers, querys);
String response = EntityUtils.toString(httpResponse.getEntity());
if (StringUtils.isEmpty(response)) {
throw new RuntimeException("企业微信AccessToken获取失败!");
}
JSONObject json = JSON.parseObject(response);
try {
// 将token信息保存到redis中,并设置过期时间
accessToken = json.getString("access_token");
//String ExpirationTime = json.getString("expires_in");
redisTemplate.opsForValue().set("WeiChat_AccessToken", accessToken, 3600, TimeUnit.SECONDS);
// 打印消息
String message = String.format("获取token成功 access token: %s, expire_in: %s", json.getString("access_token"),
json.getInteger("expires_in"));
logger.info(message);
return accessToken;
} catch (Exception e) {
String error = String.format("获取token失败 errcode: %s ,errmsg: %s", json.getInteger("errcode"),
json.getString("errmsg"));
logger.info(error);
throw new RuntimeException(e);
}
}
//部门实体
@data
public class WeChatDeptDto {
private Integer id;
private String name;
private String name_en;
private Integer parentid;//父部门id。根部门为1
private Integer order;
}
|