第一步:注册钉钉企业账号
打开链接:https://oa.dingtalk.com/#/login,注册账号即可
第二步:创建应用
以创建e应用为例:
还需要授权一个开发人员,并获取CorpSecret,需要把corpId和CorpSecret作为参数请求api接口获取AccessToken,后面的所有接口都需要AccessToken
第三步:接入接口
一、获取token
1 const corpid = 'dingd***587da6ee21d35c2f4657eb63***'; 2 const corpsecret = '*********'; 3 const requestPromise = require("request-promise"); 4 5 const getAccessToken = async (corpid, corpsecret) => { 6 // https://oapi.dingtalk.com/gettoken?corpid={corpid}&corpsecret={corpSecret或开发授权码} 7 const result = await requestPromise({ uri: 'https://oapi.dingtalk.com/gettoken', qs: { corpid, corpsecret } }); 8 console.log(result); 9 }; 10 getAccessToken(corpid, corpsecret);
二、promise请求接口封装
function request(url, method, params, headers = {}) {
const options = {
url,
method,
// timeout: 3000,
headers: Object.assign(headers, {
'content-type': 'application/json',
}),
rejectUnauthorized: false, // https
json: true,
};
switch (method) {
case 'POST':
case 'PUT':
options.body = params;
break;
case 'GET':
case 'DELETE':
options.qs = params;
break;
default:
break;
}
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (!error) {
resolve(body);
} else {
reject(error);
}
});
});
.catch (error => ({
msg: error.message,
}));
}
三、接口见代码(后端使用koa.js)
const host = 'https://oapi.dingtalk.com/';
/*
*发送工作通知消息
*/
router.post('/api/dingtalkserve/asyncsend_v2', async ({ request, response, session }) => {
try {
let body = request.fields;
if (!body['userid_list'] && !body['dept_id_list'] && !body['to_all_user']) {
return response.fail({
'msg': "userid_list,dept_id_list, to_all_user必须有一个不能为空"
});
}
if (!body['msg']) {
return response.fail({
'msg': "msg不能为空"
});
}
// 获取TOKEN
let accessToken = await getAccessToken();
let params = {
agent_id: parseInt(agentId4EP),
msg: {
"msgtype": "text",
"text": {
"content": body['msg']
}
}
};
body['to_all_user'] ? params['to_all_user'] = true : false;
body['dept_id_list'] ? params['dept_id_list'] = body['dept_id_list'] : "";
body['userid_list'] ? params['userid_li