企业微信支持接口推送消息,包括文本、图片、视频等信息,对于业务来说,提示告警信息、推送会议信息可以使用
1、企业微信地址,注册账号,新建企业
创建应用,用来发送消息
企业创建后,添加企业关联人员
2、3个关键参数获取
CORPID:企业IDCORPSECRET:应用中的SecretAGENTID:消息发送应用iduserId:可选(参考标题3,默认@all)
3、发送到指定人员
1、发送消息给应用内全员
可见范围:点击编辑,添加可以接收到推送消息的人员,不在此处配置的,人员无法接收消息
2、指定用户发送
需要先完成第一步,把人员绑定到应用内,进一步筛选给那些用户发送消息
给指定人员发送消息,需要先获取用户账号,获取用户账号步骤如下
多个用户账号,用”|“隔开,如:"touser":"admin|admin1"
4、IP白名单配置
应用管理---应用--企业可信ip--配置
测试没有可用域名,使用白嫖方式
进入微信对话平台
新建个对话机器人,绑定企业微信发送应用
填入上图三个参数
配置服务器ip白名单(业务侧服务器公网地址)
5、接口文档
5.1 获取token
token 不要频繁获取,有效时间接口会返回,基本上默认是2个小时
5.2 发送文本消息
5.3 发送图文消息
1、上传临时素材
2、发送图片消息
6、程序代码
Java代码大同小异,知道应用配置方式和请求访问地址,网上到处是代码
1、发送文本信息和获取token
//发送消息的类型
private final static String MSGTYPE = "text";
//将消息发送给所有成员
private final static String TOPARTY = "@all";
//获取企业微信的企业号,根据不同企业更改
private final static String CORPID = "xx";
//获取企业应用的密钥,根据不同应用更改
private final static String CORPSECRET = "JaDgbh6HIAW47vpLL50Zj3hKRo2jYmaGIoc0nE_yrsM";
//获取访问权限码URL
private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
//创建会话请求URL
private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
public static void main(String[] args) {
/* System.out.println(getAccessToken());
String accToken = getAccessToken();*/
sendWeChatMessage("@all", "月落乌啼霜满天,我是你大哥", "xx");
}
public static void sendWeChatMessage(String toUser, String content, String ACCESS_TOKEN) {
//请求串
String url = CREATE_SESSION_URL + ACCESS_TOKEN;
JSONObject jsonObject = new JSONObject();
jsonObject.put("touser", toUser);
jsonObject.put("toparty", "@all");
jsonObject.put("totag", "@all");
jsonObject.put("msgtype", "text");
jsonObject.put("agentid", 1000002);
JSONObject contentJSon = new JSONObject();
contentJSon.put("content", content);
jsonObject.put("text", contentJSon);
jsonObject.put("safe", 0);
jsonObject.put("enable_id_trans", 0);
jsonObject.put("enable_duplicate_check", 0);
jsonObject.put("duplicate_check_interval", 1800);
try {
URL postUrl = new URL(url);
HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
http.setDoOutput(true);
http.setDoInput(true);
// 连接超时30秒
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
// 读取超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
//写入内容
OutputStream outputStream = http.getOutputStream();
outputStream.write(jsonObject.toJSONString().getBytes("UTF-8"));
InputStream inputStream = http.getInputStream();
int size = inputStream.available();
byte[] jsonBytes = new byte[size];
inputStream.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
JSONObject jsonObject1 = JSONObject.parseObject(result);
int errcode = jsonObject1.getInteger("errcode");
if (Objects.equals(42001, errcode)) {
System.out.println("token 失效");
}
if (Objects.equals(0, errcode)) {
System.out.println("消息发送成功");
}
System.out.println("请求返回结果:" + jsonObject1);
//清空输出流
outputStream.flush();
//关闭输出通道
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//获取access_token
public static String getAccessToken() {
//访问微信服务器
String url = ACCESS_TOKEN_URL + "?corpid=" + CORPID + "&corpsecret=" + CORPSECRET;
try {
URL getUrl = new URL(url);
//开启连接,并返回一个URLConnection对象
HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//将URL连接用于输入和输出,一般输入默认为true,输出默认为false
http.setDoOutput(true);
http.setDoInput(true);
//进行连接,不返回对象
http.connect();
//获得输入内容,并将其存储在缓存区
InputStream inputStream = http.getInputStream();
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
//将内容转化为JSON代码
String message = new String(buffer, "UTF-8");
JSONObject json = JSONObject.parseObject(message);
// token失效时间,需要避免频繁读取
int timeOut = json.getInteger("expires_in");
/* token.setAccess_token(json.getString("access_token"));
token.setExpires_in(new Integer(json.getString("expires_in")));*/
return json.getString("access_token");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//返回access_token码
return null;
}
2、发送图片信息
private final static String MSGTYPE = "text";
//将消息发送给所有成员
private final static String TOPARTY = "@all";
//获取企业微信的企业号,根据不同企业更改
private final static String CORPID = "";
//获取企业应用的密钥,根据不同应用更改
private final static String CORPSECRET = "";
//上传临时素材
private final static String MEDIA_UPLOAD_API = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=";
//创建会话请求URL
private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
public static void main(String[] args) {
sendWeChatMessage("@all","2#入侵告警","0uwJwqY7SxVh37aGe8NDdrpo1VS0BQic6JsjZ1jCbGYIxGaXPOZB-Bppg4AWUO3kCVIJ80q1NrfNuGlLv6gPlVkLgEzissd2pO4Y1szpa0FO-Oj6WylesbdufFRDRsWU4dgSuFHjZyJQW1uU0o1d6MtHzjvQcXotRAS2YK3JtXKiJpPcRKy4VEPKFLCCeoIZ1bMxQeCnTysjx3d82kAsNQ");
}
public static void sendWeChatMessage(String toUser, String content, String ACCESS_TOKEN) {
//请求串
String url = CREATE_SESSION_URL + ACCESS_TOKEN;
JSONObject jsonObject = new JSONObject();
jsonObject.put("touser", toUser);
jsonObject.put("toparty", "@all");
jsonObject.put("totag", "@all");
jsonObject.put("msgtype", "mpnews");
jsonObject.put("agentid", 1000002);
JSONArray jsonArray = new JSONArray();
JSONObject article = new JSONObject();
article.put("title", "告警信息");
article.put("thumb_media_id", "38oOKzvt-p0R83OBxRzJBhsYWsu5myZB8Vbej7g3-pplBI2Bz7XJz-q8DUZA_slbt");
article.put("author", "平台");
article.put("content_source_url", "URL");
article.put("content", content);
article.put("digest", "Digest description");
jsonArray.add(article);
JSONObject articles = new JSONObject();
articles.put("articles", jsonArray);
jsonObject.put("mpnews", articles);
jsonObject.put("safe", 0);
jsonObject.put("enable_id_trans", 0);
jsonObject.put("enable_duplicate_check", 0);
jsonObject.put("duplicate_check_interval", 1800);
try {
URL postUrl = new URL(url);
HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
http.setDoOutput(true);
http.setDoInput(true);
// 连接超时30秒
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
// 读取超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
//写入内容
OutputStream outputStream = http.getOutputStream();
outputStream.write(jsonObject.toJSONString().getBytes("UTF-8"));
InputStream inputStream = http.getInputStream();
int size = inputStream.available();
byte[] jsonBytes = new byte[size];
inputStream.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
JSONObject jsonObject1 = JSONObject.parseObject(result);
int errcode = jsonObject1.getInteger("errcode");
if (Objects.equals(42001, errcode)) {
System.out.println("token 失效");
}
if (Objects.equals(0, errcode)) {
System.out.println("消息发送成功");
}
System.out.println("请求返回结果:" + jsonObject1);
//清空输出流
outputStream.flush();
//关闭输出通道
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Tuple upload(String filePath, String token) throws Exception {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
log.error("发送企业微信的图片不存在");
return new Tuple(-1, null);
}
RestTemplate restTemplate = new RestTemplate();
// MultipartFile files = fileToMultipartFile(file);
URI uri = UriComponentsBuilder.fromHttpUrl(MEDIA_UPLOAD_API)
.queryParam("access_token", token)
.queryParam("type", "image")
.build().toUri();
InputStream inputStream = new FileInputStream(file);
String s = restTemplate.postForObject(uri, new InputStreamResource(inputStream), String.class);
JSONObject jsonObject = JSON.parseObject(s);
int errcode = jsonObject.getInteger("errcode");
return new Tuple(errcode, jsonObject.getString("media_id"));
}