/** * 微信公众平台操作类 */ class WeChat { private $_appid; private $_appsecret; public function __construct($id,$secret){ $this->_appid = $id; $this->_appsecret = $secret; } /** * 获取 access_tonken * @param string $token_file,用来存在token的临时文件 */ public function getAccessToken($token_file="./access_tonken"){ //考虑过期实际,获取的access_token存储到某个文件中 $life_time = 7200; if(file_exists($token_file) && time()-filemtime($token_file)<$life_time){ //存在有效的access_token $str = file_get_contents($token_file); return $str; } //目标url $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appid}&secret={$this->_appsecret}"; //向url发送get请求 $result = $this->_requestGet($url); if(!$result){ return false; } //存在返回响应的结果 $result_obj = json_decode($result,true); //写入 file_put_contents($token_file, $result_obj['access_token']); return $result_obj['access_token']; } /** * 发送GET请求的方法 * @param string $url URL * @param bool $ssl 是否为https协议 * @return string 响应主体Content */ public function _requestGet($url,$ssl=true){ //curl完成 $curl = curl_init(); //设置curl选项 curl_setopt($curl, CURLOPT_URL, $url); //请求代理信息 $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36"; curl_setopt($curl, CURLOPT_USERAGENT,$user_agent); //referer头,请求来源 curl_setopt($curl, CURLOPT_AUTOREFERER, true); //SSL相关的 if($ssl){ //禁用后curl将终止从服务端进行验证 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //检查服务器ssl证书中是否存在一个公用名(commont name) // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); //是否返回响应头 curl_setopt($curl, CURLOPT_HEADER, false); //是否返回响应结果 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //发送请求 $response = curl_exec($curl); if (false == $response) { echo "<br />", curl_error($curl),"<br />"; return false; } return $response; } }