钉钉api调用

本文档详细介绍了如何使用Java调用钉钉API,包括获取access_token、部门管理、用户信息获取等操作。同时,展示了DingApiUntil工具类的实现,用于自动化处理相关接口请求,如获取员工信息、部门ID等。

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

钉钉api调用

开发须知()官方

(1)调用钉钉服务端接口时,需使用HTTPS协议、JSON数据格式、UTF-8编码,POST请求请在HTTP Header中设置 Content-Type:application/json。
访问域名为:
新版服务端接口:https://api.dingtalk.com。
旧版服务端接口:https://oapi.dingtalk.com。
说明 旧版服务端接口支持正常调用。
(2)在调用服务端接口前,确保你已了解调用频率限制。详情请参考调用频率限制。
(3)在调用服务端接口前,确保你已经设置了对应的接口权限。详情请参考添加接口调用权限。
(4)无论是哪种应用,都必须接入钉钉免登,即在用户打开应用时可直接获取用户身份无需输入钉钉账号和密码。

access_token

access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token。
开发者需要缓存access_token,用于后续接口的调用。因为每个应用的access_token是彼此独立的,所以进行缓存时需要区分应用来进行存储。
不能频繁调用gettoken接口,否则会受到频率拦截。

package DingDingApiDemo;

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.taobao.api.ApiException;

import java.util.*;

/**
 * DingTalkApi工具类
 *
 * @author CaoPengCheng
 * @version 1.0.0
 * @Project DingTalkDemo
 * @Date 2021-08-31
 */
public class DingApiUntil {
    //应用的唯一标识key。
    private String appkey = "ding8lrom1le5zopavwt";
    //应用的密钥。
    private String appsecret = "T_oZq1IIEj5D5rses0EGc5gyI0EL_jqL8cLGhdFyWcdvpm8eSEwfLNEsJae0ObC-";
    private DingTalkClient client;
    private String access_token;
    private final List<Long> dept_idList = new ArrayList<>();

    //无参构造,初始化access_token
    public DingApiUntil() {
        getAccess_token();
    }

    //有参构造,初始化access_token
    public DingApiUntil(String access_token) {
        this.access_token = access_token;
    }

    //双参参构造,其他应用初始化access_token
    public DingApiUntil(String appkey, String appsecret) {
        this.appkey = appkey;
        this.appsecret = appsecret;
    }

