企业微信发消息
简介
通过调用企业微信接口,给员工发消息
实现步骤
- 1.发送API(需要access_token)
https://open.work.weixin.qq.com/api/doc/90000/90135/90236#%E6%8E%A5%E5%8F%A3%E5%AE%9A%E4%B9%89 - 2.access_token获取(需要corpid和corpsecret)
https://work.weixin.qq.com/api/doc/90000/90135/91039 - 3.corpid获取
https://work.weixin.qq.com/api/doc/90000/90135/90665#corpid - 4.corpsecret获取(即secret)
https://work.weixin.qq.com/api/doc/90000/90135/90665#secret
其它功能
通过企业微信账号创建内部系统账号
@Override
public Result initUsers() {
// 通过部门ID查询用户信息
/**
* access_token:
* department_id: 部门ID
* fetchChild=1: 代表递归
*/
String accessToken = "调用接口返回的,自己取";
Map<String, String> deptMap = new HashMap<>();
// key: 企业微信部门ID,value:内部系统的分组ID
deptMap.put("7678", "32");
deptMap.put("7682", "32");
deptMap.put("7632", "32");
deptMap.put("7680", "99");
deptMap.put("7345", "33");
try {
List<UserLogin> userLogins = new ArrayList<>();
for (Map.Entry<String, String> m : deptMap.entrySet()) {
String findUserInfoByDept = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token="+accessToken+"&department_id="+m.getKey()+"&fetch_child=1";
// 获取响应信息
String result = HttpClientUtil.get(findUserInfoByDept, "UTF-8");
if(StringUtils.isNotBlank(result)) {
log.info("员工列表信息:{} ", result);
JSONObject jsonObject = JSONObject.parseObject(result);
String errMsg = jsonObject.getString("errmsg");
Integer errCode = jsonObject.getInteger("errcode");
if(errCode == 0 && "ok".equals(errMsg)) {
// 用户信息列表
JSONArray jsonArray = jsonObject.getJSONArray("userlist");
for(int i=0; i<jsonArray.size(); i++) {
JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
String userId = jsonObject1.getString("userid");
log.info("userId :{} ", userId);
String name = jsonObject1.getString("name");
log.info("name :{} ", name);
// 查询是否创建
if(userLoginRepository.findByUserLoginCode(userId) == null) {
UserLogin userLogin = new UserLogin();
Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(secret);
// 密码加了个密
userLogin.setPasswd(pbkdf2PasswordEncoder.encode(userId));
// 用户ID,即登陆账号(企业微信ID)
userLogin.setUserLoginCode(userId);
// 用户名(企业微信)
userLogin.setUserLoginName(name);
// 创建时间
userLogin.setGmtCreate(new Date());
// 最后修改时间
userLogin.setGmtModified(new Date());
// 创建人
userLogin.setCreator(1L);
// 修改人
userLogin.setModifier(1L);
// 内部系统分组ID,不考虑
userLogin.setGroupCode(m.getValue());
userLogins.add(userLogin);
} else {
log.info("用户「{}」已经创建", userId);
}
}
}
}
}
userLoginRepository.saveAll(userLogins);
} catch (Exception e) {
log.error("发生错误!", e);
return Result.fail(HttpStatusEnum.FAILED_DEPENDENCY);
}
return Result.success();
}