63 lines
1.8 KiB
Python
63 lines
1.8 KiB
Python
import requests
|
||
import json
|
||
from io import BytesIO
|
||
|
||
|
||
def upload_permanent_image_to_wechat(access_token, image_url):
|
||
"""
|
||
上传永久图片到微信公众号素材库
|
||
|
||
参数:
|
||
access_token (str): 公众号的access_token
|
||
image_url (str): 图片的URL地址
|
||
|
||
返回:
|
||
str: 成功时返回永久素材的media_id
|
||
None: 失败时返回None
|
||
"""
|
||
if not access_token or not image_url:
|
||
return None
|
||
|
||
# 微信上传永久素材接口(图片类型)
|
||
upload_url = f"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image"
|
||
|
||
try:
|
||
# 先从URL下载图片
|
||
image_response = requests.get(image_url, timeout=15)
|
||
image_response.raise_for_status() # 检查请求是否成功
|
||
|
||
# 检查图片大小(微信限制永久图片不超过2MB)
|
||
image_size = len(image_response.content)
|
||
if image_size > 2 * 1024 * 1024: # 2MB
|
||
return None
|
||
|
||
# 将图片内容转换为文件对象
|
||
image_file = BytesIO(image_response.content)
|
||
|
||
# 构造表单数据
|
||
files = {
|
||
'media': ('image.jpg', image_file, 'image/jpeg')
|
||
}
|
||
|
||
# 上传图片到微信服务器
|
||
response = requests.post(upload_url, files=files, timeout=15)
|
||
result = json.loads(response.text)
|
||
|
||
# 检查是否返回错误
|
||
if "errcode" in result and result["errcode"] != 0:
|
||
return None
|
||
|
||
# 返回media_id
|
||
media_id = result.get("media_id")
|
||
if media_id:
|
||
return media_id
|
||
else:
|
||
return None
|
||
|
||
except requests.exceptions.RequestException:
|
||
return None
|
||
except json.JSONDecodeError:
|
||
return None
|
||
except Exception:
|
||
return None
|