php微信token存储,php获取微信公众帐号access_token存储并长期使用

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 );

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值