1. 程式人生 > >微信獲取access_token並存入配置檔案 的類和程式碼

微信獲取access_token並存入配置檔案 的類和程式碼

剛寫的微信獲取access_token的程式碼,發上來做個記錄,也希望大家共同探討.

<?php

/**
 * 用於更新微信access_token
 * Class WechatAccessToken
 */
namespace Wechat;
class WechatAccessToken {
    private $appId;
    private $appSecret;
    private $WechatAccessToken = array();
    // 最後申請時間
    protected $lastApplyTime = 0;
    // 間隔時間 : 50秒內的申請算連擊,根據每天只能呼叫2000次估算出來
    protected $intervalTime = 50;

    public function __construct($WechatAccessToken, $appId='xxxxxxx', $appSecret='xxxxx') {
        $this->WechatAccessToken = $WechatAccessToken;
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    /**
     * 取得微信的accessToken
     */
    public function getWechatAccessToken() {
        # 提前10分鐘獲取token
        $pre = 110 * 60;

        // 如果沒有access_token資訊,則更新access_token
        if (count($this->WechatAccessToken) == 0) {
            $this->setWechatAccessToken();
        }

        // 如果到期時間在10分鐘內,就更新access_token
        if ($this->lastApplyTime || $this->lastApplyTime - time() >= $pre) {
            $this->setWechatAccessToken();
        }

        return $this->WechatAccessToken['access_token'];
    }

    /**
     * 申請token
     */
    private function setWechatAccessToken( ) {
        // 50 秒內不能查詢兩次,避免一下子將整天的查詢次數都用光了
        if ( time() - $this->lastApplyTime < $this->intervalTime ) {
            return $this->returnArr(0,'獲取微信公眾號token失敗,50 秒內不能查詢兩次','');
        }

        $appId = $this->appId;
        $secret = $this->appSecret;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$secret}";
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl,CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($curl);
        curl_close($curl);

        if ( ! $data ) {
            return $this->returnArr(0,'獲取微信公眾號token失敗,返回為空','');
        }

        $result = json_decode($data, true);
        // {"access_token":"16_pyPL1eL_jcT-EevdHGKZ6ohFxvQgQjYSl9AWKbEElW99aIDhtzJ6sI7oWHY1EXIuGI-KVPBxsgorLmNj6Ms83yR_cjGvLBGsg_o6UCaNtVENgm35XVFDTh0Snx4SGLfAGADRW","expires_in":7200}

        if ( ! $result ) {
            return $this->returnArr(0,'獲取微信公眾號token失敗,返回異常:'.$data,'');
        }

        // 寫檔案
        $resultData = array(
            'WechatAccessToken' => array(
                'access_token' => $result["access_token"],
                'prev_time' => time(),
                'expires_in' => $result["expires_in"],
            )
        );
        file_put_contents("Data/Config/WechatAccessToken.inc.php", "<?php \nreturn " . var_export($resultData, true) . ";\n?>");
        $this->WechatAccessToken = $resultData['WechatAccessToken'];
        return $this->returnArr(1,'獲取微信公眾號token成功',$result["access_token"]);
    }

    public function returnArr($status, $msg, $data){
        $data = array(
            'status' => $status,
            'msg' => $msg,
            'data' => $data,
        );
        return $data;
    }
}

呼叫部分:

use Wechat\WechatAccessToken;
$WechatAccessToken = new WechatAccessToken(C('WechatAccessToken'));
echo $WechatAccessToken->getWechatAccessToken();

WechatAccessToken.inc.php如下:

<?php 
return array (
  'WechatAccessToken' => 
  array (
    'access_token' => '16_3KKxDqYFiak8RmG2TPVNbZvRqHwZUUMFqcVGlPyynalk9_vnpQZM1ozkG4TV0qr9d1uvtgwSLBI345ieUIkV3Cyfay2nUsNPzeDeEncVI2wTvzjG_PL0cTDTtNt1WgVPjTBMqJQ1Yg95zZvlJAIdAJACTB',
    'prev_time' => 1543912023,
    'expires_in' => 7200,
  ),
);
?>