微信api文档让人看起来很头大,新手开发会对着文档死磕,但当重复的事情做的多了以后,比如access_token,js_ticket等等参数的获取,不同项目中用一次封装一次。 这个时候就该考虑是否有现成的解决方案,把时间花在自己的业务上边。
今天我们来介绍下适用于python的微信公众号sdk—wechatpy,使用flask作web框架的也可以使用flask-wechatpy
简单示例:
from wechatpy import WeChatClient
# 很简单 这样就实例化了一个wechat应用
client = WeChatClient(appID, appSecrete)
如果自己要实现一个获取access_token
,js_ticket
的功能,我们要写这么多代码
现在只需要这样:
client.access_token
封装的更多api
包括持久化存储
顺便记录下我使用过程中的坑
被动回复图片消息
sdk是这样定义的
其实一直不明白这个media_id从哪来,直接传url
也不行。后来研究了很久
发现是依靠另一个接口,上传素材来获取media_id
,当然你会说这不是跟描述的一样。
扫描二维码关注公众号,回复:
5144366 查看本文章
这个怎么说呢,懂的人怎么都懂。。不懂的人绕不过去这个弯
两个接口联系起来
# 引入消息回复模块
from wechatpy import WeChatClient
from flask_wechatpy import Wechat, wechat_required, oauth
from wechatpy.replies import TextReply, ImageReply
@app.route('/wx', methods=['GET', 'POST'])
@wechat_required
def wechat_handler():
client = WeChatClient(appID, appSecrete)
msg = request.wechat_msg
if msg.type == 'text':
reply = TextReply(content=msg.content, message=msg)
else:
reply = ImageReply(message=msg)
reply.media_id = get_media_id(client, msg)
return reply
def get_media_id(client, msg):
path = "图片文件路径"
with open(path, "rb") as file:
msg = client.material.add(media_type="image", media_file=file)
media_id = msg["media_id"]
return media_id