大模型落地开发实战指南!请关注微信公众号:「AGI启程号」 深入浅出,助你轻松入门!
数据分析、深度学习、大模型与算法的综合进阶,尽在CSDN博客主页
本文将详细介绍如何在 Vercel 平台上部署 自动微信公众号文章获取 项目,包括项目结构、代码实现、部署流程以及常见问题的解决方案。
注意:本项目源代码github链接,可自行克隆到自己的代码仓库完成vercel部署,注意需要稳定ip输出(微信白名单需求),免费版只用作部署测试,最好是自己租服务器部署或者用vercel企业版。
最终结果:可以看到已经能获取到草稿箱中已经发布过的文章(注意这里我获取的是草稿箱中的文章,原因是群通知发布的文章没有对应api进行获取,所以需要保证文章在发布前尽心一次草稿箱保存)
本文将详细介绍如何用 FastAPI + Vercel Serverless 部署一个可获取微信公众号草稿箱文章的 API,包括项目结构、核心代码解析、部署方法、注意事项与常见问题处理。
微信公众号文章获取/
├── api/
│ └── index.py # FastAPI 主应用,所有API入口
├── requirements.txt # Python 依赖
├── Pipfile # Python 环境配置(可选)
├── vercel.json # Vercel 路由配置
├── .gitignore # Git 忽略文件
└── test_api2.ipynb # Jupyter Notebook 示例(本地开发用,已被 .gitignore 忽略)
import os
import time
import requests
from fastapi import FastAPI, HTTPException
from dotenv import load_dotenv
# 加载本地 .env(生产环境下在 Vercel Dashboard 配置环境变量,无需 .env)
load_dotenv()
APPID = os.getenv("APPID")
SECRET = os.getenv("APPSecret")
if not APPID or not SECRET:
raise RuntimeError("Missing APPID or APPSecret environment variables")
_token = {}
def get_access_token(force: bool = False) -> str:
"""获取并缓存 access_token;提前 5 分钟失效"""
info = _token.get("wx")
if info and info["expire_at"] > time.time() and not force:
return info["token"]
resp = requests.get(
"https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": APPID,
"secret": SECRET
},
timeout=10
).json()
if "access_token" not in resp:
raise RuntimeError(f"WX API error: {resp}")
_token["wx"] = {
"token": resp["access_token"],
"expire_at": time.time() + resp["expires_in"] - 300
}
return resp["access_token"]
def _parse_draft(item: dict):
"""拆分草稿列表中的每篇文章,只保留关键字段"""
ts = time.strftime("%Y-%m-%d %H:%M", time.localtime(item["update_time"]))
for art in item["content"]["news_item"]:
yield {
"updated": ts,
"title": art.get("title", ""),
"url": art.get("url", ""),
"digest": art.get("digest", "")
}
def list_drafts(offset: int = 0, count: int = 20):
"""拉取一页草稿并返回 (列表, 总数)"""
ak = get_access_token()
resp = requests.post(
f"https://api.weixin.qq.com/cgi-bin/draft/batchget?access_token={ak}",
json={"offset": offset, "count": count},
timeout=10
)
resp.encoding = "utf-8"
data = resp.json()
if "item" not in data:
raise RuntimeError(f"WX API error: {data}")
rows = []
for it in data["item"]:
rows.extend(_parse_draft(it))
return rows, data["total_count"]
# ------ FastAPI 应用 & 路由 ------
app = FastAPI(title="微信草稿箱 API")
@app.get("/")
async def get_drafts(offset: int = 0, count: int = 20):
"""
获取草稿列表
- offset: 从第几条开始(默认 0)
- count: 本次拉取数量(默认 20)
返回 JSON: { items: [...], total_count: N }
"""
try:
items, total = list_drafts(offset, count)
return {"items": items, "total_count": total}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
代码要点:
APPID
和 APPSecret
,安全灵活。/
路由支持分页参数,返回所有草稿文章的关键信息。fastapi==0.104.1
requests
python-dotenv
{
"routes": [
{ "src": "/(.*)", "dest": "api/index.py" }
]
}
api/index.py
,由 FastAPI 应用分发。.env
、test_api2.ipynb
、__pycache__
、.vercel
等,保证敏感和本地文件不会上传。git init
git add .
git commit -m "init: wechat article api"
git remote add origin https://github.com/your-username/your-repo.git
git push -u origin main
APPID
和 APPSecret
(在 Vercel 项目 Settings → Environment Variables)。npm install -g vercel
vercel login
vercel
APPID
和 APPSecret
。pip install -r requirements.txt
uvicorn api.index:app --reload
http://localhost:8000/?offset=0&count=20
invalid ip ... not in whitelist
34.235.166.164
)加入白名单。requirements.txt
包含 fastapi
、requests
、python-dotenv
。.env
,线上在 Vercel 控制台设置。api/index.py
作为主入口,vercel.json
路由所有请求到此文件。.gitignore
已包含 test_api2.ipynb,Notebook 仅本地开发用,不会上传。本项目通过 FastAPI + Vercel Serverless 实现了微信公众号草稿箱文章的高效获取,结构极简,部署便捷。
如遇问题,优先检查依赖、环境变量、vercel.json 配置和微信白名单设置。
欢迎参考本项目进行二次开发或集成到更大的系统中!
如需转载或引用,请注明出处。
如有疑问或建议,欢迎留言交流!