1.设置企业微信后台,参考官网设置主要获取以下参数:(非真实参数)
agent-id: 1111111
secret: mxt34tutuututuutututuZUZJZi_6aIUY-C4gFG7ylmf
app-id: wx0123ac2c2c222333e
2.首先需要获取微信的token,注意:每两小时获取一次就好
@Value("${app.wei-xin.agent-id}")
public Integer agentId;
@Value("${app.wei-xin.secret}")
public String secret;
@Value("${app.wei-xin.app-id}")
public String appId;
//接口地址
public static String GET_ACCESS_TOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
//缓存微信token信息
public static String ACCESS_TOKEN = "";
/**
* 获取Token信息
*/
public void getAccessToken(){
HttpRequest httpRequest = new HttpRequest(GET_ACCESS_TOKEN);
httpRequest.setMethod(Method.GET);
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("corpid",appId);
paramsMap.put("corpsecret",secret);
httpRequest.form(paramsMap);
HttpResponse execute = httpRequest.execute();
boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
if(ok){
String body = execute.body(); // 获取响应主体
JSONObject jsonObject = JSONObject.parseObject(body);
if(jsonObject.getInteger("errcode") != 0){
log.info("获取getAccessToken-企业微信调用错误信息-------{}",body);
throw new AppException("企业微信获取Token失败");
}else{
//token 不合法40014
ACCESS_TOKEN = jsonObject.getString("access_token");
log.info("获取getAccessToken-------{}",ACCESS_TOKEN);
}
}else{
throw new AppException("企业微信获取Token异常");
}
}
//每两个小时自动更新一次Token信息
@Scheduled(fixedRate = 120 * 60 * 1000)
public void getAccessToken(){
getAccessToken();
}
3.如果是需要登录绑定微信的ID,获取微信用户ID的方法
//获取微信用户ID的接口
public static String GET_USER_ID = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo";
/**
* 获取用户ID信息
* @param code 前端传过来的code uid为业务用户表的UID
*/
public ResultVO getUserId(String code, String uid){
HttpRequest httpRequest = new HttpRequest(GET_USER_ID);
httpRequest.setMethod(Method.GET);
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("access_token",ACCESS_TOKEN);
paramsMap.put("code",code);
httpRequest.form(paramsMap);
HttpResponse execute = httpRequest.execute();
boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
if(ok){
String body = execute.body(); // 获取响应主体
JSONObject jsonObject = JSONObject.parseObject(body);
if(jsonObject.getInteger("errcode") == 0){
//绑定userId到用户表中
String userId = jsonObject.getString("userid");
// //绑定之前先检验是否存在重复绑定
// LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
// lambdaQueryWrapper.eq(User::getWxUserId,userId);
// lambdaQueryWrapper.eq(User::getIsDeleted,"present");
// User user = iUserMapper.selectOne(lambdaQueryWrapper);
// if(user != null){
// return ResultVO.fail("企业微信已绑定过用户【"+user.getName()+"】,不能连续绑定或者绑定多个系统用。");
// }
iUserMapper.updateWxUserId(uid,userId);
}else if(jsonObject.getInteger("errcode") == 40014){
//重新获取Token
getAccessToken();
getUserId(code,uid);
log.info("获取getUserId获取Token失败,重新获取Token后再次进行绑定:{}",body);
}else{
log.info("获取getUserId-------{}",body);
throw new AppException("企业微信获取Token失败:"+body);
}
}else{
throw new AppException("企业微信获取Token异常");
}
return ResultVO.success("绑定成功");
}
4.推送为企业微信消息
//企业微信推送消息接口
public static String POST_SEND_MESSAGE = "https://qyapi.weixin.qq.com/cgi-bin/message/send";
/**
* 发送消息 异步执行方法
* @param message 推送的消息信息
* @param userIds 微信用户ID多个使用逗号隔开
*/
@Async("asyncExecutor")
public void sendMessage(String message,String userIds){
HttpRequest httpRequest = new HttpRequest(POST_SEND_MESSAGE + "?access_token=" + ACCESS_TOKEN);
httpRequest.setMethod(Method.POST);
httpRequest.header("Content-Type", "application/json");
String data = "{\n" +
" \"touser\" : \""+userIds+"\",\n" +
" \"msgtype\" : \"text\",\n" +
" \"agentid\" : "+agentId+",\n" +
" \"text\" : {\n" +
" \"content\" : \"" + message + "\""+
" },\n" +
" \"safe\":0,\n" +
" \"enable_id_trans\": 0,\n" +
" \"enable_duplicate_check\": 0,\n" +
" \"duplicate_check_interval\": 1800\n" +
"}";
httpRequest.body(data);
HttpResponse execute = httpRequest.execute();
boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
if(ok){
// throw new AppException("企业微信获取Token异常");
String body = execute.body(); // 获取响应主体
JSONObject jsonObject = JSONObject.parseObject(body);
if(jsonObject.getInteger("errcode") == 0){
log.info("推送微信消息sendMessage成功:{}",body);
}else if(jsonObject.getInteger("errcode") == 40014){
//重新获取Token
getAccessToken();
sendMessage(message,userIds);
log.info("推送微信消息失败,【重新获取一次Token再次进行消息发送】:{}",body);
}else{
log.info("推送微信消息sendMessage失败:{}",body);
}
}else{
throw new AppException("企业微信获取Token异常");
}
}