package com.lz.common.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.dingtalk.api.DefaultDingTalkClient; import com.dingtalk.api.DingTalkClient; import com.dingtalk.api.request.*; import com.dingtalk.api.response.*; import com.lz.modules.app.entity.StaffEntity; import com.lz.modules.app.entity.StaffOccupationEntity; import com.lz.modules.app.service.StaffOccupationService; import com.lz.modules.app.service.StaffService; import com.lz.modules.job.model.responseBo.DepartmentInfosBo; import com.lz.modules.job.model.responseBo.DepartmentStaffBo; import com.lz.modules.luck.entity.LuckRecord; import com.lz.modules.luck.service.LuckRecordService; import com.lz.modules.sys.entity.SysUserEntity; import com.lz.modules.sys.service.SysUserTokenService; import com.lz.modules.third.entity.ThirdAppConfig; import com.lz.modules.third.entity.ThirdMsgSendRecord; import com.lz.modules.third.service.ThirdAppConfigService; import com.lz.modules.third.service.ThirdMsgSendRecordService; import com.taobao.api.ApiException; import org.apache.http.impl.client.CloseableHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Component("dingtalkRobotUtil") public class DingTalkUtil { protected static Logger logger = LoggerFactory.getLogger(DingTalkUtil.class); @Autowired RedisUtils redisUtils; @Autowired ThirdAppConfigService thirdAppConfigService; @Autowired ThirdMsgSendRecordService thirdMsgSendRecordService; @Autowired StaffService staffService; @Autowired LuckRecordService luckRecordService; @Autowired private SysUserTokenService sysUserTokenService; @Autowired StaffOccupationService staffOccupationService; CloseableHttpClient getHttpClient(){ return null; } /** * 获取机器人的有效token值 * * @return * @throws IOException */ public String getAccessToken(String appid) { ThirdAppConfig thirdAppConfig = thirdAppConfigService.getByAppId(appid); return getAccessTokenWitchEntity(thirdAppConfig); } public String getAccessTokenWitchEntity(ThirdAppConfig thirdAppConfig) { try { if(thirdAppConfig != null){ DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken"); OapiGettokenRequest req = new OapiGettokenRequest(); req.setAppkey(thirdAppConfig.getAppKey()); req.setAppsecret(thirdAppConfig.getAppSecret()); req.setHttpMethod("GET"); OapiGettokenResponse rsp = client.execute(req); String resultStr = rsp.getBody(); logger.info("钉钉请求返回{}", rsp.getBody()); JSONObject dataObj = JSON.parseObject(resultStr); String tenant_access_token = dataObj.getString("access_token"); return tenant_access_token; }else{ logger.info("appid不存在,数据库未配置appid"); } } catch (Exception e) { e.printStackTrace(); logger.info("获取token异常{}", e); } return null; } /** * 批量获取部门详情 * * @param accessToken * @return */ public Map getDepartmentDetails(String accessToken, String departmentIds) { try { //下面获取所有部门的i就按单信息 Map list = new HashMap<>(); DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list"); OapiDepartmentListRequest req = new OapiDepartmentListRequest(); req.setFetchChild(true); req.setId("1"); req.setHttpMethod("GET"); OapiDepartmentListResponse rsp = client.execute(req, accessToken); logger.info("钉钉请求返回{}", rsp.getBody()); JSONObject json = JSONObject.parseObject(rsp.getBody()); if(json.getInteger("errcode") == 0){ JSONArray array = json.getJSONArray("department"); for (int i = 0; i < array.size(); i++){ json = array.getJSONObject(i); DepartmentInfosBo departmentInfosBo = new DepartmentInfosBo(); departmentInfosBo.setName(json.getString("name")); departmentInfosBo.setId(json.getString("id"));//自身ID departmentInfosBo.setParentId(json.getString("parentid"));//父级ID //下面获取详细信息 client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get"); OapiDepartmentGetRequest deReq = new OapiDepartmentGetRequest(); deReq.setId(departmentInfosBo.getId()); deReq.setHttpMethod("GET"); OapiDepartmentGetResponse deRsp = client.execute(deReq, accessToken); json = JSONObject.parseObject(deRsp.getBody()); departmentInfosBo.setChatId(json.getString("deptGroupChatId")); departmentInfosBo.setLeaderEmployeeId(json.getString("deptManagerUseridList"));//部门主管,多个主管以|隔开 departmentInfosBo.setStatus(1); departmentInfosBo.setOrder(json.getInteger("order")); list.put(departmentInfosBo.getId(), departmentInfosBo); } }else{ logger.info("获取部门详情异常{}", rsp.getBody()); } return list; } catch (Exception e) { logger.info("获取部门详情异常{}", e); } return null; } /** * 获取部门用户详情 * * @param accessToken * @return */ public List getDepartmentStaffDetails(String accessToken, String departmentId) { try { List list =new ArrayList<>(); DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage"); OapiUserListbypageRequest req = new OapiUserListbypageRequest(); req.setDepartmentId(Long.parseLong(departmentId)); req.setSize(100L); req.setHttpMethod("GET"); boolean isNext = true; for(long page = 0; isNext; page++){ req.setOffset(page); OapiUserListbypageResponse rsp = client.execute(req, accessToken); logger.info("钉钉请求返回{}", rsp.getBody()); JSONObject json = JSONObject.parseObject(rsp.getBody()); if(json.getInteger("errcode") == 0){ JSONArray array = json.getJSONArray("userlist"); isNext = json.getBoolean("hasMore");//获取是否由更多数据 for (int i = 0; i < array.size(); i++) { json = array.getJSONObject(i); DepartmentStaffBo departmentStaffBo = new DepartmentStaffBo(); departmentStaffBo.setEmployeeId(json.getString("userid"));//用户在企业内部的唯一编号,创建时可指定。可代表一定的含义 departmentStaffBo.setName(json.getString("name")); departmentStaffBo.setEmployeeNo(json.getString("jobnumber"));//工号 departmentStaffBo.setUnionId(json.getString("unionid"));//企业内部id,唯一 departmentStaffBo.setOpenId(json.getString("openId"));//和上面的值目前是一样的,未找到说明 departmentStaffBo.setMobile(json.getString("mobile"));//手机,需要单独授权手机权限 departmentStaffBo.setEmail(json.getString("email"));//邮箱,钉钉的企业邮箱才可以,需要单独授权手机权限 departmentStaffBo.setAvatar(json.getString("avatar"));//头像 departmentStaffBo.setPosition(json.getString("position")); departmentStaffBo.setStatus(0); /*if(json.getBoolean("active")){ //在职已激活 departmentStaffBo.setStatus(0); }else{ //在职未激活 departmentStaffBo.setStatus(4); }*/ if(json.getBoolean("isLeader")){ departmentStaffBo.setIsLeader(1); }else{ departmentStaffBo.setIsLeader(0); } list.add(departmentStaffBo); } }else{ logger.info("获取部门详情异常{}", rsp.getBody()); } } return list; } catch (Exception e) { e.printStackTrace(); logger.info("获取部门用户详情异常{}", e); } return null; } /** * 获取图片image_key * * @return * @throws IOException */ public String getImageKey(File file, String tenant_access_token) throws IOException { // File file = new File(imgUrl); String result = "";//SendImageByApacheHttpClient(file, tenant_access_token); JSONObject dataObj = JSON.parseObject(result); String image_key = dataObj.getJSONObject("data").getString("image_key"); return image_key; } /** * 获取飞书用户唯一标识 * * @param mobile * @param accessToken * @return */ public static String getUserId(String mobile, String accessToken) { String urlStr = "https://open.feishu.cn/open-apis/user/v1/batch_get_id?mobiles=" + mobile; String result = HttpUtil.feishuGet(urlStr, accessToken); JSONObject dataObj = JSON.parseObject(result); String userId = dataObj.getJSONObject("data").getJSONObject("mobile_users").getJSONArray(mobile).getJSONObject(0).getString("user_id"); return userId; } public static void main(String[] args) { DingTalkUtil dingTalkUtil = new DingTalkUtil(); String token = dingTalkUtil.getAccessToken("856016278"); } //发送钉钉消息 public String sendSingleActionCardMSG(String appid, StaffEntity staff, String title, String marDown, String singleTitle, String singleUrl, String token) { String msg = "OK"; ThirdMsgSendRecord thirdMsgSendRecord = new ThirdMsgSendRecord(); thirdMsgSendRecord.setMsgType("action_card"); thirdMsgSendRecord.setStaffId(staff.getId()); thirdMsgSendRecord.setMsgTitle(singleTitle); thirdMsgSendRecord.setAppId(Long.parseLong(appid)); thirdMsgSendRecord.setHeadText(title); thirdMsgSendRecord.setMsgContent(marDown); thirdMsgSendRecord.setMsgUrl(singleUrl); thirdMsgSendRecord.setStatus(0); try{ DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2"); OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request(); req.setAgentId(thirdMsgSendRecord.getAppId()); req.setUseridList(staff.getEmployeeId()); OapiMessageCorpconversationAsyncsendV2Request.Msg obj1 = new OapiMessageCorpconversationAsyncsendV2Request.Msg(); obj1.setMsgtype(thirdMsgSendRecord.getMsgType()); OapiMessageCorpconversationAsyncsendV2Request.ActionCard obj2 = new OapiMessageCorpconversationAsyncsendV2Request.ActionCard(); obj2.setSingleUrl(thirdMsgSendRecord.getMsgUrl()); obj2.setSingleTitle(thirdMsgSendRecord.getMsgTitle()); obj2.setMarkdown(thirdMsgSendRecord.getMsgContent()); obj2.setTitle(thirdMsgSendRecord.getHeadText()); obj1.setActionCard(obj2); req.setMsg(obj1); OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, token); logger.info("钉钉请求返回{}", rsp.getBody()); //插入数据库 JSONObject json = JSONObject.parseObject(rsp.getBody()); if(json.getIntValue("errcode") == 0){ thirdMsgSendRecord.setTaskId(json.getLong("task_id")); thirdMsgSendRecord.setStatus(1); }else{ thirdMsgSendRecord.setTaskId(0L); thirdMsgSendRecord.setStatus(6); thirdMsgSendRecord.setRemark(json.getString("errmsg")); msg = thirdMsgSendRecord.getRemark(); } }catch (ApiException e) { e.printStackTrace(); thirdMsgSendRecord.setStatus(6); thirdMsgSendRecord.setRemark(e.getErrMsg()); msg = thirdMsgSendRecord.getRemark(); } thirdMsgSendRecordService.insert(thirdMsgSendRecord); return msg; } //发送待办任务 public String sendSingleWorkMSG(String appid, StaffEntity staff, String title, String marDown, String singleTitle, String singleUrl, String token) { String msg = "OK"; ThirdMsgSendRecord thirdMsgSendRecord = new ThirdMsgSendRecord(); thirdMsgSendRecord.setMsgType("work_msg"); thirdMsgSendRecord.setStaffId(staff.getId()); thirdMsgSendRecord.setMsgTitle(singleTitle); thirdMsgSendRecord.setAppId(Long.parseLong(appid)); thirdMsgSendRecord.setHeadText(title); thirdMsgSendRecord.setMsgContent(marDown); thirdMsgSendRecord.setMsgUrl(singleUrl); thirdMsgSendRecord.setStatus(0); try{ DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/workrecord/add"); OapiWorkrecordAddRequest req = new OapiWorkrecordAddRequest(); req.setUserid(staff.getEmployeeId()); req.setCreateTime(System.currentTimeMillis()); req.setTitle(singleTitle); req.setUrl(singleUrl); List list2 = new ArrayList(); OapiWorkrecordAddRequest.FormItemVo obj3 = new OapiWorkrecordAddRequest.FormItemVo(); list2.add(obj3); obj3.setTitle(title); obj3.setContent(marDown); req.setFormItemList(list2); OapiWorkrecordAddResponse rsp = client.execute(req, token); logger.info("钉钉待办任务请求返回{}", rsp.getBody()); //插入数据库 JSONObject json = JSONObject.parseObject(rsp.getBody()); if(json.getIntValue("errcode") == 0){ thirdMsgSendRecord.setTaskId(json.getLong("record_id")); thirdMsgSendRecord.setStatus(1); }else{ thirdMsgSendRecord.setTaskId(0L); thirdMsgSendRecord.setStatus(6); thirdMsgSendRecord.setRemark(json.getString("errmsg")); msg = thirdMsgSendRecord.getRemark(); } logger.info("发送消息{}", thirdMsgSendRecord); }catch (ApiException e) { e.printStackTrace(); thirdMsgSendRecord.setStatus(6); thirdMsgSendRecord.setRemark(e.getErrMsg()); msg = thirdMsgSendRecord.getRemark(); } thirdMsgSendRecordService.insertThirdMsgSendRecord(thirdMsgSendRecord); return msg; } public R getUserIdByCode(String code, String token) { try { DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo"); OapiUserGetuserinfoRequest req = new OapiUserGetuserinfoRequest(); req.setCode(code); req.setHttpMethod("GET"); OapiUserGetuserinfoResponse rsp = client.execute(req, token); logger.info("钉钉请求返回{}", rsp.getBody()); JSONObject json = JSONObject.parseObject(rsp.getBody()); if(json.getIntValue("errcode") == 0){ String employeeId = json.getString("userid"); StaffEntity staffEntity = staffService.selectStaffByEmployeeId(employeeId); if(staffEntity != null){ StaffOccupationEntity staffOccupationEntity = staffOccupationService.getStaffOccupationByStaffId(staffEntity.getId()); if(staffOccupationEntity != null && staffOccupationEntity.getStaffStatus() == 0){ //登录操作 SysUserEntity user = new SysUserEntity(); user.setPassword(staffEntity.getPassword()); user.setMobile(staffEntity.getMobile()); user.setUserId(staffEntity.getId()); user.setEmail(staffEntity.getEmail()); user.setSalt(staffEntity.getSalt()); user.setStatus(1); user.setType(1); user.setRealName(staffEntity.getName()); user.setUsername(staffEntity.getMobile()); user.setUserNo(staffEntity.getMobile()); return sysUserTokenService.createTokenSetTokenCode(user, code); } } return R.error("用户不存在"); } return R.error("请求钉钉异常:" + json.getString("errmsg")); } catch (ApiException e) { e.printStackTrace(); return R.error(e.getErrMsg()); } } public R luck(String code, String token, Long luckId) { try { DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo"); OapiUserGetuserinfoRequest req = new OapiUserGetuserinfoRequest(); req.setCode(code); req.setHttpMethod("GET"); OapiUserGetuserinfoResponse rsp = client.execute(req, token); JSONObject json = JSONObject.parseObject(rsp.getBody()); if(json.getIntValue("errcode") == 0){ String employeeId = json.getString("userid"); StaffEntity staffEntity = staffService.selectStaffByEmployeeId(employeeId); if(staffEntity != null){ LuckRecord luckRecord = luckRecordService.selectLuckRecordByLuckIdAndStaffId(luckId, staffEntity.getId()); if(luckRecord == null){//插入抽奖记录 luckRecord = new LuckRecord(); luckRecord.setStaffId(staffEntity.getId()); luckRecord.setLuckId(luckId); luckRecord.setName(staffEntity.getName()); luckRecord.setMobile(staffEntity.getMobile()); luckRecordService.insertLuckRecord(luckRecord); } //登录操作 return R.ok(); } return R.error("用户不存在"); } return R.error("请求钉钉异常:" + json.getString("errmsg")); } catch (ApiException e) { e.printStackTrace(); return R.error(e.getErrMsg()); } } }