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

前言:

爲了獲取必定高級操做,如:微信模板消息(xiao,xin)推送,把消息推送給用戶,或者是獲取用戶受權信息都須要用到access token,有效期爲兩個小時?express

過了兩個小時怎麼辦?從新獲取,來,代碼擼起走,啥女友沒有?json

獲取小程序對應的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"
    }
  ]
}

有任何問題,留言聯繫我。

相關文章
相關標籤/搜索