钉钉开放平台调用手册

获取应用令牌并发送机器人单聊

用企业应用机器人向授权范围内的一位成员发送 Markdown 通知。

官方资料核对 2026-10-15示例代码,未进行真实接口实测
← 返回平台功能

接入准备

  • 企业内部应用已配置并发布机器人,开通 qyapi_base 和 qyapi_robot_sendmsg。
  • 核对 robotCode、接收成员的安装及可用范围;不是个人账号私信接口。

准备环境变量

示例值需要替换为自己的凭证或资源 ID。代码在本机或服务端运行;密钥不应放进公开网页。

DINGTALK_CORP_ID
本企业 corpId,第三方模式则为授权企业。
DINGTALK_ACCESS_TOKEN
应用级令牌;取下面 token 操作返回的 access_token,不是 Webhook access_token。
终端
export DINGTALK_CORP_ID='ding_replace_with_corp_id'
export DINGTALK_ACCESS_TOKEN='replace_with_app_access_token'

以上 export 适用于 macOS / Linux 的终端,在同一终端内运行后续代码。Python 示例保存为 request.py 后执行 python3 request.py。

调用步骤

  1. 01

    开发者后台取得本企业 corpId、应用 ClientID、ClientSecret 和企业机器人的 robotCode。

  2. 02

    获取 Token,把响应 access_token 存入 DINGTALK_ACCESS_TOKEN。

  3. 03

    把发送 body 的 robotCode 与 userIds 替换为真实值;示例一次只发一位成员。

  4. 04

    检查无效与被限流列表;仅有 processQueryKey 不代表每位成员均收到。

调用 01

获取当前组织的应用令牌

使用当前统一 Token 端点,企业内部应用的 corpId 为本企业,第三方企业应用为已经开通应用的授权企业。

POSThttps://api.dingtalk.com/v1.0/oauth2/${DINGTALK_CORP_ID}/token

请求头

Content-Type
application/json

参数说明

参数表可左右滑动,查看完整说明。

字段 / 位置类型 / 必填说明
corpIdPathstring必填应用运行组织的 corpId,在开发者后台确认。
client_id请求体string必填应用 ClientID,先替换虚构值。
client_secret请求体string必填应用 ClientSecret,先替换虚构值;只在服务端保存。
grant_type请求体string必填固定 client_credentials。

调用代码

替换示例 ID 与请求体内容后运行。cURL 会报 HTTP 错误,业务状态还需按下方返回示例核对。

cURL
cat > request-body.json <<'JSON'
{
  "client_id": "replace_with_client_id",
  "client_secret": "replace_with_client_secret",
  "grant_type": "client_credentials"
}
JSON

# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request POST \
  --url "https://api.dingtalk.com/v1.0/oauth2/${DINGTALK_CORP_ID}/token" \
  --header "Content-Type: application/json" \
  --data-binary @request-body.json
Python 3
import json
import os
import re
import urllib.request
import urllib.error

def expand(value):
    return re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}",
                  lambda match: os.environ[match.group(1)], value)

url = expand("https://api.dingtalk.com/v1.0/oauth2/${DINGTALK_CORP_ID}/token")
headers = {
    "Content-Type": expand("application/json"),
}
body = {
    "client_id": "replace_with_client_id",
    "client_secret": "replace_with_client_secret",
    "grant_type": "client_credentials",
}
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
    raise SystemExit(1)
