spring boot3集成企业微信推送消息

1、maven依赖

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.31</version>
</dependency>       

2、yml配置文件

复制代码
spring:
  data:
    redis:
      host: localhost
      port: 6379
      password: xxxxx
      jedis:
        pool:
          max-active: 18
      database: 2
wechat:
  appid: "xxxxx"
  corpid: "xxxxx"
  corpsecret: "xxxxx"
  jumpurl: http://xx.xx.xx.xx:8080
  wxtokenkey: "weChatToken"

3、新建redis缓存部分,IRedisService接口和实现类RedisServiceImpl

3.1 IRedisService接口

复制代码
public interface IRedisService {
    Boolean isContainKey(String key);

    // 加入元素
    void setValue(String key, String value);

    Object getValue(String key);
}

3.2 RedisServiceImpl实现类

复制代码
@Service
@Slf4j
public class RedisServiceImpl implements IRedisService {
    @Resource
    private RedisTemplate redisTemplate=null;

    @PostConstruct
    public void init(){
        RedisSerializer stringSerializer=this.redisTemplate.getStringSerializer();
        this.redisTemplate.setKeySerializer(stringSerializer);
        this.redisTemplate.setHashKeySerializer(stringSerializer);
        this.redisTemplate.setValueSerializer(stringSerializer);
        this.redisTemplate.setHashValueSerializer(stringSerializer);
    }

    @Override
    public Boolean isContainKey(String key) {
        Set<String> keys = redisTemplate.keys( "*");
        if(keys.contains(key)){
            return true;
        }
        return false;
    }

    @Override
    public void setValue(String key, String value) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        vo.set(key, value);
        redisTemplate.expire(key, 2, TimeUnit.HOURS); // 这里指的是2小时后失效
    }

    @Override
    public Object getValue(String key) {
        try {
            if(!isContainKey(key)){
                throw new BusinessException("key不存在");
            }
            ValueOperations<String, String> vo = redisTemplate.opsForValue();
            return vo.get(key);
        }catch (Exception ex){
            return null;
        }
    }
}

4、新建企业微信推送接口和实现类,IEnterpriseWeChatService和EnterpriseWeChatServiceImpl

4.1 IEnterpriseWeChatService接口

复制代码
public interface IEnterpriseWeChatService {
    String getWeChatToken();

    String sentMessageToWeChat(List<String> userAccounts, String title,String message);
}

4.2 EnterpriseWeChatServiceImpl实现类

复制代码
@Service
@Slf4j
public class EnterpriseWeChatServiceImpl implements IEnterpriseWeChatService {

    @Resource
    @Lazy
    private IRedisService redisService;

    @Value("${wechat.appid}")
    private String appId;
    @Value("${wechat.corpid}")
    private String corpId;
    @Value("${wechat.corpsecret}")
    private String corpSecret;
    @Value("${wechat.jumpurl}")
    private String jumpUrl;
    @Value("${wechat.wxtokenkey}")
    private String wxTokenKey;

    @Override
    public String getWeChatToken() {
        Object token = redisService.getValue(wxTokenKey);
        if(ObjectUtils.isNotEmpty(token)){
            return token.toString();
        }
        String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", corpId, corpSecret);
        String result = HttpUtil.get(url);
        JSONObject obj = JSONUtil.parseObj(result);
        token=obj.getStr("access_token");
        redisService.setValue(wxTokenKey, token.toString());
        return token.toString();
    }

    @Override
    public String sentMessageToWeChat(List<String> userAccounts, String title, String message) {
        if(CollectionUtils.isEmpty(userAccounts)){
            return "no_account";
        }
        String token = getWeChatToken();
        String apiUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s".formatted(token);

        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("title", title);
        contentMap.put("description", message);
        contentMap.put("url", jumpUrl);
        contentMap.put("btntxt", "查看详情");

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("touser", userAccounts.stream().collect(Collectors.joining("|")));   // 如 "LiSi" 或 "ZhangSan|LiSi"
        requestBody.put("msgtype", "textcard");
        requestBody.put("agentid", appId);
        requestBody.put("textcard", contentMap);

        // Hutool 发送 POST 请求
        return HttpUtil.post(apiUrl, JSONUtil.toJsonStr(requestBody));
    }
}

5、测试控制器测试

复制代码
@RestController
@RequestMapping("/enterpriseWeChat")
public class EnterpriseWeChatController {
    @Resource
    private IEnterpriseWeChatService enterpriseWeChatService;

    @GetMapping("/sentMessageToWeChat")
    public ResultMap sentMessageToWeChat(){
        List<String> userAccounts=List.of("zhangsan");
        return ResultMap.SUCCESS.setNewData(enterpriseWeChatService.sentMessageToWeChat(userAccounts,"备件消息","测试消息内容"));
    }
}
相关推荐
xieliyu.6 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
星辰徐哥6 小时前
Spring Boot 微服务架构设计与实现
spring boot·后端·微服务
星辰徐哥6 小时前
Spring Boot 数据导入导出与报表生成
spring boot·后端·ui
明夜之约6 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee6 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Micro麦可乐6 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
Jinkxs6 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
毕设源码_郑学姐6 小时前
计算机毕业设计springboot网络相册设计与实现 基于Spring Boot框架的在线相册管理系统开发与应用 Spring Boot驱动的网络影集设计与实践
spring boot·后端·课程设计
辣机小司6 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
一条小锦吕*6 小时前
基于Spring Boot + 数据可视化 + 协同过滤算法的推荐系统设计与实现(源码+论文+部署全讲解)
spring boot·算法·信息可视化