java_专有钉钉获取组织架构以及人员

本文介绍了如何在Spring框架中配置钉钉API,并展示了一个Service实现,用于获取指定租户ID下的部门信息,包括部门层级和用户列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.配置类

package cn.xwl.demo;

import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;


@Configuration
public class AppConfig {

    @Value("${dingTalk.appKey}") //从专有钉钉平台获取
    public String appkey;

    @Value("${dingTalk.secretKey}") //从专有钉钉平台获取
    public String secretKey;

    @Value("${dingTalk.domain}") //从专有钉钉平台获取
    public String domain;


	//创建实例	
    @Bean
    public ExecutableClient creatbean(){
        ExecutableClient executableClient= ExecutableClient.getInstance();
        //DomainName不同环境对应不同域名,示例为sass域名
        executableClient.setDomainName(domain);
        executableClient.setProtocal("https");
        //应用App Key
        executableClient.setAccessKey(appkey);
        //应用App Secret
        executableClient.setSecretKey(secretKey);
        executableClient.init();
        return executableClient;
    }
}

2.部门和用户实体

package cn.xwl.demo; /**
 * @author taoxi
 * @creat 2021-09-24 14:25
 */

import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
public class DeptDTO {
    //行政区划code
    private String divisionCode;
    //父组织名称
    private String parentName;
    //组织名称
    private String organizationName;
    //父组织Code
    private String parentCode;
    //组织Code
    private String organizationCode;
    //排序码
    private String displayOrder;
    //组织类型名称
    private String typeName;
    //创建时间
    private String gmtCreate;
    //组织类型Code
    private String typeCode;
    //组织状态 A - 有效的数据, F - 无效的数据
    private String status;

    private List<DeptDTO> dtoList;


}
package cn.xwl.demo;


import lombok.Data;
import org.springframework.stereotype.Component;


@Data
@Component
public class User {
    //姓名
    private String employeeName;
    //人员Code
    private String employeeCode;
    //人员性别 Code
    private String empGender;
    //人员状态
    private String status;
    //账号ID
    private String accountId;
    //账号code
    private String accountCode;



}

3.service

package cn.xwl.demo;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.api.request.*;
import com.alibaba.xxpt.gateway.shared.api.response.*;
import com.alibaba.xxpt.gateway.shared.client.http.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Service
public class DepartmentInfoService{
    @Autowired
    ExecutableClient executableClient;

    //获取部门及子部门
     
    public List<DeptDTO> getDeptVisibleScopes(Long tenantID) {
        //Long tenantID=50087450L;
        List<DeptDTO> dtoListTree=new ArrayList<>();
        //1.获取通讯录权限范围 及 当前权限层极
        //executableClient保证单例
        IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient("/auth/scopesV2");
        OapiAuthScopesV2Request oapiAuthScopesV2Request = new OapiAuthScopesV2Request();
        //租户ID
        oapiAuthScopesV2Request.setTenantId(tenantID);
        //获取结果
        OapiAuthScopesV2Response apiResult = intelligentGetClient.get(oapiAuthScopesV2Request);
        if(apiResult.getSuccess()){
           String json= apiResult.getContent();
          List<String> deptScopes= JSONObject.parseObject(json).getJSONArray("deptVisibleScopes").toJavaList(String.class);
          //2.获取所有的子级下级编码  及 本级组织
            List<String> deptScopesAll=new ArrayList<>();
            if(!deptScopes.isEmpty()){
                deptScopes.forEach(str->deptScopesAll.add(str));
                List<String> deptScopesAllChild=getChildScopes(deptScopes,tenantID);
                if(!deptScopesAllChild.isEmpty()){
                    deptScopesAllChild.forEach(str->deptScopesAll.add(str));
                }
                //获取各部门信息
                List<DeptDTO> dtoList=getDeptList(deptScopesAll,tenantID);
                String parentCode=dtoList.stream().filter(DeptDTO->DeptDTO.getOrganizationCode().equals(deptScopes.get(0))).findFirst().get().getParentCode();
                //递归创建部门树结构
                dtoListTree=getThree(dtoList, parentCode);
            }
        }
        return  dtoListTree;
    }

