通过钉钉工作通知API给指定用户发送消息,主要流程是创建应用、获取访问令牌,然后调用消息发送接口。下面是具体的步骤和代码示例。
步骤 | 关键信息 | 说明 |
---|---|---|
1. 创建应用 | AppKey , AppSecret , AgentId |
在钉钉开放平台创建"企业内部开发"类型的H5微应用,并获取凭证。 |
2. 获取令牌 | Access Token |
使用AppKey和AppSecret调用接口获取,有效期为7200秒。 |
3. 发送消息 | userid_list , agent_id , msg |
调用异步发送接口,指定接收用户、应用ID和消息内容。 |
🔑 第一步:准备阶段与获取Access Token
首先,你需要在钉钉开放平台上创建一个"企业内部开发"类型的H5微应用。创建成功后,记录下应用详情页提供的 AppKey 、AppSecret 和 AgentId,这是后续API调用的关键凭证。
获取Access Token的示例代码如下:
java
// 引入必要的依赖,例如阿里云的Java SDK
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;
public String getAccessToken() throws ApiException {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest request = new OapiGettokenRequest();
request.setAppkey("你的AppKey"); // 替换为你的AppKey
request.setAppsecret("你的AppSecret"); // 替换为你的AppSecret
request.setHttpMethod("GET");
OapiGettokenResponse response = client.execute(request);
// 正常情况下access_token有效期为7200秒
return response.getAccessToken();
}
✉️ 第二步:发送工作通知消息
拿到Access Token后,就可以调用工作通知API发送消息了。核心接口是 corpconversation/asyncsend_v2
,支持文本、链接、Markdown等多种消息格式。
以下是一个发送文本消息的Java示例:
java
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
// 发送文本工作通知
public OapiMessageCorpconversationAsyncsendV2Response sendTextMessage(String accessToken, String userIds, String content) throws ApiException {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
// 设置接收者的用户ID列表,多个用逗号分隔
request.setUseridList(userIds);
// 设置微应用的AgentId
request.setAgentId(Long.parseLong("你的AgentId")); // 替换为你的AgentId
// 构造消息体
OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
msg.setMsgtype("text"); // 消息类型为文本
msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
msg.getText().setContent(content); // 消息内容
request.setMsg(msg);
OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request, accessToken);
return response;
}
💡 重要提示与进阶用法
- 如何获取用户ID(UserID):发送消息需要准确的用户ID。除了从钉钉管理后台查询,还可以通过API根据员工手机号获取UserID。
- 消息类型 :除了文本,该API还支持丰富的消息类型,如Markdown、图片、链接卡片、OA消息等,只需修改
msgtype
和对应的消息体即可。 - 发送限制:请注意,通过工作通知API发送消息有频率限制。例如,同一个微应用给同一个用户发送消息,企业内部开发方式一天不得超过500次;全员推送一天最多3次。
- 异步发送 :该接口是异步发送的,接口返回成功仅表示任务提交成功,不代表用户已收到。可以通过返回的
task_id
查询发送进度和结果。