公司内部交流使用的企业微信,最近项目中要实现向员工发送企业微信通知,于是看了下企业微信的api,简单实现了下:
1. 其实就是一个HTTP请求,如下
请求方式:POST(HTTPS)
请求地址: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
文本消息请求参数实例如下
{
"touser" : "UserID1|UserID2|UserID3",//用户的ID,
"toparty" : "PartyID1|PartyID2",//部门id
"totag" : "TagID1 | TagID2",//标签id
"msgtype" : "text",//消息类型
"agentid" : 1,//应用的ID,比如时公告还是通知什么一类的,可参考企业微信开发者文档
"text" : {//类型和内容
"content" : "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
},
"safe":0//是否保密信息
}
- //其中 touser、toparty、totag不能同时为空
其他如图片类型,语音则可以参考开发者文档中的类型对应设置
2. 获取access_token
请求方式:GET(HTTPS)
请求URL:https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRECT
注:此处标注大写的单词ID和SECRET,为需要替换的变量,根据实际获取值更新。
public String getToken(String corpId, String corpSecret) throws IOException {
SendMsgService sw = new SendMsgService();
UrlData uData = new UrlData();
uData.setGetTokenUrl(corpId, corpSecret);
String resp = sw.toAuth(uData.getGetTokenUrl());//就是按照GET方式拼接了字符串得到url
Map<String, Object> map = gson.fromJson(resp,
new TypeToken<Map<String, Object>>() {
}.getType());
System.out.println(map);
return map.get("access_token").toString();
}
protected String toAuth(String Get_Token_Url) throws IOException {
httpClient = HttpClients.createDefault();
httpGet = new HttpGet(Get_Token_Url);
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(response.toString());
String resp;
try {
HttpEntity entity = response.getEntity();
System.out.println(response.getAllHeaders());
resp = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
} finally {
response.close();
}
return resp;
}
3. POST请求
public String post(String charset, String contentType, String url, String data, String token) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
httpPost = new HttpPost(url + token);
httpPost.setHeader(CONTENT_TYPE, contentType);
httpPost.setEntity(new StringEntity(data, charset));
CloseableHttpResponse response = httpclient.execute(httpPost);
String resp;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, charset);
EntityUtils.consume(entity);
} finally {
response.close();
}
return resp;
}
//其中data是请求的json数据
public String createPostData(String touser, String msgtype, int agent_id, String contentKey, String contentValue) {
WeChatData weChatData = new WeChatData();
weChatData.setTouser(touser);
weChatData.setAgentid(agent_id);
weChatData.setMsgtype(msgtype);
Map<Object, Object> content = new HashMap<Object, Object>();
content.put(contentKey, contentValue + "\n--------\n" + df.format(new Date()));
weChatData.setText(content);
System.out.println(gson.toJson(weChatData));
return gson.toJson(weChatData);
}
其实企业微信开发者文档就是给我们提供了接口,我们要做的只是封装好我们的请求json,请求对应的接口就可以了。