    public List<String> getChildScopes(List<String> deptScopes,Long tenantID){
        List<String> listAll=new ArrayList<>();
        for(String str:deptScopes){
            //executableClient保证单例
            IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient("/mozi/organization/pageSubOrganizationCodes");
            OapiMoziOrganizationPageSubOrganizationCodesRequest oapiMoziOrganizationPageSubOrganizationCodesRequest = new OapiMoziOrganizationPageSubOrganizationCodesRequest();
            oapiMoziOrganizationPageSubOrganizationCodesRequest.setReturnTotalSize(true);
            oapiMoziOrganizationPageSubOrganizationCodesRequest.setPageSize(100);
            oapiMoziOrganizationPageSubOrganizationCodesRequest.setOrganizationCode(str);
            oapiMoziOrganizationPageSubOrganizationCodesRequest.setPageNo(1);
            oapiMoziOrganizationPageSubOrganizationCodesRequest.setStatus("A");
            oapiMoziOrganizationPageSubOrganizationCodesRequest.setTenantId(tenantID);
            //获取结果
            OapiMoziOrganizationPageSubOrganizationCodesResponse apiResult = intelligentGetClient.get(oapiMoziOrganizationPageSubOrganizationCodesRequest);

            if(apiResult.getSuccess()){
                String json= apiResult.getContent().getData();
                if(json!=null){
                    List<String> deptScopeChild= Arrays.asList(json.replace("[","").replace("]","").replace("\"","").split(","));
                    deptScopeChild.forEach(str1->listAll.add(str1));
                    List<String> list=getChildScopes(deptScopeChild,tenantID);
                    if(!list.isEmpty()){
                        list.forEach(str2->listAll.add(str2));
                    }
                }
                /*List<String> deptScopeChild= Arrays.asList(json.split(","));
                deptScopes.addAll(deptScopeChild);
                getChildScopes(deptScopeChild,tenantID);*/

            }
        }

        //return deptScopes;
        return listAll;
    }


    public List<DeptDTO> getDeptList(List<String> deptScopes,Long tenantID){
        IntelligentPostClient intelligentPostClient = executableClient.newIntelligentPostClient("/mozi/organization/listOrganizationsByCodes");
        OapiMoziOrganizationListOrganizationsByCodesRequest oapiMoziOrganizationListOrganizationsByCodesRequest = new OapiMoziOrganizationListOrganizationsByCodesRequest();
        oapiMoziOrganizationListOrganizationsByCodesRequest.setOrganizationCodes(deptScopes);
        oapiMoziOrganizationListOrganizationsByCodesRequest.setTenantId(tenantID);
        //获取结果
        OapiMoziOrganizationListOrganizationsByCodesResponse apiResult = intelligentPostClient.post(oapiMoziOrganizationListOrganizationsByCodesRequest);
        JSONArray json= JSONArray.parseArray(apiResult.getContent().getData());
        //转化成bean
        List<DeptDTO> dtoList= json.toJavaList(DeptDTO.class);
        return dtoList;
    }

    private static List<DeptDTO> getThree(List<DeptDTO> departmentList, String parentCode) {
        //找出 根 列表
        // List<Department> departmentListPareant=departmentList.stream().filter(x->x.getParentId()==pId).collect(Collectors.toList());
        //获取所有子节点
        List<DeptDTO> childTreeList = getChildTree(departmentList,parentCode);
        for (DeptDTO dept:childTreeList) {
            List<DeptDTO> rest=getThree(departmentList,dept.getOrganizationCode());
            dept.setDtoList(rest);
        }
        return childTreeList;

    }

