钉钉消息推送
进入钉钉开放平台,找到应用开发–>企业内部开发
获取到重要的三个参数
AgentId,AppKey,AppSecret
其次就是开启权限
一般是全部员工,然后,你想调用那个接口就申请那个权限。如果你不知道申请那个权限可以再他的官方文档里找,那里有提示。
因为这里是做的发送消息通知,那么就需要通讯录的权限,找到通讯录,把需要的都选了。
开发准备
引入dingtalk和alibaba-dingtalk-service-sdk
第一步获取access_token
dingtalk: #钉钉--消息通知
agentId: xxxxxxxx
appKey: xxxxxxxxxxxx
appSecret: xxxxxxxxxxxx
工具类
// 调用httpGet方法获得access_token的代码实现:
public static String getAccess_Token(String appkey, String appsecret) {
String url = "https://oapi.dingtalk.com/gettoken?" + "appkey=" + appkey + "&appsecret=" + appsecret;
JSONObject res = HttpHelper.httpGet(url);
String access_token = "";
if (res != null) {
access_token = res.getString("access_token");
} else {
new Exception("获取token异常");
}
return access_token;
}
第二步根据这个access_token就是获得了对应的接口凭证,现在根据api
DingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_by_mobile");
第三步根据req, accessToken去请求urid
OapiUserGetByMobileRequest req = new OapiUserGetByMobileRequest();
req.setMobile(mobile);
req.setHttpMethod("GET");
//根据req, accessToken去请求urid
OapiUserGetByMobileResponse rsp = client2.execute(req, accessToken);
//获取到Urid就是在公司里要发送到那个人的id
String urid = rsp.getUserid();
第四步根据用户id获取用户详情
//根据用户id获取用户详情
DingTalkClient userDetail = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
OapiUserGetRequest userReq = new OapiUserGetRequest();
userReq.setUserid(urid);
userReq.setHttpMethod("GET");
OapiUserGetResponse userRsp = userDetail.execute(userReq, accessToken);
String userName = userRsp.getName();
第五步发送消息
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
request.setUseridList(urid);
request.setAgentId(Long.valueOf(agentId));
request.setToAllUser(false);
第六步设置消息类型(OA)
OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
第七步消息体
//设置head
msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
msg.getOa().getHead().setText("待办事宜");
msg.getOa().getHead().setBgcolor("00409eff");
//设置body
msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
msg.getOa().getBody().setTitle("尊敬的 " + userName + "(项目经理)");
msg.getOa().getBody().setContent("待审批:"+sendMsg+"条"+"\n创建时间:" + sdf.format(new Date())+"");
//消息类型
msg.setMsgtype("oa");
request.setMsg(msg);
log.info("获取发送通知消息体和获取发送通知人完成");
OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request,accessToken);
log.info("发送消息是否成功"+response.isSuccess());
System.out.println(response.isSuccess());
log.info("消息任务ID"+response.getTaskId());
System.out.println(response.getTaskId());
s());
log.info(“消息任务ID”+response.getTaskId());
System.out.println(response.getTaskId());