1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| const access_token = '123'; const secret = '123';
function ddRobot(msg) { let s = ddSign(secret); let url = 'https://oapi.dingtalk.com/robot/send?access_token=' + access_token + '×tamp=' + s.timestamp + '&sign=' + s.sign;
fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ msgtype: 'text', text: { content: msg } }) }) .then(response => response.json()) .then(data => { if (data.errcode === 0) { console.log('钉钉消息发送成功'); } }) .catch(error => { console.error('钉钉发生错误:', error); }) }
function ddSign(secret){ const crypto = require('crypto'); const timestamp = String(Math.round((new Date()).getTime())); const secret_enc = Buffer.from(secret, 'utf-8'); const string_to_sign = `${timestamp}\n${secret}`; const string_to_sign_enc = Buffer.from(string_to_sign, 'utf-8'); const hmac_code = crypto.createHmac('sha256', secret_enc).update(string_to_sign_enc).digest(); const sign = encodeURIComponent(hmac_code.toString('base64'));
return { 'timestamp': timestamp, 'sign': sign } }
|