    private static List<DeptDTO> getChildTree(List<DeptDTO> list,String parentCode){
        List<DeptDTO> childTree = new ArrayList<>();
        for (DeptDTO dept:list) {
            if(dept.getParentCode().equals(parentCode)){
                childTree.add(dept);
            }
        }
        return childTree;
    }

     
    public List<User> getDeptUser(String OrganizationCode,Long tenantId) {
        List<User> list=new ArrayList<>();
        //获取 组织下人员 code
        IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient("/mozi/organization/pageOrganizationEmployeeCodes");
        OapiMoziOrganizationPageOrganizationEmployeeCodesRequest oapiMoziOrganizationPageOrganizationEmployeeCodesRequest = new OapiMoziOrganizationPageOrganizationEmployeeCodesRequest();
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setReturnTotalSize(true);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setPageSize(100);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setOrganizationCode(OrganizationCode);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setPageNo(1);
        oapiMoziOrganizationPageOrganizationEmployeeCodesRequest.setTenantId(tenantId);
        //获取结果
        OapiMoziOrganizationPageOrganizationEmployeeCodesResponse apiResult = intelligentGetClient.get(oapiMoziOrganizationPageOrganizationEmployeeCodesRequest);
        if(apiResult.getSuccess()){
            String json= apiResult.getContent().getData();
            if(json!=null){
                List<String> userCode= Arrays.asList(json.replace("[","").replace("]","").replace("\"","").split(","));

                //批量根据员⼯Code查询详情
                if(!userCode.isEmpty()){
                    IntelligentPostClient intelligentPostClient = executableClient.newIntelligentPostClient("/mozi/employee/listEmployeesByCodes");
                    OapiMoziEmployeeListEmployeesByCodesRequest oapiMoziEmployeeListEmployeesByCodesRequest = new OapiMoziEmployeeListEmployeesByCodesRequest();
                    oapiMoziEmployeeListEmployeesByCodesRequest.setEmployeeCodes(userCode);
                    oapiMoziEmployeeListEmployeesByCodesRequest.setTenantId(tenantId);
                    //获取结果
                    OapiMoziEmployeeListEmployeesByCodesResponse apiResultInfo = intelligentPostClient.post(oapiMoziEmployeeListEmployeesByCodesRequest);
                    if(apiResultInfo.getSuccess()){
                        JSONArray jsonArray= JSONArray.parseArray(apiResultInfo.getContent().getData());
                        list=jsonArray.toJavaList(User.class);
                        System.out.println("==================");
                        if(!list.isEmpty()){
                            批量根据员⼯Code查询 账号ID
                            String api ="/mozi/employee/listEmployeeAccountIds";
                            PostClient postClient = executableClient.newPostClient(api);
                            //JSON.toJSONString(userCode)
                            userCode.stream().forEach(str->{
                                postClient.addParameter("employeeCodes", str);
                            });
                            postClient.addParameter("tenantId", Long.toString(tenantId));
                            String apiResultAccount = postClient.post();
                            JSONObject jsonObject= JSON.parseObject(apiResultAccount);
                            if(jsonObject.getBoolean("success")){
                                List<User> userList= jsonObject.getJSONObject("content").getJSONArray("data").toJavaList(User.class);
                                list.stream().forEach(User->{
                                    for(User user:userList){
                                        if(User.getEmployeeCode().equals(user.getEmployeeCode())){
                                            User.setAccountCode(user.getAccountCode());
                                            User.setAccountId(user.getAccountId());
                                        }
                                    }
                                });
                            }
                        }

                    }
                }
            }
        }
       return list;
    }


    //获取access_token
    public String getAccessToken() {

        IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient("/gettoken.json");
        OapiGettokenJsonRequest oapiGettokenJsonRequest = new OapiGettokenJsonRequest();
/*        oapiGettokenJsonRequest.setAppkey("字符串");
        oapiGettokenJsonRequest.setAppsecret("字符串");*/
        OapiGettokenJsonResponse apiResult = intelligentGetClient.get(oapiGettokenJsonRequest);

        if(apiResult.getSuccess()){
            JSONObject json = JSONObject.parseObject(apiResult.getContent().getData());
            return  json.getString("accessToken");
        }else{
            return null;
        }
    }

    //获取用户
    public JSONObject  getUser(String access_token, String auth_code) {

        //executableClient保证单例
        IntelligentPostClient intelligentPostClient = executableClient.newIntelligentPostClient("/rpc/oauth2/dingtalk_app_user.json");
        OapiRpcOauth2DingtalkAppUserJsonRequest oapiRpcOauth2DingtalkAppUserJsonRequest = new OapiRpcOauth2DingtalkAppUserJsonRequest();
        oapiRpcOauth2DingtalkAppUserJsonRequest.setAccess_token(access_token);
        oapiRpcOauth2DingtalkAppUserJsonRequest.setAuth_code(auth_code);
        OapiRpcOauth2DingtalkAppUserJsonResponse apiResult = intelligentPostClient.post(oapiRpcOauth2DingtalkAppUserJsonRequest);


        System.out.println(apiResult.getContent());
        if(apiResult.getSuccess()){
            return JSONObject.parseObject(apiResult.getContent()).getJSONObject("content").getJSONObject("data");
        }else{
            return null;
        }
    }

}

4.测试

package cn.xwl.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class DemoApplicationTests {

    @Resource
    public DepartmentInfoService departmentInfoService;

	// 50623173L 是租户ID 可以通过调用专有钉钉的免登方法获取
    @Test
    void contextLoads() {
        List<DeptDTO> deptVisibleScopes = departmentInfoService.getDeptVisibleScopes(50623173L);
        deptVisibleScopes.forEach( x ->{
            System.out.println(x.getOrganizationCode());
        });
    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值