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,"备件消息","测试消息内容"));
    }
}
相关推荐
SamDeepThinking2 小时前
用工厂模式和模板方法统一封装所有第三方的Access Token
java·后端·架构
AI人工智能+电脑小能手2 小时前
【大白话说Java面试题】【Java基础篇】第17题:HashMap的加载因子为什么是0.75而不是1或0.5
java·开发语言·算法·哈希算法·散列表
huipeng9262 小时前
GateWay使用详解
java·spring boot·spring cloud·微服务·gateway
AKA__Zas2 小时前
初识多线程(初初识)
java·服务器·开发语言·学习方法
aLTttY2 小时前
Spring Boot + Redis 实战分布式锁:从入门到精通
spring boot·redis·分布式
wechatbot8882 小时前
企业微信管理系统:企业私域流量自动化运营api接口开发实战指南
运维·微信·自动化·企业微信·ipad
程序员老邢2 小时前
【重启日记】第五周复盘:持续突破高位,把 “平台期” 变成 “上升期”
java·运维·经验分享·ai·devops
weixin_419658312 小时前
RabbitMQ 应用问题
java·分布式·中间件·rabbitmq
Maiko Star2 小时前
跑通第一个Spring AI 应用
java·后端·spring·springai