虽然长期以来都在用 telegram 的 pushbot,但是还是多一点统治手段比较好,毕竟不是什么时候 tg 都在线,微信的在线时间反而会更有保证一些。以前的 ServerChan 现在也限制每天五条了,有时候会不够用。想起 21 年的时候试过用企业微信来推送通知,后面丢失了源码和 Key 就没用了。重新弄了一下发现还是可以用的。发出来以供备份。

需要用到的参数

参数 类型 必选 描述 示例
id str true 企业微信公司id
secert str true 企业微信应用的应用secert
agentId int true 企业微信应用的应用agentId 1000002
msg str true 需要发送的内容 test

搭建起来很简单,将下列代码复制到 worker.js 中,即可。

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

// 获取Token
async function getTocken(id, secert, msg, agentId) {
  const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${id}&corpsecret=${secert}`;

  const response = await fetch(url);
  const data = await response.json();
  const token = data.access_token;
  return sendText(token, agentId, msg);
}

// 发送文本信息
async function sendText(token, agentId, msg) {
  const sendUrl = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${token}`;
  const data = JSON.stringify({
    "safe": 0,
    "touser": "@all",
    "msgtype": "text",
    "agentid": agentId,
    "text": {
      "content": msg
    }
  });

  const response = await fetch(sendUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: data
  });
  return response.json();
}

async function handleRequest(request) {
  const { searchParams } = new URL(request.url);
  let status = 0, apimsg = '';

  // 读取参数
  const apiId = searchParams.get('id');
  const apiSecert = searchParams.get('secert');
  const apiAgentId = searchParams.get('agentId');
  const apiMsgParam = searchParams.get('msg');

  if (!apiId || !apiSecert || !apiAgentId || !apiMsgParam) {
    apimsg = '有必填参数没有填写,请检查是否填写正确和格式是否错误。';
    status = 1;
  } else {
    try {
      // 执行主程序
      await getTocken(apiId, apiSecert, apiMsgParam, apiAgentId);
    } catch (error) {
      status = 1;
      apimsg = '主程序运行时出现错误,请检查参数是否填写正确。';
    }
  }

  return new Response(JSON.stringify({
    "status": status,
    "msg": apimsg
  }), {
    headers: { 'Content-Type': 'application/json' },
  });
}

然后请求 https://xxx.xxx.workers.dev/?id=xxx&secert=xxx&agentId=xxx&msg=test 即可成功发送信息到微信。

由于workers.dev在国内被污染了,所以如果要在国内使用最好绑定自己的域名。