基于python 微信小程序之获取已存在模板消息列表

前言:

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

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

获取小程序对应的access token

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

并判断是否过期

def get_access_token():

try:
    with open(token_file, "r") as f:
        content = f.read()
        data_dict = content
        # 如果缓存内容为空,直接重新获取token
        if (content == ''):
            print("token文件为空,重新获取并写入文件")
            result = get_wx_token()
            return result
        else:
            data_dict = re.sub('\'', '\"', data_dict)
            token_time = int(json.loads(data_dict)['time'])
            if (stamp - token_time) > 7100:
                # print("token过期,重新获取并写入文件")
                get_wx_token()
            else:
                return  json.loads(data_dict)['access_token']
except Exception as e:
    msg = traceback.format_exc()
    print("access token express time", msg)
    


根据access token 获取模板列表

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

返回数据示例

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

有任何问题,留言联系我。

    原文作者:moss1993
    原文地址: https://segmentfault.com/a/1190000019967171
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