前言:
為了獲取一定高級(jí)操作,如:微信模板消息(xiao,xin)推送,把消息推送給用戶(hù),或者是獲取用戶(hù)授權(quán)信息都需要用到access token,有效期為兩個(gè)小時(shí)?
過(guò)了兩個(gè)小時(shí)怎么辦?重新獲取,來(lái),代碼擼起走,啥女朋友沒(méi)有?
獲取小程序?qū)?yīng)的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過(guò)期,重新寫(xiě)入文件的內(nèi)容>>>', 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
并判斷是否過(guò)期
def get_access_token():
try:
with open(token_file, "r") as f:
content = f.read()
data_dict = content
# 如果緩存內(nèi)容為空,直接重新獲取token
if (content == ''):
print("token文件為空,重新獲取并寫(xiě)入文件")
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過(guò)期,重新獲取并寫(xiě)入文件")
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)
根據(jù)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'))
返回?cái)?shù)據(jù)示例
{
"errcode": 0,
"errmsg": "ok",
"list": [
{
"template_id": "wDYzYZVxobJivW9oMpSCpuvACOfJXQIoKUm0PY397Tc",
"title": "購(gòu)買(mǎi)成功通知",
"content": "購(gòu)買(mǎi)地點(diǎn){{keyword1.DATA}}\n購(gòu)買(mǎi)時(shí)間{{keyword2.DATA}}\n物品名稱(chēng){{keyword3.DATA}}\n",
"example": "購(gòu)買(mǎi)地點(diǎn):TIT造艦廠\n購(gòu)買(mǎi)時(shí)間:2016年6月6日\(chéng)n物品名稱(chēng):咖啡\n"
}
]
}
有任何問(wèn)題,留言聯(lián)系我。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
