package com.hotent.system.controller; import com.dingtalk.api.DefaultDingTalkClient; import com.dingtalk.api.DingTalkClient; import com.dingtalk.api.request.OapiSnsGetuserinfoBycodeRequest; import com.dingtalk.api.request.OapiUserGetbyunionidRequest; import com.dingtalk.api.response.OapiSnsGetuserinfoBycodeResponse; import com.dingtalk.api.response.OapiUserGetbyunionidResponse; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.hotent.base.annotation.ApiGroup; import com.hotent.base.constants.ApiGroupConsts; import com.hotent.base.controller.BaseController; import com.hotent.base.exception.BaseException; import com.hotent.base.model.CommonResult; import com.hotent.base.query.PageList; import com.hotent.base.query.QueryFilter; import com.hotent.base.util.*; import com.hotent.system.consts.DingTalkConsts; import com.hotent.system.consts.FlyBookConsts; import com.hotent.system.consts.WeChatOffAccConsts; import com.hotent.system.consts.WeChatWorkConsts; import com.hotent.system.enums.BaseUrlEnum; import com.hotent.system.enums.ExterUniEnum; import com.hotent.system.manager.FlyBookManager; import com.hotent.system.model.SysExternalUnite; import com.hotent.system.model.WxOrg; import com.hotent.system.persistence.manager.SysExternalUniteManager; import com.hotent.system.util.DingTalkTokenUtil; import com.hotent.system.util.ThreadMessageUtil; import com.hotent.system.util.WechatOffAccTokenUtil; import com.hotent.system.util.WechatWorkTokenUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import poi.util.ExcelUtil; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.util.Map.Entry; @RestController @RequestMapping("/portal/sysExternalUnite/v1") @Api(tags="第三方集成") @ApiGroup(group= {ApiGroupConsts.GROUP_PORTAL}) public class SysExternalUniteController extends BaseController { @Resource SysExternalUniteManager sysExternalUniteManager; @Autowired private FlyBookManager flyBookManager; @RequestMapping(value="listJson", method= RequestMethod.POST, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "第三方系统集成列表", httpMethod = "POST", notes = "第三方系统集成列表") public PageList list(@ApiParam(name="queryFilter",value="通用查询对象")@RequestBody QueryFilter queryFilter){ return sysExternalUniteManager.query(queryFilter); } @RequestMapping(value="getJson", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "获得集成对象", httpMethod = "GET", notes = "获得集成对象") public SysExternalUnite getJson(@ApiParam(name="id",value="主键")@RequestParam String id) throws Exception{ if(StringUtil.isEmpty(id)){ return new SysExternalUnite(); } SysExternalUnite sysExternalUnite=sysExternalUniteManager.get(id); return sysExternalUnite; } @RequestMapping(value="generateMenuUrl", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "生成应用菜单url", httpMethod = "GET", notes = "生成应用菜单url") public CommonResult generateMenuUrl(@ApiParam(name="id",value="主键")@RequestParam String id, @ApiParam(name="corpId",value="第三方企业ID")@RequestParam(required = false) String corpId, @ApiParam(name="baseUrl",value="本系统地址")@RequestParam(required = false) String baseUrl, @ApiParam(name="baseUrlType",value="首页地址类型,mobile-移动端首页;pc-PC端首页")@RequestParam(required = false) String baseUrlType) throws Exception{ if(StringUtil.isEmpty(baseUrlType)){ baseUrl = BaseUrlEnum.MOBILE.value(); } String menuUrl = sysExternalUniteManager.generateMenuUrl(id, corpId, baseUrl, BaseUrlEnum.fromValue(baseUrlType)); return new CommonResult<>(true,"",menuUrl); } @PostMapping(value="save", produces={"application/json; charset=utf-8" }) @ApiOperation(value = "保存系统第三方集成信息", httpMethod = "POST", notes = "保存系统第三方集成信息") public CommonResult save(@ApiParam(name="sysExternalUnite",value="第三方集成信息")@RequestBody SysExternalUnite sysExternalUnite) throws Exception{ CommonResult resultMsg=null; String id=sysExternalUnite.getId(); try { Boolean isTypeExists = sysExternalUniteManager.isTypeExists(sysExternalUnite.getType(),sysExternalUnite.getId()); if(isTypeExists){ for(ExterUniEnum en : ExterUniEnum.values()){ if(en.getKey().equals(sysExternalUnite.getType())){ return new CommonResult(false,"【"+en.getLabel()+"】已集成,无需重复添加!"); } } } if(StringUtil.isEmpty(id)){ sysExternalUnite.setId(UniqueIdUtil.getSuid()); sysExternalUnite.setCorpName(ExterUniEnum.getLabelByKey(sysExternalUnite.getType())); sysExternalUniteManager.create(sysExternalUnite); resultMsg=new CommonResult(true,"添加成功"); }else{ sysExternalUniteManager.update(sysExternalUnite); resultMsg=new CommonResult(true,"更新成功"); } } catch (Exception e) { resultMsg=new CommonResult(false,"对第三方集成操作失败"); } return resultMsg; } @RequestMapping(value="removes",method=RequestMethod.DELETE, produces = { "application/json; charset=utf-8" }) @ApiOperation(value = "批量删除系统第三方集成记录", httpMethod = "DELETE", notes = "批量删除系统第三方集成记录") public CommonResult batchRemove(@ApiParam(name="主键集合",value="主键集合", required = true) @RequestParam String...ids) throws Exception{ try { sysExternalUniteManager.removeByIds(Arrays.asList(ids)); return new CommonResult("删除成功"); } catch (Exception e) { return new CommonResult(false,"删除失败"); } } @RequestMapping(value="syncUser", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "将本系统的用户同步到第三方平台", httpMethod = "GET", notes = "将本系统的用户同步到第三方平台") public void syncUser(@ApiParam(name="id",value="主键")@RequestParam String id, HttpServletResponse response) throws Exception{ boolean state = true; String errMsg = "上传通讯录成功"; try { sysExternalUniteManager.syncUser(id); } catch (Exception e) { state = false; errMsg= e.getMessage(); e.printStackTrace(); }finally { Map mapMsg = ThreadMessageUtil.getMapMsg(true); if(BeanUtils.isNotEmpty(mapMsg)){ Iterator> iterator = mapMsg.entrySet().iterator(); Map exportMap = new LinkedHashMap<>(); exportMap.put("fullname", "账号"); exportMap.put("errmsg", "异常信息"); List> data = new ArrayList<>(); while(iterator.hasNext()){ Entry next = iterator.next(); Map item = new HashMap<>(); item.put("fullname", next.getKey()); item.put("errmsg", next.getValue()); data.add(item); } // 拼装exprotMaps HSSFWorkbook book = ExcelUtil.exportExcel("异常账号", 24, exportMap, data); ExcelUtil.downloadExcel(book, "上传通讯录异常的账号信息", response); }else{ response.setHeader("content-type", "text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); CommonResult commonResult = new CommonResult(state,errMsg); PrintWriter out = response.getWriter(); out.write(JsonUtil.toJsonString(commonResult)); out.flush(); out.close(); } ThreadMessageUtil.cleanMapMsg(); } } @RequestMapping(value="bindMobile", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "通过手机号绑定平台用户账号", httpMethod = "GET", notes = "从第三方系统拉取通讯录至本系统") public void bindMobile(@ApiParam(name="id",value="主键")@RequestParam String id, HttpServletResponse response) throws Exception{ boolean state = true; String errMsg = "绑定成功"; try { sysExternalUniteManager.bingMobile(id); } catch (Exception e) { state = false; errMsg= e.getMessage(); e.printStackTrace(); }finally { Map mapMsg = ThreadMessageUtil.getMapMsg(true); if(BeanUtils.isNotEmpty(mapMsg)){ Iterator> iterator = mapMsg.entrySet().iterator(); Map exportMap = new LinkedHashMap<>(); exportMap.put("mobile", "手机号"); exportMap.put("errmsg", "异常信息"); List> data = new ArrayList<>(); while(iterator.hasNext()){ Entry next = iterator.next(); Map item = new HashMap<>(); item.put("mobile", next.getKey()); item.put("errmsg", next.getValue()); data.add(item); } // 拼装exprotMaps HSSFWorkbook book = ExcelUtil.exportExcel("异常账号", 24, exportMap, data); ExcelUtil.downloadExcel(book, "通讯录绑定手机号码异常信息", response); }else{ response.setHeader("content-type", "text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); CommonResult commonResult = new CommonResult(state,errMsg); PrintWriter out = response.getWriter(); out.write(JsonUtil.toJsonString(commonResult)); out.flush(); out.close(); } ThreadMessageUtil.cleanMapMsg(); } } @RequestMapping(value="pullUser", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "从第三方系统拉取通讯录至本系统", httpMethod = "GET", notes = "从第三方系统拉取通讯录至本系统") public CommonResult pullUser(@ApiParam(name="id",value="主键")@RequestParam String id) throws Exception{ try { sysExternalUniteManager.pullUser(id); return new CommonResult("拉取通讯录成功"); } catch (IOException e) { return new CommonResult(false,"拉取通讯录失败"+e.getMessage()); } } @RequestMapping(value="syncContacts", method=RequestMethod.POST, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "手动同步通讯录", httpMethod = "POST", notes = "手动同步通讯录") public void syncContacts(@ApiParam(name = "sysExternalUnite", value = "第三方应用配置信息") @RequestBody SysExternalUnite sysExternalUnite, HttpServletResponse response) throws Exception{ boolean state = true; String errMsg = "同步通讯录成功"; try { if(sysExternalUnite == null || !sysExternalUnite.getSyncFlag()){ errMsg = "请先修改通讯录同步配置,并启用同步组织架构"; } else { sysExternalUniteManager.syncContacts(sysExternalUnite); } } catch (Exception e) { state = false; errMsg= e.getMessage(); }finally { Map mapMsg = ThreadMessageUtil.getMapMsg(true); if(BeanUtils.isNotEmpty(mapMsg)){ Iterator> iterator = mapMsg.entrySet().iterator(); LinkedHashMap exportMap = new LinkedHashMap<>(2); exportMap.put("fullname", "账号"); exportMap.put("errmsg", "异常信息"); List> data = new ArrayList<>(); while(iterator.hasNext()){ Entry next = iterator.next(); Map item = new HashMap<>(2); item.put("fullname", next.getKey()); item.put("errmsg", next.getValue()); data.add(item); } // 拼装exprotMaps String title = "通讯录同步异常信息"; // HSSFWorkbook book = ExcelUtil.exportExcel(title, 24, exportMap, data); // ExcelUtil.downloadExcel(book, title, response); ExcelUtil.exportCSV(title, exportMap, data, response); }else{ response.setHeader("content-type", "application/json"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); CommonResult commonResult = new CommonResult(state,errMsg); PrintWriter out = response.getWriter(); out.write(JsonUtil.toJsonString(commonResult)); out.flush(); out.close(); } ThreadMessageUtil.cleanMapMsg(); } } @RequestMapping(value="saveAgent", method=RequestMethod.POST, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "保存系统第三方集成信息", httpMethod = "POST", notes = "保存系统第三方集成信息") public CommonResult saveAgent(@ApiParam(name="sysExternalUnite",value="第三方集成信息")@RequestBody SysExternalUnite sysExternalUnite) throws Exception{ CommonResult resultMsg=null; try { sysExternalUniteManager.saveAgent(sysExternalUnite); resultMsg=new CommonResult<>("操作成功"); } catch (Exception e) { resultMsg=new CommonResult<>(false,"对第三方集成操作失败:"+e.getMessage()); } return resultMsg; } @RequestMapping(value="getToken", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "获取getToken", httpMethod = "GET", notes = "获取getToken") public String getToken(String type) throws IOException { String token=""; if(ExterUniEnum.WeChatWork.getKey().equals(type)){ token=WechatWorkTokenUtil.getToken(); }else if(ExterUniEnum.Dingtalk.getKey().equals(type)){ token=DingTalkTokenUtil.getToken(); } return token; } @RequestMapping(value="getUserInfoUrl", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "获取getUserInfoUrl", httpMethod = "GET", notes = "获取getUserInfoUrl") public String getUserInfoUrl(@ApiParam(name="type",value="第三方集成类型")@RequestParam String type, @ApiParam(name="code",value="应用code")@RequestParam String code) throws Exception{ String url=""; if(ExterUniEnum.WeChatWork.getKey().equals(type)){ url=WeChatWorkConsts.getQyWxUserInfo(code); }else if(ExterUniEnum.Dingtalk.getKey().equals(type)){ url=DingTalkConsts.getUserInfo(code); }else if(ExterUniEnum.WeChatOfficialAccounts.getKey().equals(type)){ url=WeChatOffAccConsts.getWxAccessToken(code); }else if(ExterUniEnum.MiniProgram.getKey().equals(type)){ url = WeChatOffAccConsts.code2SessionUrl(code); } return url; } /** * PC端登录页,生成企微钉钉二维码所需的信息, * 该接口需要配置匿名 * @return */ @GetMapping("/getQrCodeInfo") @ApiOperation(value="获取生成企微钉钉二维码的信息",httpMethod = "GET") public Object getScanAppId(@ApiParam(name="tenantId",value="租户编码")@RequestParam String tenantId){ return baseService.getScanAppList(tenantId); } /** * 根据钉钉App扫码得到的code获取dingtalkId * @return * @throws Exception */ @GetMapping("getDingtalkIdFromScanCode") @ApiOperation(value="根据钉钉App扫码得到的code获取dingtalkId",httpMethod = "GET") public CommonResult getDingtalkIdFromScanCode( @ApiParam(name="code",value="钉钉App扫码得到的code")@RequestParam String code) throws Exception{ SysExternalUnite dingtalk = this.baseService.getDingtalk(); if(BeanUtils.isEmpty(dingtalk)){ return new CommonResult<>(false,"系统查无钉钉集成信息!"); } try { DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode"); OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest(); req.setTmpAuthCode(code); OapiSnsGetuserinfoBycodeResponse rsp = client.execute(req, dingtalk.getCorpId() ,dingtalk.getCorpSecret()); System.out.println(rsp.getBody()); if(rsp.getErrcode()!=0){ return new CommonResult<>(false,rsp.getBody()); } DingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); OapiUserGetbyunionidRequest req2 = new OapiUserGetbyunionidRequest(); req2.setUnionid(rsp.getUserInfo().getUnionid()); OapiUserGetbyunionidResponse rsp2 = client2.execute(req2, DingTalkTokenUtil.getToken()); System.out.println(rsp2.getBody()); if(rsp2.getErrcode()!=0){ return new CommonResult<>(false,rsp2.getErrmsg()); } return new CommonResult<>(true,"获取钉钉dingtalkId成功",rsp2.getResult().getUserid()); } catch (Exception e) { e.printStackTrace(); return new CommonResult<>(false,"根据钉钉App扫码得到的code获取dingtalkId失败:"+e.getMessage()); } } /** * 根据企业微信App扫码得到的code获取wxWorkId * @return * @throws Exception */ @GetMapping("getWxWorkIdFromScanCode") @ApiOperation(value="根据企业微信App扫码得到的code获取wxWorkId",httpMethod = "GET") public CommonResult getWxWorkIdFromScanCode( @ApiParam(name="code",value="企业微信App扫码得到的code")@RequestParam String code) throws Exception{ SysExternalUnite weChatWork = this.baseService.getWechatWork(); if(BeanUtils.isEmpty(weChatWork)){ return new CommonResult<>(false,"系统查无企业微信集成信息!"); } try { String url = WeChatWorkConsts.getQyWxUserInfo(code); String response = HttpUtil.sendHttpsRequest(url, "", "POST"); ObjectNode jsonNode = (ObjectNode) JsonUtil.toJsonNode(response); if(!"0".equals(jsonNode.get("errcode").asText())){ return new CommonResult<>(false,response); } return new CommonResult<>(true,"获取企业微信wxWorkId成功",jsonNode.get("UserId").asText()); } catch (Exception e) { e.printStackTrace(); return new CommonResult<>(false,"根据企业微信App扫码得到的code获取wxWorkId失败:"+e.getMessage()); } } /** * 根据飞书App扫码得到的code获取FLYBOOK_ID_ * @return * @throws Exception */ @GetMapping("getFlyBookIdFromScanCode") @ApiOperation(value="根据飞书App扫码得到的code获取FLYBOOK_ID_",httpMethod = "GET") public CommonResult getFlyBookIdFromScanCode( @ApiParam(name="code",value="飞书App扫码得到的code")@RequestParam String code, @ApiParam(name="redirectUri",value="前端回调地址")@RequestParam(value = "redirectUri", required = false) String redirectUri) throws Exception{ SysExternalUnite flyBook = this.baseService.getFlyBook(); if(BeanUtils.isEmpty(flyBook)){ return new CommonResult<>(false,"系统查无飞书集成信息!"); } try { String userId = flyBookManager.getUserInfo(code, redirectUri); return new CommonResult<>(true,"获取用户ID成功",userId); } catch (Exception e) { e.printStackTrace(); return new CommonResult<>(false,"根据App扫码得到的code获取用户ID失败:"+e.getMessage()); } } /** * 飞书获取登录预授权码 code 对应的登录用户身份 * @return * @throws Exception */ @GetMapping("getFlyBookIdByCode") @ApiOperation(value="飞书获取登录预授权码 code 对应的登录用户身份",httpMethod = "GET") public CommonResult getFlyBookIdByCode( @ApiParam(name="code",value="飞书登录预授权码code")@RequestParam String code) throws Exception{ SysExternalUnite flyBook = this.baseService.getFlyBook(); if(BeanUtils.isEmpty(flyBook)){ return new CommonResult<>(false,"系统查无飞书集成信息!"); } String userId = flyBookManager.getAccessUserId(code); return new CommonResult<>(true,"获取用户ID成功",userId); } @RequestMapping(value="clearToken", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "清除token缓存", httpMethod = "GET", notes = "清除token缓存") public CommonResult clearToken(@ApiParam(name="type",value="第三方集成类型")@RequestParam(required = false) String type) throws Exception{ boolean clearAll = BeanUtils.isEmpty(type); if(ExterUniEnum.WeChatWork.getKey().equals(type) || clearAll){ WechatWorkTokenUtil.clearToken(); } if(ExterUniEnum.Dingtalk.getKey().equals(type) || clearAll){ DingTalkTokenUtil.clearToken(); } if(ExterUniEnum.WeChatOfficialAccounts.getKey().equals(type) || clearAll){ WechatOffAccTokenUtil.clearToken(); } return CommonResult.ok(); } @RequestMapping(value="getDepartmentTree", method=RequestMethod.GET, produces={"application/json; charset=utf-8" }) @ApiOperation(value = "获得集成对象", httpMethod = "GET", notes = "获得集成对象") public List getDepartmentTree(@ApiParam(name="type",value="第三方类型,微信-weChatWork;dingtalk-钉钉;flyBook-飞书")@RequestParam String type) throws Exception{ return sysExternalUniteManager.getDepartmentTree(type); } }