Skip to content

企业微信+Server酱CloudFlare Serverless实现消息的自动推送

昨天试的是PHP版本(本馆档案),今天试试用CloudFlare搭建Serverless的方法。

参考

https://www.hostloc.com/thread-807156-1-1.html

JS代码


//教程:https://shimo.im/docs/38dpjtwWtRRVQ6Wy/read
const OPT = {
  corpid : '',//企业id
  agentid:'',//应用id
  corpsecret:'', //应用secret

  access_token:undefined
}

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

/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
  let url = new URL(request.url);
  //消息title
  let title = url.searchParams.get('title')||"Server酱默认通知";
  //消息内容
  let description = url.searchParams.get('description')||url.searchParams.get('msg')||"默认通知内容";
  //跳转地址
  let jumpUrl = url.searchParams.get('url')||"URL";

  //获取access_token,写入OPT中
  let msg = await getAccessToken();
  if(msg.errcode){
    return new Response(JSON.stringify(msg), {
      status: 200,
      headers:{
        'content-type':'application/json; charset=UTF-8'
      }
    })
  }

  //发送消息
  return await pushMsg(title, description, jumpUrl);
}

//获取access_token,写入OPT中
async function getAccessToken(){
  let result = await fetch("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+OPT.corpid+"&corpsecret="+OPT.corpsecret);
  let json = await result.json();
  console.log(json)
  if(json.errcode==0){
    OPT.access_token = json.access_token
  }
  return json
}

//发送消息
async function pushMsg(title, description,url="URL",btntxt="更多"){
  let body = {
    /**
     * 指定接收消息的成员,成员ID列表(多个接收者用‘|’分隔,最多支持1000个)。
     * 特殊情况:指定为”@all”,则向该企业应用的全部成员发送
     */
    "touser" : "@all",//非必须,但touser、toparty、totag不能同时为空,后面不再强调。
    /**
     * 指定接收消息的部门,部门ID列表,多个接收者用‘|’分隔,最多支持100个。
     * 当touser为”@all”时忽略本参数
     */
    //"toparty" : "PartyID1|PartyID2",//非必须
    /**
     * 指定接收消息的标签,标签ID列表,多个接收者用‘|’分隔,最多支持100个。
     * 当touser为”@all”时忽略本参数
     */
    //"totag" : "TagID1 | TagID2",//非必须
    "msgtype" : "textcard",//必须,消息类型,此时固定为:textcard
    "agentid" : OPT.agentid,//企业应用的id,整型。企业内部开发,可在应用的设置页面查看;第三方服务商,可通过接口 获取企业授权信息 获取该参数值
    "textcard" : {
      "title" : title,//必须,标题,不超过128个字节,超过会自动截断(支持id转译)
      "description" : description, //必须,消息内容,最长不超过2048个字节,超过将截断(支持id转译)
      "url": url,//点击后跳转的链接。最长2048字节,请确保包含了协议头(http/https)
      "btntxt":btntxt //非必须,按钮文字。 默认为“详情”, 不超过4个文字,超过自动截断。
    },
    "safe":0, //非必须, 表示是否是保密消息,0表示可对外分享,1表示不能分享且内容显示水印,默认为0
    "enable_id_trans": 0,//非必须,表示是否开启id转译,0表示否,1表示是,默认0。仅第三方应用需要用到,企业自建应用可以忽略。
    "enable_duplicate_check": 1,//非必须,表示是否开启重复消息检查,0表示否,1表示是,默认0
    "duplicate_check_interval": 1800 //非必须,表示是否重复消息检查的时间间隔,默认1800s(3小时),最大不超过4小时
  }

  return fetch("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+OPT.access_token,{
    method:'post',
    body: JSON.stringify(body)
  });
}

开启新的域名+Worker+路由

试验

Leave a Reply

Your email address will not be published.