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,"备件消息","测试消息内容"));
    }
}
相关推荐
Resean02234 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
学长毕设5 小时前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
Flynt7 小时前
Spring AI Alibaba 真停更了?我把它的 GitHub 翻了个底朝天
java·spring·开源
夜郎king9 小时前
Shapefile 一键生成 GeoServer 样式:GeoTools + Spring Boot 实现 YSLD 自动生成器
spring boot·gis·geotools·ysld
她的男孩10 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
咖啡八杯11 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
北冥有鱼12 小时前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端
CoderYanger13 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第四弹):@ControllerAdvice 源码分析+案例代码
java·数据库·spring boot·后端·spring·java-ee·mybatis
玖米GEO运营王总监16 小时前
抖音和视频号算法区别:玖米快跑的双端分发信号与内容适配对比
java·前端·人工智能
AI人工智能+电脑小能手17 小时前
集合按大小切片分批,这个Java工具类5个方法含基本类型数组
java·工具类·批量处理·集合分片·分批调用