AccessToken 2小時有效。
就不要每次都調取了,這樣會造成浪費。
或者存入Session中,設置過期時間。
或者存入Redis中,設置過期時間。
過期之后,進行重新獲取。
<?php
class WeixinAction extends CommonAction{
public $red;
const TOKEN_EXPIRES = 1000;
public function _initialize(){
parent::_initialize();
vendor('Func.Red');
$this->red = Red::create();
}
// 獲取access_token
public function get_access_token() {
// 查詢緩存中是否存在
$k = "access_token_".C('APPID');
if ($this->getCacheTtl($k)) {
return $this->getCache($k);
}
vendor('Func.Http');
// 獲取Token
$request_url = "https://api.weixin.qq.com/cgi-bin/token?";
$request_url .= "grant_type=client_credential&appid=".C('APPID')."&secret=".C('APP_SECRET');
$data = json_decode(Http::doGet($request_url,30),true);
$this->setCache($k,$data['access_token'],$data['expires_in'] - self::TOKEN_EXPIRES);
return $data['access_token'];
}
// 存
protected function setCache($k, $v, $expires = -1)
{
if ($expires == -1) {
return $this->red->set($k, $v);
} else {
return $this->red->setex($k, $expires, $v);
}
}
// 取
public function getCache($k) {
return $this->red->get($k);
}
// 查看剩余時間
public function getCacheTtl($k)
{
$ttl = $this->red->ttl($k);
if ($ttl != '-2') {
return $ttl;
} else {
return false;
}
}
// 查看是否存在
public function cacheExists($k)
{
return $this->red->exists($k);
}
}
想得到AccessToken需要知道AppID和AppSecret。這兩個數據,可以配置起來。
然后需要初始化Redis。
然后需要幾個獨立的Redis函數。
存儲,獲取,判斷是否過期。
判斷Redis中是否存在,且未過期。
如果有,直接獲取。
如果沒有,通過HttpGet請求,得到AccessToken。存入Redis中,並返回。
Redis很強大,只要保證key值不重復,就可以存儲任何數據。
這里key值通過AppID進行唯一標示,防止有別的access_token也要存儲。
PHP的redis擴展函數,功能強大!
