
WechatPy 是一个功能强大的微信公众平台第三方 Python SDK,它简化了与微信服务器交互的复杂性,让开发者能够更专注于业务逻辑的实现。本文将介绍 WechatPy 的主要功能和使用方法,并提供实用的代码示例。
WechatPy 支持微信公众平台、企业微信、微信支付等多种微信生态功能:
使用 pip 命令即可轻松安装 WechatPy:
pip install wechatpy如需升级到最新版本:
pip install -U wechatpyfrom wechatpy import WeChatClient
# 公众号配置
appid = 'your_appid'appsecret = 'your_appsecret'
# 创建客户端实例
client = WeChatClient(appid, appsecret)# 获取 access_token
access_token = client.fetch_access_token()
print(f"Access Token: {access_token}")
# 也可以直接使用 client 的方法,它会自动处理
tokenuser_info = client.user.get('openid')from wechatpy import parse_message
from wechatpy.replies import TextReply
# 解析用户消息
xml = """<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
<MsgId>1234567890123456</MsgId>
</xml>"""
msg = parse_message(xml)
# 创建回复消息
ifmsg.type == 'text':
reply = TextReply(content=f"收到你的消息: {msg.content}", message=msg)
reply_xml = reply.render()
print(reply_xml)template_id = 'your_template_id'
openid = 'user_openid'
data = {
'first': {'value': '您好,您有新的订单'},
'keyword1': {'value': '202308080001'},
'keyword2': {'value': '¥99.00'},
'remark': {'value': '感谢您的惠顾!'}
}
# 发送模板消息
result = client.message.send_template(openid, template_id, data)
print(f"模板消息发送结果: {result}")from wechatpy.pay import WeChatPay
# 支付配置
pay_config = {
'appid': 'your_appid',
'api_key': 'your_api_key',
'mch_id': 'your_mch_id',
'mch_cert': '/path/to/cert.pem',
'mch_key': '/path/to/key.pem'}
# 创建支付客户端
pay_client = WeChatPay(**pay_config)
# 统一下单
order = pay_client.order.create(
trade_type='JSAPI',
body='测试商品',
total_fee=100,
notify_url='https://your.domain.com/notify',
openid='user_openid',
out_trade_no='202308080001'
)
print(f"支付订单创建结果: {order}")from wechatpy.enterprise import WeChatClientasQyWeChatClient
# 企业微信配置
corp_id = 'your_corp_id'
corp_secret = 'your_corp_secret'
# 创建企业微信客户端
qy_client = QyWeChatClient(corp_id, corp_secret)
# 发送企业微信消息
qy_client.message.send_text(
agent_id=1000002,
user_ids=['user1', 'user2'],
content='企业微信消息测试'
)from wechatpy.miniprogram import Cloud
# 小程序配置
appid = 'your_miniprogram_appid'
appsecret = 'your_miniprogram_secret'
# 创建云开发客户端
cloud = Cloud(appid, appsecret)
# 调用云函数
result = cloud.call_function(
name='testFunction',
data={'x': 1, 'y': 2}
)
print(f"云函数调用结果: {result}")WechatPy 为 Python 开发者提供了全面且易用的微信生态开发工具,无论是公众号开发、企业微信应用还是微信支付集成,都能通过简洁的 API 快速实现。其丰富的功能和良好的文档支持,使其成为微信开发的优选 SDK。
更多详细信息和最新功能,请参考官方文档和 GitHub 仓库:https://github.com/wechatpy/wechatpy
“无他,惟手熟尔”!有需要就用起来。
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!