一、获取access_token
def get_access():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
返回结果如下:
{'access_token': '83_TAxuwdtIiaB-_UZHrzVUFSvuZ-TV4jG7NubqdhtOU8t2hyFMPpJeM3x0XP-p_UyNXYp1udnRYa77hVYKZzx4lqwpnvw66Y85pGVHeLpKTfuZ-7gTabjGgro1htELMFjAEAOPI','expires_in': 7200
}
二、发送消息
模板信息如下:
{{first.DATA}}
订单编号:{{keyword1.DATA}}
商品名称:{{keyword2.DATA}}
订单金额:{{keyword3.DATA}}
付款状态:{{keyword4.DATA}}
付款时间:{{keyword5.DATA}}
{{remark.DATA}}
代码实现如下:
acc = "83_TAxuwdtIiaB-_UZHrzVUFSvuZ-TV4jG7NubqdhtOU8t2hyFMPpJe******"url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accbody = {"touser": "用户的openid","template_id": "rbMtmDx5k1JdpGFKbgBowQoeKco7D2uQJFI3keiQ8dQ -- 模板id","url": "http://weixin.qq.com/download","data": {"first": {"value": "恭喜你购买成功!","color": "#173177"},"keyword1": {"value": "1234567"},"keyword2": {"value": "大白"},"keyword3": {"value": "12元"},"keyword4": {"value": "已付款"},"keyword5": {"value": "2024-10-01 12:00:00"}}}res = requests.post(url, json=body)print(res.json())
正常情况下返回结果:
{'errcode': 0, 'errmsg': 'ok', 'msgid': 3600641223326859267}
3.注意事项
1.测试时需要在服务号添加ip白名单,并等待10分钟生效
2.模板id在服务号的模板消息处获取
3.用户的openid一般在用户使用微信公众号登录时会获取,测试时可以在服务号后台的用户页面,在用户头像上右键在新标签中打开链接,里面的tofakeid=后面的值就是该用户的openid