企业微信消息推送对接,通过员工电话号码向员工发送消息

需求:企业微信消息推送对接,通过员工电话号码向员工发送消息。
主要逻辑就是:
1.先获取到企业微信的accessToken。(需要企业微信创建应用,就可以拿到应用的相关消息)。
2.通过accessToken + 电话号码 去调用企业微信的接口,获取userId。
3.通过accessToken + userId 调用企业微信接口发送消息。 消息模板可以自己选择,详见https://developer.work.weixin.qq.com/document/path/90236
效果如下:
在这里插入图片描述

//------------企业微信--------------
    @Value("${sms.qiyeweixin.corpid}")
    private String corpid;
    @Value("${sms.qiyeweixin.corpSecret}")
    private String corpSecret;
    @Value("${sms.qiyeweixin.agentid}")
    private String agentid;
      /**
     * @param mobile  企业微信员工的电话号码
     * @param content 需要向他发送的消息
     * @return ResponseVo
     */
    @Override
    public ResponseVo<String> sendByQiYeWeiXin(String mobile, String content) {
        // 1.获取到企微的token
        String accessToken = getWXAccessToken();

        // 2.获取到用户ID
        String userId = getUserId(accessToken, mobile);

        // 3.携带token发送消息
        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("touser", userId);
        requestBody.put("msgtype", "text");
        requestBody.put("agentid", agentid);

        Map<String, Object> textContent = new HashMap<>();
        textContent.put("content", content);
        requestBody.put("text", textContent);

        // 创建HttpEntity对象,封装请求头和请求体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
        JSONObject response = restTemplate.postForObject(url, requestEntity, JSONObject.class);

        System.out.println("响应结果:"+response);
        if (response != null && (Integer) response.get("errcode") == 0){
            log.info("发送成功");
            return ResponseVo.succ2("发送成功");
        }else {
            log.info("发送失败");
            return ResponseVo.succ2("发送失败");
        }
    }

    /**
     * 获取企业微信的accessToken
     */
    public String getWXAccessToken() {
        // 从Redis中获取access_token
        cn.hutool.json.JSONObject accessResult = (cn.hutool.json.JSONObject) redisUtil.get(CommonConstants.REDIS_QIYEWEIXIN_TOKEN + corpid);
        if (accessResult != null) {
            return accessResult.getStr("access_token");
        }
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

        // 构建请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("corpid", corpid);
        paramMap.put("corpsecret", corpSecret);

        // 发送GET请求获取access_token
        String response = HttpUtil.get(url, paramMap);
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(response);

        // 检查请求结果是否成功
        if (jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException("获取企业微信access_token失败:" + jsonObject.getStr("errmsg"));
        }

        // 将access_token存入Redis,并设置过期时间
        redisUtil.set(CommonConstants.REDIS_QIYEWEIXIN_TOKEN + corpid, jsonObject, jsonObject.getLong("expires_in"));

        System.out.println(jsonObject);
        return jsonObject.getStr("access_token");
    }

    /**
     * @param accessToken 企业微信的token
     * @param mobile      用户电话号码
     * @return String
     */
    public String getUserId(String accessToken, String mobile) {
        String GET_USERID_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid";
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mobile", mobile);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        Map<String, Object> response = restTemplate.postForObject(GET_USERID_URL + "?access_token=" + accessToken, requestEntity, Map.class);

        if (response != null && response.containsKey("userid")) {
            return (String) response.get("userid");
        } else {
            throw new RuntimeException("Failed to get UserId");
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值