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,"备件消息","测试消息内容"));
    }
}
相关推荐
蛋蛋的就会顺顺的6 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣
需要8267 小时前
Spring Bean 生命周期:从实例化到销毁的完整钩子
java·后端·spring
小 黄 鸡7 小时前
HashMap 面试必会知识点详解(JDK 8)
java·面试·职场和发展
凤山老林8 小时前
Spring Boot 接入国密 SM2/SM3/SM4 的一些实践记录
spring boot·后端·python
伯恩bourne9 小时前
Spring Boot Bean 注册的两种方式:@Component 家族 vs @Configuration + @Bean
java·spring boot·后端
silvamux_9 小时前
curl 测试 OpenAI 兼容 API 的完整流程
java·人工智能·缓存·ai·oneapi
省钱兄--zs10 小时前
深圳24小时自助健身房软硬件解决方案实战指南与开发流程详解
java·数据仓库·spring boot·小程序·架构
顽疲10 小时前
Java vue 养老系统源码详解:月账单 care_month_bill 与 Quartz 扣费 Job 实践
java·开发语言·vue.js·vue养老·springboot养老·java养老
Wang's Blog10 小时前
Java 项目实战: 交友项目 - 安装开发工具与环境准备
java·开发语言·交友
用户212968352616810 小时前
开源了一个 Java 多智能体 LLM 框架 Baton:一个依赖,把 Agent 循环、工具调用、记忆、编排全配齐
java·llm