Java对接企业微信消息推送

  • Post author:
  • Post category:java

官方文档:开发前必读 – 接口文档 – 企业微信开发者中心

要实现消息推送前需要先获得企业微信的access_token,详细文档:获取access_token – 接口文档 – 企业微信开发者中心

请求方式: GET(HTTPS
请求地址: https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET

需要参数:

参数 说明
corpid 企业ID
corpsecret 应用的凭证密钥

代码:

    String corpid = "xxx";
    String corpsecret = "xxx";

    public static String getAccessToken() throws Exception {
        try {
            String result = HttpClientUtils.doGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken" + "?corpid=" + corpid + "&corpsecret=" + corpsecret);
            return result;
        }catch (Exception e){
            throw e;
        }
    }

返回结果:

{
   "errcode": 0,
   "errmsg": "ok",
   "access_token": "accesstoken000001",
   "expires_in": 7200
}

获取到了access_token,就可以开始推送消息了:

测试类:

入参:

格式 说明
ArrayList<String> users 接收人(最多支持1000个)
String test 发送的消息内容,最长不超过2048个字节,超过将截断**(支持id转译)**(换行请用“\n”,如需带超链接请用a标签,如:<a href=\”http://www.baidu.com\”>百度一下</a>)
/**
 * 发送文本消息
 */
public void wechatTest() throws Exception {
    // 接收人
    ArrayList<String> users = new ArrayList<>();
    users.add("23263");
    users.add("1");
    users.add("2");
    // 内容
    String test = "你的快递已到,请携带工卡前往邮件中心领取。
出发前可查看<a href="http://work.weixin.qq.com">邮件中心视频实况</a>,聪明避开排队。";
    String s = WechatUtils.textMessage(users, test);
}

工具类(WechatUtils.java):

请求方式:POST(HTTPS
请求地址: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN

    String token = "xxx";
 
   /**
     * 发送文本消息
     *
     * @param users 接收人
     * @param test  文本消息
     * @return 发送结果
     * @throws Exception 异常
     */
    public String textMessage(List<String> users, String test) throws Exception {
        JSONObject paramJson = new JSONObject();
        // 发送人或者发送消息为空
        if (StringUtils.isNullOrEmptyObject(users) && StringUtils.isEmpty(test)) {
            return "发送人或者发送消息为空,请检测!";
        }

        // 转换接收人为微信需要的格式
        String userTest = "";
        for (String user : users) {
            userTest += user + "|";
        }
        String result = "";

        try {
            // 标识发送文本消息
            JSONObject myText = new JSONObject();
            // 文本信息
            myText.put("content", test);
            paramJson.put("text", myText);

            // 接收人
            paramJson.put("touser", userTest.substring(0, userTest.length() - 1));
            paramJson.put("agentid", agentId);
            // 发送类型 test = 文本
            paramJson.put("msgtype", "text");

            // 发送消息
            // 请求方式:POST(HTTPS)
            result = HttpClientUtils.doPostNoSSL("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token, paramJson.toString());
        } catch (Exception e) {
            throw e;
        }
        return result;
    }

返回结果:

{
     "errcode":0,
     "errmsg":"ok",
     "invaliduser":"1|2",
     "msgid":"xxx"
}

结束


版权声明:本文为Ming_Mi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。