php缓存accestoken_php微信开发(1):缓存access_token的方法
语言:PHP
access_token一直要用,但每天取的数量有限制。反正2小时才过期。就想缓存一下。
File1: wx_access_token.php
File2: file_cache.php
---------------------------
File1: wx_access_token.php <?php
/*
* wx_access_token.php
*
* get the weixin access token
* */
if (!defined("DOCUMENT_ROOT")) define("DOCUMENT_ROOT", $_SERVER['DOCUMENT_ROOT']);
if (!defined("__HOME__")) define("__HOME__", dirname(DOCUMENT_ROOT));
require_once("file_cache.php");
class WxAccessToken{
public function getToken(){
$wx_access_token_cache_key = 'wx_access_token';
$cache = new FileCache(__HOME__ . '/myfolder/cache_file.txt');
$token = $cache->get($wx_access_token_cache_key);
if (!$token){
$token = $this->getTokenFromWx();
$cache->set($wx_access_token_cache_key, $token, time()+7000);
}
return $token;
}
private function getTokenFromWx(){
$appid = "your appid";
$appsecret = "your app secret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$jsoninfo = json_decode($output, true);
return $jsoninfo["access_token"];
}
}
?>
File2: file_cache.php
/*
* file_cache.php
*
* cache objects via json with filesystem
* author: hydon lee
* */
/*
class FileCache
examples:
$cache = new FileCache('../myfolder/cache_file.txt');
$cache->set('username', 'lihd', time()+3600);
$username = $cache->get('username');
echo $username;
*/
class FileCache{
private $cache_file;
private function load(){
if(file_exists($this->cache_file)){
$content = file_get_contents($this->cache_file);
if (strlen($content) > 0){
$data = json_decode($content);
return $data;
}
}
return array();
}
private function save($data){
$content = json_encode($data);
return file_put_contents($this->cache_file, $content);
}
public function __construct($filename) {
$this->cache_file = $filename;
}
public function get($key){
$data = $this->load();
foreach($data as $item){
if ($item->key == $key){
if ($item->expire_time > time()){
return $item->value;
}
break;
}
}
return NULL;
}
public function set($key, $value, $expire_time=NULL){
$data = $this->load();
$obj = NULL;
foreach($data as $item){
if ($item->key == $key){
$obj = $item;
$obj->value = $value;
if ($expire_time != NULL){
$obj->expire_time = $expire_time;
}
break;
}
}
if ($obj == NULL){
$obj = new CacheItem($key, $value, $expire_time);
array_push($data, $obj);
}
return $this->save($data);
}
}
class CacheItem{
public $key;
public $value;
public $expire_time;
public function __construct($key, $value, $expire_time) {
$this->key = $key;
$this->value = $value;
$this->expire_time = $expire_time;
}
}
?>