header("Content-type: text/html; charset=utf-8");
$apitest = new GetWeixinToken ();
$apitest->cacheData('weixin_access_token');//获取微信公众号的access_token
class GetWeixinToken {
private $_dir;
const EXT = '.php';
private $app_id;//微信公众号app_id
private $appsecret;//微信公众号apsecret
public function __construct() {
$this->app_id = '你的微信appid';
$this->appsecret = '你的apsecret';
$this->_dir = dirname(__FILE__) . '/files/';
}
//获取微信公众号access_token
public function getAccessToken(){
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->app_id.'&secret='.$this->appsecret;
$token_json = $this->get_url($url);
$token_arr = json_decode( $token_json, true );
if( array_key_exists('errcode', $token_arr) ){
exit( $token_arr['errmsg'] );
}else{
return $token_arr;
}
}
//将获取到的access_token保存到缓存文件,以备长期使用
//$key : 自定义文件名
//$value : 写入缓存的数据
public function cacheData($key,$expires="7200"){
$filename = $this->_dir . $key . self::EXT;
//获取缓存时,判断文件是否存在
if(!is_file($filename)) {
$value = $this->getAccessToken();//获取微信公众号的access_token
if($value !== '') { // 将value值写入缓存
$dir = dirname($filename);
if(!is_dir($dir)) {
mkdir($dir, 0777);
}
$is_write_ok = file_put_contents($filename,json_encode($value));//写入数据
if( $is_write_ok ){
echo '直接获取'.$value['access_token'];
}
}
}else{
$file_modfiy_time = filemtime ( $filename );//获取文件的上次修改时间
//如果当前时间距上次缓存的修改时间小于access_token的有效时间将不去写入缓存
if( time() - $file_modfiy_time < $expires ){
$contents = file_get_contents($filename);
$access_token = json_decode( $contents ,true);
echo '获取缓存'.$access_token['access_token'];
}else{
@unlink( $filename );//删除缓存文件
$this->cacheData($key);
}
}
}
/**
* @param str $url post传递的url地址
* @return string
*/
public function get_url($url){
//2初始化
$ch = curl_init();
//3.设置参数
curl_setopt($ch , CURLOPT_URL, $url);
curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
//4.调用接口
$res = curl_exec($ch);
if( curl_errno($ch) ){
exit( curl_error() );
exit();
}else{
return $res;
//5.关闭curl
curl_close( $ch );
}
}
}