自定义钉钉机器人
土豆 2023/2/11
# 密钥加签
把timestamp+"\n"+
密钥当做签名字符串,使用HmacSHA256算法计算签名,然后进行Base64 encode,最后再把签名参数再进行urlEncode,得到最终的签名(需要使用UTF-8字符集)。
参数 | 说明 |
---|---|
timestamp | 当前时间戳,单位是毫秒,与请求调用时间误差不能超过1小时。 |
secret | 密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串。 |
// sign js
const crypto = require('crypto');
// 加签
module.exports = (secret, content) => {
const str = crypto
.createHmac('sha256', secret)
.update(content)
.digest()
.toString('base64');
return encodeURIComponent(str);
};
使用
// 时间戳
const timestamp = Date.now();
// 密钥
const secret = "xxxxxxxxxxxx"
// 密钥加签
const signStr =
'×tamp=' +
timestamp +
'&sign=' +
sign(secret, timestamp + '\n' + secret);
# 发送消息
const sign = require('./sign');
const axios = require('axios');
// 时间戳
const timestamp = Date.now();
// webhook网址
const webHook =
'https://oapi.dingtalk.com/robot/send?access_token=xxxxxx';
// 密钥
const secret = 'xxxxxxxx';
// 密钥加签
const signStr = '×tamp=' + timestamp + '&sign=' + sign(secret, timestamp + '\n' + secret);
(async () => {
const res = await axios.post(`${webHook}${signStr}`, {
msgtype: 'text',
text: {
content: '我就是我, @XXX 是不一样的烟火',
},
});
console.log(res);
})();