Files
yidaima_tools/docs/公众号.md

85 lines
3.1 KiB
Markdown
Raw Normal View History

2026-04-09 14:55:54 +08:00
在 Python 中推送文章到微信公众号草稿箱,主要通过微信提供的 **草稿箱 API** 实现。
这个过程通常分为三步:**获取 Access Token**、**上传封面图(素材)**、以及 **新增草稿**
---
### 1. 前期准备
你需要先在 [微信公众平台](https://mp.weixin.qq.com/) 获取以下信息:
* **AppID**
* **AppSecret**
* **白名单配置**:确保你运行代码的服务器 IP 已加入公众号后台的 IP 白名单。
### 2. 核心流程与代码实现
我们可以使用 Python 的 `requests` 库来完成。
#### 第一步:获取 Access Token
这是调用所有 API 的“通行证”。
```python
import requests
import json
def get_access_token(appid, secret):
url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"
res = requests.get(url).json()
return res.get('access_token')
```
#### 第二步:上传封面图片
草稿箱要求文章必须有封面图,且封面图需要先上传到微信服务器获取 `thumb_media_id`
```python
def upload_thumb(access_token, image_path):
url = f"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image"
files = {'media': open(image_path, 'rb')}
res = requests.post(url, files=files).json()
return res.get('media_id') # 这就是 thumb_media_id
```
#### 第三步:推送至草稿箱
最后将文章标题、正文HTML 格式)和封面 ID 提交。
```python
def add_draft(access_token, title, content, thumb_id):
url = f"https://api.weixin.qq.com/cgi-bin/draft/add?access_token={access_token}"
# 文章数据结构
articles = {
"articles": [
{
"title": title,
"author": "YourName",
"digest": "摘要内容",
"content": content, # 支持 HTML 格式
"content_source_url": "", # 阅读原文链接
"thumb_media_id": thumb_id,
"need_open_comment": 0 # 是否打开评论
}
]
}
# 微信 API 要求发送 JSON 字符串,且处理中文需确保编码正确
data = json.dumps(articles, ensure_ascii=False).encode('utf-8')
res = requests.post(url, data=data).json()
return res
```
---
### 3. 常见问题提示
* **图片问题**:如果你在 `content`(正文)里引用了外部图片链接,微信可能会屏蔽它们。建议先通过 `cgi-bin/media/uploadimg` 接口将图片上传到微信图床,获取微信内部链接后再放入 HTML 中。
* **API 限制**:草稿箱 API 每天的调用次数有限(通常为 10,000 次),对于个人/小团队来说完全够用。
* **HTML 标签**:微信正文支持的 HTML 比较基础,复杂的 CSS 样式可能会被过滤,建议使用标准的 `p`, `span`, `strong`, `img` 等标签。
---
### 快速总结工具
| 步骤 | API 接口 | 目的 |
| :--- | :--- | :--- |
| 1 | `/cgi-bin/token` | 获取授权凭证 |
| 2 | `/cgi-bin/material/add_material` | 获取封面图 ID |
| 3 | `/cgi-bin/draft/add` | 写入草稿箱 |