这里前端只按照模板写了大概,样式什么的都极简了
一、登录钉钉开放平台,点击应用开发,先创建一个小程序
二、设置服务器公网出口ip名单,多个用“,”隔开,这个是设置所有访问服务端的客户端ip。这里需要复制AgentId、AppKey、AppSecret,后面需要用
三、添加开发人员
四、设置设置安全域名,这里是设置服务端的ip
六、java后台controller代码:把AgentId、AppKey、AppSecret这三个值换成自己的。目前已实现的有获取accessToken,获取用户信息,获取用户详细信息,发送消息通知,撤回消息通知。
我这边小程序的登录逻辑是:
package com.enter.net.system.sysadmin.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMediaUploadRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiMessageCorpconversationRecallRequest;
import com.dingtalk.api.response.OapiMediaUploadResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiMessageCorpconversationRecallResponse;
import com.enter.net.fhbusiness.cadre.model.VPersonalWorkDailyDD;
import com.enter.net.fhbusiness.cadre.service.VPersonalWorkDailyService;
import com.enter.net.frame.util.log.SystemControllerLog;
import com.enter.net.system.sysadmin.model.UserDD;
import com.enter.net.system.sysadmin.service.DDLoginService;
import com.enter.net.util.DDUtils;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*
* @Date: 2019年11月05日 下午2:03:02
*
* @Description: 钉钉登录-控制层
*
* @Version: 1.0
*
*/
@Controller
@RequestMapping(value="dd")
public class DDLoginController {
public DDLoginController() {
}
@Resource
DDLoginService dDLoginService;
@Resource
VPersonalWorkDailyService vPersonalWorkDailyService;
// 钉钉api相关
static String TOKEN_URL = "https://oapi.dingtalk.com/gettoken";
static String USER_INFO_URL = "https://oapi.dingtalk.com/user/getuserinfo";
static String USER_ALL_URL = "https://oapi.dingtalk.com/user/get";
private static String ACCESS_TOKEN = "";
private static String USER_ID = "";
private static Long AGENT_ID = ;
private static String AppKey = "";
private static String AppSecret = "";
private static String media_id = "";
/**
*
*
* @Date 2019年11月05日 下午2:02:17
* @Description 与钉钉服务器请求生成的accessToken
* @Fcunction getAccessToken
* @return JSONObject
*
*/
@ResponseBody
@RequestMapping("/getAccessToken")
@SystemControllerLog(description="与钉钉服务器请求生成的accessToken")
public JSONObject getAccessToken() {
JSONObject object = null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet accessToken = new HttpGet(TOKEN_URL + "?appkey=" + AppKey + "&appsecret=" + AppSecret); // 数据接口url
try {
HttpResponse response = httpclient.execute(accessToken);
HttpEntity entity = response.getEntity();
String temp = EntityUtils.toString(entity);
object = JSON.parseObject(temp); // 这里就是我们要的数据了。
ACCESS_TOKEN = object.getString("access_token");
} catch (IOException e) {
e.printStackTrace();
}
return object;
}
/**
*
*
* @Date 2019年11月05日 下午2:02:17
* @Description 根据token获取用户信息
* @Fcunction getUserInfo
* @param access_token
* @param code
* @return JSONObject
*
*/
@ResponseBody
@RequestMapping("/getUserInfo")
@SystemControllerLog(description="根据token获取用户信息")
public JSONObject getUserInfo(String access_token, String code) {
JSONObject object = null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet accessToken = new HttpGet(USER_INFO_URL + "?access_token=" + access_token + "&code=" + code); // 数据接口url
try {
HttpResponse response = httpclient.execute(accessToken);
HttpEntity entity = response.getEntity();
String temp = new String(EntityUtils.toString(entity).getBytes("ISO-8859-1"),"UTF-8");
object = JSON.parseObject(temp); // 这里就是我们要的数据了。
USER_ID = object.getString("userid");
} catch (IOException e) {
e.printStackTrace();
}
return object;
}
/**
*
*
* @Date 2019年11月05日 下午2:02:17
* @Description 根据token和用户id获取用户详细信息
* @Fcunction getUserAllInfo
* @param access_token
* @param userid
* @return JSONObject
*
*/
@ResponseBody
@RequestMapping("/getUserAllInfo")
@SystemControllerLog(description="根据token和用户id获取用户详细信息")
public JSONObject getUserAllInfo(String access_token, String userid) {
JSONObject object = null;
HttpClient httpclient = new DefaultHttpClient();
if (StringUtils.isBlank(access_token)) {
access_token = ACCESS_TOKEN;
}
if (StringUtils.isBlank(userid)) {
userid = USER_ID;
}
HttpGet accessToken = new HttpGet(USER_ALL_URL + "?access_token=" + access_token + "&userid=" + userid); // 数据接口url
try {
HttpResponse response = httpclient.execute(accessToken);
HttpEntity entity = response.getEntity();
String temp = new String(EntityUtils.toString(entity).getBytes("ISO-8859-1"),"UTF-8");
object = JSON.parseObject(temp); // 这里就是我们要的数据了。
} catch (IOException e) {
e.printStackTrace();
}
return object;
}
/**
*
*
* @Date 2019年11月05日 下午2:02:17
* @Description 查看是否关联数据库
* @Fcunction getRelationUser
* @param id_user
* @param name
* @return Map
*
*/
@ResponseBody
@RequestMapping(value = "/getRelationUser", method = RequestMethod.POST)
@SystemControllerLog(description="查看是否关联数据库")
public Map getRelationUser(String id_user, String name) {
Map map = new HashMap<>();
try {
map = dDLoginService.getRelationUser(DDUtils.getValue(id_user), DDUtils.getValue(name));
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
*
*
* @Date 2019年11月12日 下午2:02:17
* @Description 判断关联用户密码是否正确
* @Fcunction validatePassword
* @param id_user
* @param password
* @return boolean
*
*/
@ResponseBody
@RequestMapping(value = "/validatePassword", method = RequestMethod.POST)
@SystemControllerLog(description="判断关联用户密码是否正确")
public boolean validatePassword(String id_user, String password) {
boolean flag = false;
try {
flag = dDLoginService.validatePassword(DDUtils.getValue(id_user), DDUtils.getValue(password));
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
*
*
* @Date 2019年11月15日 下午2:02:17
* @Description 保存钉钉id和用户id到用户中间表
* @Fcunction saveUser
* @param id_user
* @param id_dd_user
* @return UserDD
*
*/
@ResponseBody
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
@SystemControllerLog(description="保存钉钉id和用户id到用户中间表")
public UserDD saveUser(String id_user, String id_dd_user) {
UserDD obj = null;
try {
obj = dDLoginService.saveUser(DDUtils.getValue(id_user), DDUtils.getValue(id_dd_user));
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
*
*
* @Date 2019年11月21日 下午2:02:17
* @Description 根据用户id查看子履职
* @Fcunction listPersonalWorkDailyByIdUser
* @param id_user
* @return List
*
*/
@ResponseBody
@RequestMapping(value = "/listPersonalWorkDailyByIdUser", method = RequestMethod.POST)
@SystemControllerLog(description="根据用户id查看子履职")
public List listPersonalWorkDailyByIdUser(String id_user,String month_) {
List list = null;
try {
list = vPersonalWorkDailyService.listPersonalWorkDailyByIdUser(DDUtils.getValue(id_user),DDUtils.getValue(month_));
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
*
*
* @Date 2020年04月14日 下午2:02:17
* @Description 发送消息
* @Fcunction sendMessage
* @param content
* @return OapiMessageCorpconversationAsyncsendV2Response
*
*/
@ResponseBody
@RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
@SystemControllerLog(description="发送消息")
public OapiMessageCorpconversationAsyncsendV2Response sendMessage(String content) throws UnsupportedEncodingException, ApiException {
if (!java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(content)) {//判断是不是GBK编码
content = new String(content.getBytes("ISO-8859-1"),"UTF-8");
}
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
request.setUseridList("manager6337");
// request.setUseridList("manager6337,15869175017659612");
request.setAgentId(AGENT_ID);
// request.setDeptIdList("1");
request.setToAllUser(false);
OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
msg.setMsgtype("text");
msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
msg.getText().setContent(content);
request.setMsg(msg);
// if (StringUtils.isBlank(media_id)) {
// uploadFile();
// }
// msg.setMsgtype("image");
// msg.setImage(new OapiMessageCorpconversationAsyncsendV2Request.Image());
// msg.getImage().setMediaId(media_id);
// request.setMsg(msg);
// msg.setMsgtype("file");
// msg.setFile(new OapiMessageCorpconversationAsyncsendV2Request.File());
// msg.getFile().setMediaId("@lADOdvRYes0CbM0CbA");
// request.setMsg(msg);
// msg.setMsgtype("link");
// msg.setLink(new OapiMessageCorpconversationAsyncsendV2Request.Link());
// msg.getLink().setTitle("test");
// msg.getLink().setText("test");
// msg.getLink().setMessageUrl("https://www.baidu.com");
// msg.getLink().setPicUrl("test");
// request.setMsg(msg);
// msg.setMsgtype("markdown");
// msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
// msg.getMarkdown().setText("##### text");
// msg.getMarkdown().setTitle("### Title");
// request.setMsg(msg);
// msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
// msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
// msg.getOa().getHead().setText("head");
// msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
// msg.getOa().getBody().setContent("xxx");
// msg.setMsgtype("oa");
// request.setMsg(msg);
// msg.setActionCard(new OapiMessageCorpconversationAsyncsendV2Request.ActionCard());
// msg.getActionCard().setTitle("xxx123411111");
// msg.getActionCard().setMarkdown("### 测试123111");
// msg.getActionCard().setSingleTitle("测试测试");
// msg.getActionCard().setSingleUrl("https://www.baidu.com");
// msg.setMsgtype("action_card");
// request.setMsg(msg);
request.setMsg(msg);
if (StringUtils.isBlank(ACCESS_TOKEN)) {
getAccessToken();
}
OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request, ACCESS_TOKEN);
return response;
}
/**
*
*
* @Date 2020年04月14日 下午2:02:17
* @Description 上传文件,获取MediaId
* @Fcunction uploadFile
*
*/
private void uploadFile() throws ApiException {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/media/upload");
OapiMediaUploadRequest request = new OapiMediaUploadRequest();
request.setType("image");
request.setMedia(new FileItem("C:\\Users\\dell\\Desktop\\06.png"));
OapiMediaUploadResponse response = client.execute(request,ACCESS_TOKEN);
if (0 == response.getErrcode()) {
media_id = response.getMediaId();
}
System.out.println(1);
}
/**
*
*
* @Date 2020年04月14日 下午2:02:17
* @Description 撤回消息
* @Fcunction reback
* @param taskId
* @return OapiMessageCorpconversationRecallResponse
*
*/
@ResponseBody
@RequestMapping(value = "/reback", method = RequestMethod.POST)
@SystemControllerLog(description="撤回消息")
public OapiMessageCorpconversationRecallResponse reback(Long taskId) throws ApiException {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/recall");
OapiMessageCorpconversationRecallRequest request = new OapiMessageCorpconversationRecallRequest();
request.setAgentId(AGENT_ID);
request.setMsgTaskId(taskId);
OapiMessageCorpconversationRecallResponse response = client.execute(request, ACCESS_TOKEN);
return response;
}
}
注:
(1)使用发送通知消息、撤回消息、上传文件需要导入jar包,可以下载官方的sdk解压添加到项目中。
(2)我这里jar包添加到项目中后,报java.lang.NoClassDefFoundError,把jar包放到项目所在tomcat\lib下解决。
(3)更多的api官方已经写得很详细了,参考官方开发文档