经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 微信小程序 » 查看文章
基于python 微信小程序之获取已存在模板消息列表
来源:jb51  时间:2019/8/5 10:53:32  对本文有异议

前言:

为了获取一定高级操作,如:微信模板消息(xiao,xin)推送,把消息推送给用户,或者是获取用户授权信息都需要用到access token,有效期为两个小时?

过了两个小时怎么办?重新获取,来,代码撸起走,啥女朋友没有?

获取小程序对应的access token

  1. def get_wx_token():
  2. url = "https://api.weixin.qq.com/cgi-bin/token?"
  3. try:
  4. respone = requests.get(url, params=payload, timeout=50)
  5. access_token = respone.json().get("access_token")
  6. res = respone.json()
  7. res["time"] = stamp
  8. print(u'token过期,重新写入文件的内容>>>', res)
  9. with open(token_file, "w+") as f:
  10. f.write(json.dumps(res))
  11. return access_token
  12. except Exception as e:
  13. msg = traceback.format_exc()
  14. print('get token error', msg)
  15. return

并判断是否过期

  1. def get_access_token():
  2.  
  3. try:
  4. with open(token_file, "r") as f:
  5. content = f.read()
  6. data_dict = content
  7. # 如果缓存内容为空,直接重新获取token
  8. if (content == ''):
  9. print("token文件为空,重新获取并写入文件")
  10. result = get_wx_token()
  11. return result
  12. else:
  13. data_dict = re.sub('\'', '\"', data_dict)
  14. token_time = int(json.loads(data_dict)['time'])
  15. if (stamp - token_time) > 7100:
  16. # print("token过期,重新获取并写入文件")
  17. get_wx_token()
  18. else:
  19. return json.loads(data_dict)['access_token']
  20. except Exception as e:
  21. msg = traceback.format_exc()
  22. print("access token express time", msg)

根据access token 获取模板列表

  1. def get_templates_list(access_token):
  2. url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token={}".format(access_token)
  3. data = {
  4. "offset": 0,
  5. "count": 20
  6. }
  7. r = requests.post(url,data=json.dumps(data)).json()
  8. tpl_list = r.get('list')
  9. for tpl in tpl_list:
  10. print(tpl)
  11. # print(r.get('list'))

返回数据示例

  1. {
  2. "errcode": 0,
  3. "errmsg": "ok",
  4. "list": [
  5. {
  6. "template_id": "wDYzYZVxobJivW9oMpSCpuvACOfJXQIoKUm0PY397Tc",
  7. "title": "购买成功通知",
  8. "content": "购买地点{{keyword1.DATA}}\n购买时间{{keyword2.DATA}}\n物品名称{{keyword3.DATA}}\n",
  9. "example": "购买地点:TIT造舰厂\n购买时间:2016年6月6日\n物品名称:咖啡\n"
  10. }
  11. ]
  12. }

总结

以上所述是小编给大家介绍的基于python 微信小程序之获取已存在模板消息列表,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对w3xue网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号