springboot、java实现调用企业微信接口向指定用户发送消息

因为项目的业务逻辑需要向指定用户发送企业微信消息,所以在这里记录一下

目录

  • 引入相关依赖
  • 创建配置工具类
  • 创建发送消息类
  • 测试类
  • 最终效果

引入相关依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
dependency>

<dependency>
    <groupId>com.github.binarywanggroupId>
    <artifactId>weixin-java-cpartifactId>
    <version>4.0.8.Bversion>
dependency>
<dependency>
    <groupId>redis.clientsgroupId>
    <artifactId>jedisartifactId>
    <version>3.6.0version>
dependency>

其中,redis用于缓存token

创建配置工具类

@Component
public class WechatConfigUtil {
    // 要发送消息的应用的两个字段
    private static Integer agentId;
    private static String secret;
    // 企业id
    private static String corpId;
    // 用于访问redis的密码,没设置就不需要这个字段
    private static String redisPwd;

    @Value("${wx-cp-config.secret}")
    public void setSecret(String secret) {
        WechatConfigUtil.secret = secret;
    }

    @Value("${wx-cp-config.corpid}")
    public void setCorpId(String corpId) {
        WechatConfigUtil.corpId = corpId;
    }

    @Value("${wx-cp-config.redis-pwd}")
    public void setRedisPwd(String redisPwd) {
        WechatConfigUtil.redisPwd = redisPwd;
    }

    @Value("${wx-cp-config.agentid}")
    public void setAgentId(Integer agentId) {
        WechatConfigUtil.agentId = agentId;
    }

    /**
     * 配置企业微信服务
     * @return
     */
    public static WxCpService getWxCpService() {
        WxCpService wxCpService = new WxCpServiceImpl();
        WxCpDefaultConfigImpl config =new WxCpDefaultConfigImpl();
        config.setAgentId(agentId);
        config.setCorpSecret(secret);
        config.setCorpId(corpId);
        resetTokenAndJsApi(wxCpService, config);
        return wxCpService;
    }

    /**
     * 重置token
     * @param wxCpService
     * @param wxCpDefaultConfig
     */
    public static void resetTokenAndJsApi(WxCpService wxCpService, WxCpDefaultConfigImpl wxCpDefaultConfig) {

        Jedis jedis = new JedisPool().getResource();
        jedis.auth(redisPwd);
        wxCpService.setWxCpConfigStorage(wxCpDefaultConfig);
        String wxAccessToken = "wx"+agentId;
        String json = jedis.get(wxAccessToken);  // 根据应用id获取对应token
        if(!StringUtils.isEmpty(json)){
            wxCpDefaultConfig = JSON.parseObject(json, WxCpDefaultConfigImpl.class);
        }
        if(wxCpDefaultConfig.isAccessTokenExpired()){  // token到期
            try {
                String accessToken = null;
                accessToken =wxCpService.getAccessToken(false);
                wxCpDefaultConfig.setAccessToken(accessToken);
            }catch (WxErrorException e){
                e.printStackTrace();
            }
        }
        jedis.set(wxAccessToken, JSON.toJSONString(wxCpDefaultConfig));  // 缓存token
        jedis.close();
    }
}

这里把几个关键字段都做了application.yml文件配置注入值
@Value给静态变量赋值

# 企业微信配置(msg-url: 消息卡片点击后跳转网页,可配置OA登录网站)
wx-cp-config:
  corpid: xxx
  agentid: 123456
  secret: xxx
  redis-pwd: 123456

corpid需要你先以管理员身份创建一个企业,agentidsecret需要你创建一个应用获取

创建发送消息类

public class SendWxCpMsg {
    private static final Logger logger = LoggerFactory.getLogger(SendWxCpMsg.class);

    public static void sendToWxCp(String username) {
        //微信消息对象
        WxCpMessageServiceImpl wxCpMessageService = new WxCpMessageServiceImpl(WechatConfigUtil.getWxCpService());
        WxCpMessage wxCpMessage = new WxCpMessage();
        wxCpMessage.setSafe("0");
        wxCpMessage.setMsgType("textcard");  // 设置消息形式,这里设置为卡片消息

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time=sdf.format(new Date());
        //设置发送用户
        wxCpMessage.setToUser(username);
        //发送的标题
        wxCpMessage.setTitle("温馨提示");
        //发送内容
        wxCpMessage.setDescription("您的密码被检测为弱密码,请尽快修改!"
                +"\n"+"当前时间为:"
                +time+"\n"
                +"点击下方修改密码");
        //设置跳转url
        wxCpMessage.setUrl("https://developer.work.weixin.qq.com/tutorial/detail/53");
        wxCpMessage.setBtnTxt("前往修改");
        try {
            wxCpMessageService.send(wxCpMessage);  // 发送消息
        } catch (WxErrorException e) {
            logger.error("发送信息接口调用出错", e);
        }
    }
}

username字段就是企业微信通讯录中企业成员的userid

测试类

@SpringBootTest
public class WxMsgTest {
    @Test
    void test() {
        SendWxCpMsg.sendToWxCp("chenyx");
    }
}

最终效果

springboot、java实现调用企业微信接口向指定用户发送消息_第1张图片

参考文档:
官方应用消息接口文档
WxCpService文档

你可能感兴趣的:(Java,spring,boot,java,spring,boot,企业微信)