企业微信获取token 存入redis 设置时长2小时 && 发送企业应用消息接口
1.常量类
package com.ruoyi.common.constant;
/**
* 微信常用常量
* @author chenkai
*/
public class WeChatConstants {
/**
* 获取企业微信access_token地址
*/
public static final String BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
/**
* 获取企业微信部门地址
*/
public static final String DEPARTMENT_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/list";
/**
* 企业微信推送消息地址
*/
public static final String sendMessage_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
/**
* 获取企业微信access_token组装URL
*/
public static final String ACCESS_TOKEN_URL = BASE_URL + "?corpid=%s&corpsecret=%s";
/**
* 企业微信返回错误信息
*/
public static final String ERRCODE = "errcode";
/**
* 企业微信token redis key
*/
public static final String ACCESS_TOKEN = "access_token";
/**
* 企业微信agentSecret redis key
*/
public static final String AGENT_SECRET = "agent_secret";
/**
* 企业微信corpID redis key
*/
public static final String CORP_ID = "corp_id";
}
2.消息发送文本类
package com.ruoyi.system.domain.weChat;
import lombok.Data;
/**
* 消息发送文本
* @author chenkai
*/
@Data
public class TextMessage extends BaseMessage{
/** 文本*/
private Text text;
/** 否 表示是否是保密消息,0表示否,1表示是,默认0*/
private int safe;
}
3.企业微信发送基本参数类
package com.ruoyi.system.domain.weChat;
import lombok.Data;
/**
* @author chenkai
*/
@Data
public class BaseMessage {
/**否 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向该企业应用的全部成员发送*/
private String touser;
/**否 部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数*/
private String toparty;
/**否 标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数*/
private String totag;
/**是 消息类型*/
private String msgtype;
/**是 企业应用的id,整型。可在应用的设置页面查看*/
private int agentid;
}
4.文本类
package com.ruoyi.system.domain.weChat;
import lombok.Data;
/**
* 文本
* @author 15553051722
*/
@Data
public class Text {
/**是 消息内容,最长不超过2048个字节*/
private String content;
}
5.接受入参类
package com.ruoyi.system.domain.weChat.DTO;
import lombok.Data;
/**
* 企业微信发送消息实体类
* @author chenkai
*/
@Data
public class MessageDTO {
/**消息*/
private String content;
/**用户id*/
private String userid;
/**部门id*/
private String toparty;
}
6.实现类
package com.ruoyi.system.service.impl;
import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.WeChatConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.weChat.DTO.MessageDTO;
import com.ruoyi.system.domain.weChat.Text;
import com.ruoyi.system.domain.weChat.TextMessage;
import com.ruoyi.system.service.IEnterpriseWeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 企业微信实现类
* @author chenkai
*/
@Service
public class EnterpriseWeChatServiceImpl implements IEnterpriseWeChatService {
@Autowired
private RedisCache redisCache;
/**
* 发送应用消息
* 先从redis中获取 如获取不到或不可用 则重新获取
* 并存入redis设置时长2小时 因为每天获取token的次数是有限的
* @param messageDTO 消息内容 发送人 发送部门
* @return accessToken
*/
@Override
public void weCharMessage(MessageDTO messageDTO) {
if (StringUtils.isNull(messageDTO.getUserid())&&StringUtils.isNull(messageDTO.getToparty())){
throw new ServiceException("发送人或发送部门最少选一个");
}
String url = WeChatConstants.sendMessage_url.replace("ACCESS_TOKEN", this.getAccessToken());
// 2.获取发送对象,并转成json
Gson gson = new Gson();
Text text = new Text();
//发送消息实体
TextMessage textMessage = new TextMessage();
//非必需
textMessage.setTouser(messageDTO.getUserid());
textMessage.setToparty(messageDTO.getToparty());
//必须
textMessage.setAgentid(1000002);
//设置消息类型
textMessage.setMsgtype("text");
//存入消息文本
text.setContent(messageDTO.getContent());
//将消息文本存入实体
textMessage.setText(text);
String jsonMessage = gson.toJson(textMessage);
Map response = (Map) JSON.parse(HttpUtils.sendPost(url,jsonMessage));
//获取错误日志
if (response.containsKey(WeChatConstants.ERRCODE) && (Integer) response.get(WeChatConstants.ERRCODE) != 0) {
throw new ServiceException("消息发送失败", (Integer) response.get(WeChatConstants.ERRCODE));
}
}
/**
* 通过corpID获取AccessToken
*
* 从redis中获取accessToken如果为空
* 或者当前accessToken校验失败
* 则重新访问企业微信获取accessToken接口
* 并存入redis
* @return accessToken
*/
@Override
public String getAccessToken() {
//获取redis里的accessToken
String accessToken = redisCache.getCacheObject(getCacheKey(WeChatConstants.ACCESS_TOKEN));
//redis中有并且redis中的token可正常使用就返回redis中的token
//如果redis中没有 或者 redis中的token不可正常使用 则重新获取token
if (StringUtils.isNotEmpty(accessToken) && this.isToken(accessToken)) {
return accessToken;
}
//获取token必携带数据 corpId agentSecret 具体获取方法 查看企业微信api文档
//之前手动存入redis 组装redisKey 从redis中获取
String corpId = redisCache.getCacheObject(getCacheKey(WeChatConstants.CORP_ID));
String agentSecret = redisCache.getCacheObject(getCacheKey(WeChatConstants.AGENT_SECRET));
if (StringUtils.isEmpty(corpId) || StringUtils.isEmpty(agentSecret)) {
throw new ServiceException("企业ID和应用secret不能为空");
}
//将企业微信获取accessTokenURL组装
String getAccessTokenUrl = String.format(WeChatConstants.ACCESS_TOKEN_URL, corpId, agentSecret);
//将访问企业微信接口 返回的String数据 转换成map
Map response = (Map) JSON.parse(HttpUtils.sendGet(getAccessTokenUrl));
//获取错误日志
if (response.containsKey(WeChatConstants.ERRCODE) && (Integer) response.get(WeChatConstants.ERRCODE) != 0) {
throw new ServiceException("获取token失败", (Integer) response.get(WeChatConstants.ERRCODE));
}
//获取token 并存入redis 设置时间两个小时
accessToken = (String) response.get(WeChatConstants.ACCESS_TOKEN);
redisCache.setCacheObject(getCacheKey(WeChatConstants.ACCESS_TOKEN), accessToken, 2, TimeUnit.HOURS);
return accessToken;
}
/**
* 校验token访问企业微信接口是否成功
*
* @param accessToken 参数键
* @return 缓存键key
*/
private boolean isToken(String accessToken) {
Map department = (Map) JSON.parse(HttpUtils.sendGet(WeChatConstants.DEPARTMENT_URL, "access_token=" + accessToken));
if (department.containsKey(WeChatConstants.ERRCODE) && (Integer) department.get(WeChatConstants.ERRCODE) != 0) {
throw new ServiceException("token校验错误", (Integer) department.get(WeChatConstants.ERRCODE));
}
return true;
}
/**
* 设置cache key
*
* @param configKey 参数键
* @return 缓存键key
*/
private String getCacheKey(String configKey) {
return CacheConstants.SYS_CONFIG_KEY + configKey;
}
}