print(json.dumps(result, ensure_ascii=False, indent=2))
Node.js
// Node.js 22+,保存为 request.mjs 后运行 node request.mjs
function expand(value) {
  return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (_, name) => {
    if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`);
    return process.env[name];
  });
}

const url = expand("https://api.dingtalk.com/v1.0/oauth2/${DINGTALK_CORP_ID}/token");
const headers = Object.fromEntries(
  Object.entries({
  "Content-Type": "application/json"
}).map(([key, value]) => [key, expand(value)])
);
const body = {
  "client_id": "replace_with_client_id",
  "client_secret": "replace_with_client_secret",
  "grant_type": "client_credentials"
};
const response = await fetch(url, {
  method: "POST",
  headers,
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
const result = JSON.parse(text);
console.log(JSON.stringify(result, null, 2));

返回示例

按官方字段整理的节选示意,使用虚构 ID,不是实测结果。读取 access_token、expires_in,缓存后供消息及通讯录请求使用。 以下为结构示意,非本站实测结果。

JSON
{
  "access_token": "replace_with_returned_token",
  "expires_in": 7200
}

常见错误与排查

invalid.clientClientID 或 ClientSecret 不正确
确认凭证来自同一应用、未重置。
unauthorized.client应用未被授权
核对目标组织已安装并开通该应用。

调用注意

  • 当前端点为 /oauth2/{corpId}/token,字段为 access_token/expires_in;不要与旧接口 accessToken/expireIn 混用。
  • 需要 qyapi_base 应用基本权限;有效期以返回值为准。
调用 02

发送 Markdown 单聊消息

msgParam 必须是 JSON 序列化后的字符串,消息模板与其字段对应。

POSThttps://api.dingtalk.com/v1.0/robot/oToMessages/batchSend

请求头

x-acs-dingtalk-access-token
${DINGTALK_ACCESS_TOKEN}
Content-Type
application/json

参数说明

参数表可左右滑动,查看完整说明。

字段 / 位置类型 / 必填说明
robotCode请求体string必填开发者后台企业内部应用机器人的编码,不是群 Webhook Token。
userIds请求体string[]必填接收人 userId 数组;当前请求参数文档上限为 20,本例 1 个。
msgKey请求体string必填本例 sampleMarkdown。
msgParam请求体string必填JSON 字符串,sampleMarkdown 使用 title 和 text;不能传一个未序列化对象。

调用代码

替换示例 ID 与请求体内容后运行。cURL 会报 HTTP 错误,业务状态还需按下方返回示例核对。

cURL
cat > request-body.json <<'JSON'
{
  "robotCode": "ding_replace_with_robot_code",
  "userIds": [
    "replace_with_member_userid"
  ],
  "msgKey": "sampleMarkdown",
  "msgParam": "{\"title\":\"接入测试\",\"text\":\"通知服务已启动。\"}"
}
JSON

# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request POST \
  --url "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend" \
  --header "x-acs-dingtalk-access-token: ${DINGTALK_ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request-body.json
Python 3
import json
import os
import re
import urllib.request
import urllib.error

def expand(value):
    return re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}",
                  lambda match: os.environ[match.group(1)], value)

url = expand("https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend")
headers = {
    "x-acs-dingtalk-access-token": expand("${DINGTALK_ACCESS_TOKEN}"),
    "Content-Type": expand("application/json"),
}
body = {
    "robotCode": "ding_replace_with_robot_code",
    "userIds": [
        "replace_with_member_userid",
    ],
    "msgKey": "sampleMarkdown",
    "msgParam": "{\"title\":\"接入测试\",\"text\":\"通知服务已启动。\"}",
}
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
    raise SystemExit(1)
print(json.dumps(result, ensure_ascii=False, indent=2))
Node.js
// Node.js 22+,保存为 request.mjs 后运行 node request.mjs
function expand(value) {
  return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (_, name) => {
    if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`);
    return process.env[name];
  });
}

const url = expand("https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend");
const headers = Object.fromEntries(
  Object.entries({
  "x-acs-dingtalk-access-token": "${DINGTALK_ACCESS_TOKEN}",
  "Content-Type": "application/json"
}).map(([key, value]) => [key, expand(value)])
);
const body = {
  "robotCode": "ding_replace_with_robot_code",
  "userIds": [
    "replace_with_member_userid"
  ],
  "msgKey": "sampleMarkdown",
  "msgParam": "{\"title\":\"接入测试\",\"text\":\"通知服务已启动。\"}"
};
const response = await fetch(url, {
  method: "POST",
  headers,
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
const result = JSON.parse(text);
console.log(JSON.stringify(result, null, 2));

返回示例

按官方字段整理的节选示意,使用虚构 ID,不是实测结果。保存 processQueryKey,检查 invalidStaffIdList 与 flowControlledStaffIdList。 以下为结构示意,非本站实测结果。

JSON
{
  "processQueryKey": "example_process_query_key",
  "invalidStaffIdList": [],
  "flowControlledStaffIdList": []
}

常见错误与排查

invalidParameter.msgParam.invalid模板参数不是有效 JSON
先序列化 title/text 对象,避免双重转义错误。
invalidParameter.robotCode.notExsit目标企业没有安装相应机器人
确认 robotCode 所属应用及目标租户安装情况。
send.too.fast消息发送频率过快
降低并发,按接收人和业务重试被限流部分。

调用注意

  • 官方错误说明里仍存在旧的 100 人文字,但当前 userIds 参数和页面简介为最多 20,按更严格的 20 分批。
  • 成功响应可能包含部分失败成员;不要把整个批次直接标记全成功。

注意事项

  • 第三方个人应用不支持此机器人能力;此场景只演示企业内部应用。

核验来源

本站按官方资料整理本场景的必要调用步骤与代码,覆盖范围以本页列出的接口为准。官方资料用于追溯规范及查看变更。

  1. 01
    获取应用的 Access Token核验日期 2026-10-15
  2. 02

钉钉开放平台的其他调用手册

← 返回钉钉开放平台的全部功能