Skip to content

钉钉自定义机器人加签方式发送消息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}&timestamp=${timestamp}&sign=${sign}`;
}

module.exports = {
    async sendText(content) {
        return request({
            url:  buildUrl(),
            method: 'POST',
            data: {
                msgtype: 'text',
                text: {
                    content
                }
            }
        })
    }
}
/src/technology/dateblog/2025/05/20250519-%E9%92%89%E9%92%89%E8%87%AA%E5%AE%9A%E4%B9%89%E6%9C%BA%E5%99%A8%E4%BA%BA%E5%8A%A0%E7%AD%BE%E6%96%B9%E5%BC%8F%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AFnode%E7%A4%BA%E4%BE%8B.html