• PHP取微信access_token并全局存储与更新


    来源:http://www.zcphp.com/html/weixinkaifa-show-20.html

    官方的说明:

    access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。

    开发时需要进行妥善保存。

    access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

    众所周知,在微信开发中access_token是经常用的。但是access_token的请求次数是有限制的,所以不能每次都重新请求,只有将它缓存到本地了。

     function accessToken() {
        $tokenFile = "./access_token.txt";//缓存文件名
        $data = json_decode(file_get_contents($tokenFile));
        if ($data->expire_time < time() or !$data->expire_time) {
        $appid = "你的appid";
        $appsecret = "你的appsecret";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
          $res = getJson($url);
          $access_token = $res['access_token'];
          if($access_token) {
            $data['expire_time'] = time() + 7000;
            $data['access_token'] = $access_token;
            $fp = fopen($tokenFile, "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
          }
        } else {
          $access_token = $data->access_token;
        }
         return $access_token;
      }
       
     //取得微信返回的JSON数据
     function getJson($url){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      $output = curl_exec($ch);
      curl_close($ch);
      return json_decode($output, true);
    }
    

      

  • 相关阅读:
    OneDay!——冲刺日志9(05-06)
    Hail_Hydra2—代码规范
    Hail_Hydra2—凡事预则立
    Alpha冲刺的问题总结
    Hail_Hydra2—冲刺日志集合
    Hail_Hydra2—总结随笔
    Hail_Hydra2—测试随笔
    Hail_Hydra2—冲刺日志(10)
    Hail_Hydra2—冲刺日志(9)
    Hail_Hydra2—冲刺日志(8)
  • 原文地址:https://www.cnblogs.com/cblx/p/8960710.html
Copyright © 2020-2023  润新知