项目需要开发一个消息推送插件,今天整理一下做一个记录。
消息推送插件实现了钉钉和企业微信推送消息的功能。
首先介绍的是钉钉的实现方式:
1.需要在钉钉后台创建一个应用,并且需要记录下agentId、appKey、appSecret三个值,具体的做法不会的请移步下面的链接;
钉钉开放平台:https://developers.dingtalk.com/document/;
2.获取钉钉的Token;
public static OapiGettokenResponse getToken(String appKey, String appSecret) {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest request = new OapiGettokenRequest();
request.setAppkey(appKey);
request.setAppsecret(appSecret);
request.setHttpMethod("GET");
try {
OapiGettokenResponse response = client.execute(request);
return response;
} catch (ApiException | com.taobao.api.ApiException e) {
e.printStackTrace();
}
return null;
}
3.获取钉钉用户信息;
public static OapiV2UserGetbymobileResponse getByMobile(String appKey, String appSecret,String phone) {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
req.setMobile(phone);
OapiGettokenResponse oapiGettokenResponse =getToken(appKey,appSecret);
String accessToken = oapiGettokenResponse.getAccessToken();
try {
OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);
return rsp;
} catch (ApiException | com.taobao.api.ApiException e) {
e.printStackTrace();
}
return null;
}
4.推送钉钉消息;
public static OapiMessageCorpconversationAsyncsendV2Response asyncsendV2(Integer agentId, String appKey, String appSecret, String user, String content) {
OapiV2UserGetbymobileResponse oapiV2UserGetbymobileResponse = getByMobile(appKey, appSecret,user);
if (!oapiV2UserGetbymobileResponse.isSuccess()) {
log.error(oapiV2UserGetbymobileResponse.getErrmsg());
return null;
}
OapiV2UserGetbymobileResponse.UserGetByMobileResponse result = oapiV2UserGetbymobileResponse.getResult();
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2")