这里我准备了两种模板:文本卡片和文本两种
1.要获取AccessToken,这里使用的是Hutool工具执行发送请求AccessToken最好缓存起来使用有效期两小时
public static String getAccessToken() {
String body = HttpUtil.createGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=xxx&corpsecret=xxxx").execute().body();
JSONObject jsonObject = JSONObject.parseObject(body);
if (jsonObject.getInteger("errcode") != 0) {
throw new RuntimeException(jsonObject.getString("errmsg"));
}
return jsonObject.get("access_token").toString();
}
2.创建模板消息
/**
* @Version v1.0
* @Description 推送文本卡片消息到企业微信
* @author fbf
* @date 2023/6/30 11:27
*/
public static String sendTextAndCardMessage() {
Gson gson = new Gson();
Map<String, Object> map = new HashMap<>(5);
map.put("touser", "@all");
map.put("totag", "测试发消息");
map.put("msgtype", "textcard");
map.put("agentid", "1000000");
map.put("safe", "0 ");
map.put("enable_id_trans", "0");
map.put("enable_duplicate_check", "0");
map.put("duplicate_check_interval", "1800");
Map<String, Object> textcard = new HashMap<>(1);
textcard.put("title", "领奖通知");
textcard.put("url", "https://www.baidu.com");
textcard.put("description", "<div class=\"gray\">2023年6月29日</div> <div class=\"normal\">恭喜你抽中iPhone 18一台,领奖码:xxxx</div><div class=\"highlight\">请于2016年10月10日前联系行政同事领取</div>\"\n");
map.put("textcard", textcard);
String s = gson.toJson(map);
String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + ACCESS_TOKEN;
String data = HttpUtil.post(url, s);
return data;
}
/**
* @Version v1.0
* @Description 推送文本消息到企业微信
* @author fbf
* @date 2023/6/30 11:27
*/
public static String sendTextMessage() {
Gson gson = new Gson();
Map<String, Object> map = new HashMap<>(5);
map.put("touser", "@all");
map.put("totag", "测试发消息");
map.put("msgtype", "text");
map.put("agentid", "1000000");
map.put("safe", "0 ");
map.put("enable_id_trans", "0");
map.put("enable_duplicate_check", "0");
map.put("duplicate_check_interval", "1800");
Map<String, Object> content = new HashMap<>(1);
content.put("content", "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。");
map.put("text", content);
String s = gson.toJson(map);
String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + ACCESS_TOKEN;
String data = HttpUtil.post(url, s);
return data;
}