微信公眾平臺開發—access_token的獲取儲存與更新(Python開發)
access_token是公眾號的全域性唯一票據,公眾號呼叫各介面時都需使用access_token。
正常情況下access_token有效期為7200秒,重複獲取將導致上次獲取的access_token失效。由於獲取access_token的api呼叫次數非常有限,建議開發者全域性儲存與更新access_token,頻繁重新整理access_token會導致api呼叫受限,影響自身業務。
要解決的問題
1、如何獲取access_token。
2、由於access_token的有效期為7200秒,即2小時,並且重複獲取將導致上次獲取的access_token失效,獲取access_token的api呼叫次數非常有限,所以要解決如何全域性儲存與更新access_token。
解決方案
1、access_token放入資料庫。
2、access_token在建立URL、Token連結時生成,放入快取。
我們選擇了放入快取的方案。放入資料庫也需要每次訪問時重新整理access_token,以保證資料的有效性。
access_token怎麼更新呢?
access_token失效更新後,怎麼判斷access_token有沒有失效呢?
使用當前的access_token請求微信介面,獲取自定義選單,如果返回的errcode為42001,則說明access_token已經失效,這時再重新獲取access_token。
程式碼
python提供了快取引入機制
from django.core.cache import cache
引入快取後,定義和微信介面相關的變數
class AppItem(models.Model): Token = models.CharField(max_length=128, unique=True, blank=True, null=True, verbose_name='token', db_index=True) Appid = models.CharField(max_length=128, blank=True, null=True, verbose_name='APPID') App_secret = models.CharField(max_length=128, blank=True, null=True, verbose_name='APP_SECRET')
建立和微信的基礎連結,需要Token and AppID
Token = models.CharField(max_length=128, unique=True, blank=True, null=True, verbose_name='token', db_index=True)
定義了Token
Appid = models.CharField(max_length=128, blank=True, null=True, verbose_name='APPID')
定義了AppID
App_secret = models.CharField(max_length=128, blank=True, null=True, verbose_name='APP_SECRET')
微信的加密結構
定義了和微信的基礎介面關係後,開始定義access_token的函式
def get_token(self):
token_cache_key = TOKEN_CACHE_PRE+'_'+self.token #對不同的app指定不同的快取
token = cache.get(token_cache_key)
if token:
return token
else:
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (self.appid, self.app_secret)
dict_data = method_get_api(url)
token = dict_data.get('access_token')
expires_in = dict_data.get('expires_in')
if token and expires_in:
cache.set(token_cache_key, token, expires_in-60)
return token or ''
微信中的服務有很多,圖文訊息、支付、卡券、微店、紅包等。不同的python的app都有不同的快取。
針對不同的快取提供不同的token_cache_key
token_cache_key = TOKEN_CACHE_PRE+'_'+self.token #對不同的app指定不同的快取
token = cache.get(token_cache_key)
token可能獲得成功,也可能“過期(失效)”;失效後,重新建立微信的access_token。
if token:
return token
else:
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (self.appid, self.app_secret)
access_token獲得後,分配Python的app快取和微信access_token的配對,並且在其它應用重新整理了access_token後能夠及時獲得新的token。
dict_data = method_get_api(url)
token = dict_data.get('access_token')
expires_in = dict_data.get('expires_in')
if token and expires_in:
cache.set(token_cache_key, token, expires_in-60)
return token or ''
特別提醒: 不同的微信應用 —— 如: 圖文訊息或者客服介面(48小時有效),與,卡券會遇到重新整理access_token的情況;任何一個服務重新整理的access_token其它服務調取的時候都要重新“生成或者讀取最新的”access_token。