Vercel
是一个用于前端框架和静态站点的平台,可以用来部署静态网站和 Serverless
函数,功能强大,使用方便。
企业微信提供一系列的
API 接口,可以通过企业微信应用或群机器人发送消息,而且企业微信接入了 MiPush,在
MIUI 系统上可以无后台接收消息。
但是发送企业微信应用消息比较麻烦,要先通过corpid和corpsecret获取access_token,然后通过
POST 请求发送消息。所以我利用 Vercel 搭建了一个 Serverless
函数,只需要一个token就可以发送消息,非常方便。
接口说明
请求地址为https://api.meancoder.xyz/push,参数如下:
| token | 
是 | 
在环境变量中设置的TOKEN,用于验证身份 | 
| content | 
是 | 
消息内容 | 
| msgtype | 
否 | 
text或markdown,默认为text | 
| touser | 
否 | 
指定接收消息的成员,默认为Mean | 
代码
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
   |  import requests import json import os import urllib.parse from http.server import BaseHTTPRequestHandler
 
  def push(content, touser, msgtype):     params = {         'corpid': os.environ['CORPID'],         'corpsecret': os.environ['CORPSECRET']     }     access_token = json.loads(requests.get(         'https://qyapi.weixin.qq.com/cgi-bin/gettoken', params=params).text)['access_token']     push_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+access_token     data = {         'msgtype': msgtype,         'agentid': os.environ['AGENTID'],         msgtype: {             'content': content         },         'touser': touser     }     response = requests.post(push_url, json=data)     return response.text
 
  class handler(BaseHTTPRequestHandler):
      def do_GET(self):         errcode = 0         errmsg = "ok"
          content = ""         touser = "Mean"         msgtype = "text"
          datas = urllib.parse.parse_qs(self.path.split("?")[1])
          if "token" not in datas:             errcode = -1             errmsg = "no token"         elif datas["token"][0] != os.environ["TOKEN"]:             errcode = -2             errmsg = "invalid token"
          if "content" in datas:             content = datas["content"][0]         else:             errcode = -3             errmsg = "no content"
          if "touser" in datas:             touser = datas["touser"][0]
          if "msgtype" in datas:             if datas["msgtype"][0] not in ["text", "markdown"]:                 errcode = -4                 errmsg = "invalid token"             else:                 msgtype = datas["msgtype"][0]
          if errcode == 0:             errmsg = push(content, touser, msgtype)         else:             errmsg = json.dumps({"errcode": errcode, "errmsg": errmsg})
          self.send_response(200)         self.send_header('Content-type', 'text/plain')         self.end_headers()         self.wfile.write(errmsg.encode())         return
 
  | 
 
重定向
由于 api
要放在/api路径下,默认是通过https://api.meancoder.xyz/api/push发送请求。如果在根目录配置vercel.json文件,就可以把/api重定向到根目录,就能直接通过https://api.meancoder.xyz/push发送请求了。
1 2 3 4 5 6 7 8
   | {   "rewrites": [     {       "source": "/:path*",       "destination": "/api/:path*"     }   ] }
  |