飞书机器人---使用Node发送签名消息

310 阅读1分钟
import axios from 'axios';
import crypto from 'crypto';

const secret = 'nIMtb7r3N9pkXyXdtAbx6e';
const webhook = 'https://open.feishu.cn/open-apis/bot/v2/hook/5e3d587e-d78e-4a07-bd07-265f269f86fd';

// https://stackoverflow.com/questions/13465048/nodejs-crypto-vs-python-hashlib
// https://www.feishu.cn/hc/zh-CN/articles/244506653275#magicdomid-1_155
const encode = (secret) => {
  const timestamp = Math.floor(Date.now() / 1000);
  const key = Buffer.from(`${timestamp}\n${secret}`, 'utf8');
  const hmac = crypto.createHmac('SHA256', key);
  hmac.update(Buffer.alloc(0));
  const sign = hmac.digest('base64');
  return { timestamp, sign: sign };
};

const send = async (text) => {
  const { timestamp, sign } = encode(secret);
  const params = {
    timestamp: timestamp.toString(),
    sign,
    msg_type: 'text',
    content: {
      text
    }
  };
  const { data: result } = await axios.post(
    webhook,
    params
  );
  return console.log(result);
};

send('request with sign');