钉钉自定义机器人加签方式发送消息node示例
js
const request = require('./request')
const DING_ROBOT_WEB_HOOK = process.env.DING_ROBOT_WEB_HOOK
const DING_ROBOT_SECRET = process.env.DING_ROBOT_SECRET
const crypto = require('crypto')
function buildUrl() {
// 获取当前时间戳(毫秒级)
const timestamp = Date.now();
// 构建待签名字符串,格式为 "timestamp\nsecret"
const stringToSign = `${timestamp}\n${DING_ROBOT_SECRET}`;
// 创建一个HMAC对象,使用SHA256算法和机器人密钥作为密钥
const hmac = crypto.createHmac('sha256', Buffer.from(DING_ROBOT_SECRET, 'utf-8'));
// 更新HMAC对象的内容为待签名字符串
hmac.update(stringToSign);
// 计算签名,并将其编码为Base64格式,然后进行URL编码
const sign = encodeURIComponent(hmac.digest('base64'));
// 返回完整的Webhook URL,包含时间戳和签名参数
return `${DING_ROBOT_WEB_HOOK}×tamp=${timestamp}&sign=${sign}`;
}
module.exports = {
async sendText(content) {
return request({
url: buildUrl(),
method: 'POST',
data: {
msgtype: 'text',
text: {
content
}
}
})
}
}