class WeChat{ private $_appid; private $_appsecret; private $_token; public function __construct($_appid,$_appsecret,$_token){ $this->_appid = $_appid; $this->_appsecret = $_appsecret; $this->_token = $_token; } public function _request($curl,$https=true,$method=‘GET‘,$data=null){ $ch = curl_init();//初始化 curl_setopt($ch,CURLOPT_URL,$curl);//URL curl_setopt($ch,CURLOPT_HEADER,false);// curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); if($https){ curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,true); } if($method == ‘POST‘){ curl_setopt($ch,CURLOPT_POST,true); curl_setopt($ch,CURLOPT_POSTFIELDS,$data); } $content = curl_exec($ch); curl_close($ch); return $content; } public function _getAccessToken(){ $file = ‘./accesstoken‘; if(file_exists($file)){ $content = file_get_contents($file); $content = json_decode($content); if(time() - filemtime($file)<$content->expires_in){ return $content->access_token; } } $curl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_appid."&secret=".$this->_appsecret; $content = $this->_request($curl); file_put_contents($file,$content); $content = json_decode($content); return $content->access_token; } } $wechat = new WeChat(‘wxb7e7af838ec6bed2‘,‘d4624c36b6795d1d99dcf0547af5443d‘,‘‘); echo $wechat->_getAccessToken();
原文:http://www.cnblogs.com/longfeiPHP/p/5119101.html