    /*
     * 获取access_token
     * request:get
     * return:String
     * */
    public String getAccess_token() {
        OapiGettokenResponse response;
        OapiGettokenRequest request;
        String token = null;
        try {
            client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            request = new OapiGettokenRequest();
            request.setAppkey(appkey);
            request.setAppsecret(appsecret);
            request.setHttpMethod("GET");
            response = client.execute(request);
            //将response转为json,取出access_token
            token = JSONObject.parseObject(response.getBody()).getString("access_token");
            //每次获取都应该刷新access_token
            this.access_token = token;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return token;
    }

    /*
     * 获取所有小部门Id
     * request:post
     * return:void
     * */
    private void getDept_id(Long deptId) {
        OapiV2DepartmentListsubidRequest req;
        OapiV2DepartmentListsubidResponse rsp;
        try {
            if (access_token != null) {
                client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
                req = new OapiV2DepartmentListsubidRequest();
                req.setDeptId(deptId);
                rsp = client.execute(req, access_token);
                String json = JSONObject.parseObject(JSONObject.parseObject(rsp.getBody()).getString("result")).getString("dept_id_list");
                json = json.replace("]", "");
                json = json.replace("[", "");
                if (json.equals("")) {
                    dept_idList.add(Long.valueOf(deptId));
                } else {
                    for (String str : json.split(",")) {
                        getDept_id(Long.valueOf(str));
                    }
                }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    /*
     * 根据dept_id获取全部userId
     * request:post
     * return:
     * */
    public String[] getUserIdAllByDept_id(Long dept_id) {
        OapiUserListidRequest req;
        OapiUserListidResponse rsp;
        String json = null;
        try {
            if (access_token != null) {
                client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
                req = new OapiUserListidRequest();
                req.setDeptId(dept_id);
                rsp = client.execute(req, access_token);
                json = JSONObject.parseObject(JSONObject.parseObject(rsp.getBody()).getString("result")).getString("userid_list");
                json = json.replace("]", "");
                json = json.replace("[", "");
                json = json.replace("\"", "");
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return json.split(",");
    }

    /*
     * 根据userId获取全部信息
     * request:post
     * return:UserDetail
     * */
    public UserDetail getMassageByUserId(String userId) {
        OapiV2UserGetRequest req;
        OapiV2UserGetResponse rsp;
        UserDetail user = null;
        try {
            if (access_token != null) {
                client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
                req = new OapiV2UserGetRequest();
                req.setUserid(userId);
                req.setLanguage("zh_CN");
                rsp = client.execute(req, access_token);
                JSONObject result = JSONObject.parseObject(JSONObject.parseObject(rsp.getBody()).getString("result"));
                if (result != null) {
                    user = new UserDetail();
                    user.setCode(result.getString("mobile"));
                    user.setName(result.getString("name"));
                    user.setPhone(result.getString("mobile"));
                    user.setDingUserId(userId);
                    user.setPassWord("123456");
                }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return user;
    }

    /*
     * 通过部门获取所有员工信息
     * return:List<UserDetail>
     * */
    public List<UserDetail> getUserMassgAllByDept(Set<String> oldUserid) {
        List<UserDetail> userList = null;
        getDept_id(1L);
        if (!dept_idList.isEmpty()) {
            Set<String> setUserId = new TreeSet<>();
            for (Long deptid : dept_idList) {
                String[] userid = getUserIdAllByDept_id(deptid);
                Collections.addAll(setUserId, userid);//自去重
            }
            //oldUserid非空去重
            if (!oldUserid.isEmpty()) {
                Set<String> UserIdAll = new TreeSet<>();
                //与系统中的userid去重
                setFor:
                for (String id : setUserId) {
                    for (String old : oldUserid) {
                        if (id.equals(old)) {
                            continue setFor;
                        }
                    }
                    UserIdAll.add(id);
                }
                setUserId = UserIdAll;
            }
            //setUserId非空,取信息
            if (!setUserId.isEmpty()) {
                userList = new ArrayList<>();
                for (String str : setUserId) {
                    userList.add(getMassageByUserId(str));
                }
            }
        }
        return userList;
    }

    /*
     * 电话获取UserId
     * request:post
     * return:List<UserDetail>
     * */
    public String getUserIdByTelephone(String phone) {
        OapiV2UserGetbymobileRequest req;
        OapiV2UserGetbymobileResponse rsp;
        String userId = null;
        try {
            if (access_token != null) {
                client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
                req = new OapiV2UserGetbymobileRequest();
                req.setMobile(phone);
                rsp = client.execute(req, access_token);
                JSONObject result = JSONObject.parseObject(rsp.getBody());
                if(result.getString("errmsg").equals("ok")){
                    userId=JSONObject.parseObject(result.getString("result")).getString("userid");
                }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return userId;
    }

    /*
     * 电话获取当员工信息
     * return: UserDetail
     * */
    public UserDetail getUserMassgByTelephone(String phone) {
        String id = getUserIdByTelephone(phone);
        if (!id.equals("")) {
            return getMassageByUserId(id);
        }
        else {
            return null;
        }
    }

    /*
     * 获取员工人数
     * request:post
     * return:int
     * */
    public int getPersonnelCount() {
        OapiUserCountRequest req;
        OapiUserCountResponse rsp;
        int count = 0;
        try {
            if (access_token != null) {
                client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/count");
                req = new OapiUserCountRequest();
                req.setOnlyActive(false);
                rsp = client.execute(req, access_token);
                //将response转为json,取出access_token
                count = Integer.parseInt(JSONObject.parseObject(JSONObject.parseObject(rsp.getBody()).getString("result")).getString("count"));
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return count;

    }

    //打印list
    public void printList() {
        dept_idList.forEach(System.out::println);
    }

    //刷新Access_token
    public void refreshAccess_token() {
        this.access_token = getAccess_token();
    }

    //TODO:没有授权,获取部到部门信息
    /*
     * 获取所有部门信息
     * request:post
     * return:void
     * */
    public void getDepartment() {
        OapiV2DepartmentListsubRequest req;
        OapiV2DepartmentListsubResponse rsp;
        try {
            if (access_token != null) {
                client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
                req = new OapiV2DepartmentListsubRequest();
                req.setDeptId(1L);
                req.setLanguage("zh_CN");
                rsp = client.execute(req, access_token);
                System.out.println(rsp.getBody());
                System.out.println(JSONObject.parseObject(JSONObject.parseObject(rsp.getBody()).getString("result")));
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    public void getDepartment2() {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
            req.setDeptId(1L);
            req.setLanguage("zh_CN");
            OapiV2DepartmentGetResponse rsp;
            rsp = client.execute(req, access_token);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }
}

package DingDingApiDemo;

import org.junit.Test;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * DingTalkApi测试类
 *
 * @author CaoPengCheng
 * @version 1.0.0
 * @project DingTalkDemo
 * @date 2021-08-31
 */
public class DingApiTest {
    DingApiUntil dingApiUntil = new DingApiUntil();

    @Test
    public void countTest() {
        System.out.println("公司人数=" + dingApiUntil.getPersonnelCount());
    }

    @Test
    public void selectMassage() {
        UserDetail user = dingApiUntil.getMassageByUserId("manager8145");
        if (user == null) {
            System.out.println("user is null!");
        } else {
            System.out.println(user);
        }
    }

    @Test
    public void getUserIdAllByDept_idTest() {
        dingApiUntil.getUserIdAllByDept_id(537768596L);
    }

    @Test
    public void selectUserAll() {
        Set<String> newId = new TreeSet<>();
        Set<String> oldId = new TreeSet<>();
        newId.add("250214042135263180");
        newId.add("141434602621593606");
        newId.add("2502254505676061");
        newId.add("300156295239381872");
        newId.add("595749044939157569");
        newId.add("490055366940074226");
        newId.add("594261420524905377");
        newId.add("595851032426476806");
        newId.add("221639481420359250");
        newId.add("131854291335519272");
        newId.add("311633010520063562");
        newId.add("251155622521627291");
        newId.add("1648535929690701");
        newId.add("15864876864482337");
        newId.add("1585648369415541");
        oldId.add("250214042135263180");
        oldId.add("141434602621593606");
        oldId.add("2502254505676061");
        oldId.add("300156295239381872");
        oldId.add("595749044939157569");
        oldId.add("490055366940074226");
        test(oldId, newId);
    }

    public void test(Set<String> oldUserid, Set<String> setUserId) {
        Set<String> UserIdAll = new TreeSet<>();
        //与系统中的userid去重
        setFor:
        for (String id : setUserId) {

            for (String old : oldUserid) {
                if (id.equals(old)) {
                    continue setFor;
                }
            }
            UserIdAll.add(id);
        }
        for (String s : UserIdAll)
            System.out.println(s);
    }

    //通过电话精确获取
    @Test
    public void getUserIdByTelephoneTest() {
        UserDetail user=dingApiUntil.getUserMassgByTelephone("18993472079");
        if(user==null)
            System.out.println("查无此人");
        else
            System.out.println(user);
    }


    //通过部门全部获取
    @Test
    public void getuser() {
        Set<String> oldId = new TreeSet<>();
        oldId.add("manager8145");
        oldId.add("01326153421626553659");
        oldId.add("010937525215978977");
        oldId.add("manager81450");
        List<UserDetail> list = dingApiUntil.getUserMassgAllByDept(oldId);
        if (list == null)
            System.out.println("error");
        else
            list.forEach(System.out::println);
    }
}

<think>好的,我需要回答用户关于如何调用钉钉API的问题。首先,我需要整理用户提供的引用内容,看看里面有没有有用的信息。引用[1]提到安装dingtalk-jsapi,引用[2]和[4]涉及access_token和Webhook地址,引用[3]则概述了调用流程。看来步骤大致分为获取access_token、使用SDK或Webhook发送请求,以及参数配置。 首先,获取access_token是关键步骤,每个API调用都需要它。用户需要提供corpid和corpsecret,这通常在钉钉开放平台创建应用后获得。然后,拼接URL请求获取token,这可能需要处理参数编码问题,比如引用[2]中的URL参数错误,需要确保参数正确编码。 接下来,调用具体的API接口。根据引用[3],使用SDK可以简化调用过程,比如dingtalk-jsapi,这可能封装了常用的方法。另外,机器人推送消息可以使用Webhook方式,如引用[4]所述,需要配置自定义关键词,并确保消息中包含这些关键词才能成功推送。 用户可能需要具体的示例代码。例如,获取access_token的Python示例,或者发送消息的代码。同时,需要注意参数的正确传递方式,比如msgParam需要JSON字符串,并且进行URL编码,避免像引用[2]中的错误。 此外,还需要提醒用户注意安全,比如保护access_token,避免泄露。另外,错误处理也很重要,比如处理API返回的错误码,确保程序健壮性。 最后,生成相关问题,可能涉及鉴权失败处理、消息推送失败排查、SDK的其他功能等。需要确保问题覆盖用户可能遇到的常见问题。</think>### 钉钉 API 调用方法及参数说明 #### 1. 获取 Access Token 调用钉钉 API 前需先获取访问凭证 `access_token`,这是鉴权核心参数[^3]。 **步骤**: 1. 登录钉钉开放平台创建应用,获取企业唯一参数 `corpid` 和 `corpsecret`。 2. 通过以下接口请求: ``` GET https://oapi.dingtalk.com/gettoken?corpid=YOUR_CORPID&corpsecret=YOUR_CORPSECRET ``` 3. 返回示例: ```json { "errcode": 0, "errmsg": "ok", "access_token": "xxxxxx", "expires_in": 7200 } ``` #### 2. 调用具体 API 接口 以「机器人推送消息」为例,需使用 Webhook 方式[^4]: **步骤**: 1.钉钉群机器人设置中获取 Webhook URL,格式如: ``` https://oapi.dingtalk.com/robot/send?access_token=xxx ``` 2. 消息需包含预定义关键词(如“:”),请求示例: ```python import requests import json webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN" headers = {"Content-Type": "application/json"} data = { "msgtype": "text", "text": {"content": "监控告警:服务器CPU使用率超过90%"} } response = requests.post(webhook_url, headers=headers, data=json.dumps(data)) ``` #### 3. 使用 SDK 简化调用 安装官方 SDK 可减少底层编码复杂度[^1]: ```bash npm install dingtalk-jsapi --save # 前端项目 ``` Java 示例(获取用户信息): ```java DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get"); OapiUserGetRequest request = new OapiUserGetRequest(); request.setUserid("员工ID"); request.setHttpMethod("GET"); OapiUserGetResponse response = client.execute(request, "YOUR_ACCESS_TOKEN"); ``` #### 4. 关键参数说明 | 参数 | 作用 | 来源 | |----------------|-------------------------------|------------------------| | `access_token` | API 调用凭证 | 鉴权接口返回 | | `robotCode` | 机器人唯一标识 | 机器人配置页[^2] | | `msgKey` | 消息模板类型(如文本/卡片) | 钉钉文档定义[^4] | | `msgParam` | 消息内容(需 JSON 字符串) | 开发者自定义 | #### 5. 常见错误处理 - **参数编码问题**:URL 中的 `msgParam` 需进行 URL 编码,避免特殊字符报错[^2]。 - **关键词缺失**:机器人消息未包含预设关键词时会被拦截[^4]。 - **Token 过期**:`access_token` 有效期为 2 小时,需定时刷新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CaoPengCheng&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值