获取微信基础接口凭证Access_token

来源:互联网 发布:手动安装windows补丁 编辑:程序博客网 时间:2024/04/25 02:23

access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

使用AppID和AppSecret调用本接口来获取access_token。AppID和AppSecret可在微信公众平台官网-开发者中心页中获得。

1. 构造一个请求函数

[php] view plain copy
  1. //设置网络请求配置  
  2. public function _request($curl,$https=true,$method='GET',$data=null){  
  3.     // 创建一个新cURL资源  
  4.     $ch = curl_init();  
  5.       
  6.     // 设置URL和相应的选项  
  7.     curl_setopt($ch, CURLOPT_URL, $curl);    //要访问的网站  
  8.     //启用时会将头文件的信息作为数据流输出。  
  9.     curl_setopt($ch, CURLOPT_HEADER, false);      
  10.     //将curl_exec()获取的信息以字符串返回,而不是直接输出。  
  11.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
  12.   
  13.     if($https){  
  14.         //FALSE 禁止 cURL 验证对等证书(peer's certificate)。  
  15.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    
  16.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  //验证主机  
  17.     }  
  18.     if($method == 'POST'){  
  19.         curl_setopt($ch, CURLOPT_POST, true);  //发送 POST 请求  
  20.          //全部数据使用HTTP协议中的 "POST" 操作来发送。  
  21.         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);   
  22.     }  
  23.       
  24.       
  25.     // 抓取URL并把它传递给浏览器  
  26.     $content = curl_exec($ch);  
  27.   
  28.     //关闭cURL资源,并且释放系统资源  
  29.     curl_close($ch);  
  30.       
  31.     return $content;  
  32. }  

2.获取票据并保存
[php] view plain copy
  1. //获取令牌[access_token]  
  2. public function _getAccessToken(){  
  3.       
  4.     //指定保存文件位置  
  5.     if(!is_dir('./access_token/')){  
  6.         mkdir(iconv("UTF-8""GBK"'./access_token/'),0777,true);   
  7.     }  
  8.     $file = './access_token/token';  
  9.     if(file_exists($file)){  
  10.         $content = file_get_contents($file);  
  11.         $cont = json_decode($content);  
  12.         if( (time()-filemtime($file)) < $cont->expires_in){  
  13.             //当前时间-文件创建时间<token过期时间  
  14.             return $cont->access_token;  
  15.         }  
  16.     }  
  17.       
  18.     $curl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_appid.'&secret='.$this->_appsecret;  
  19.     $content = $this->_request($curl);  
  20.     file_put_contents($file,$content);  
  21.     $cont = json_decode($content);  
  22.     return $cont->access_token;  
  23.       
  24. }  

*出于安全考虑的话,获取到的票据可以先编码或加密再保存,使用的时候进行解码解密再使用!
原创粉丝点击