TP获取微信token并保存token

分类首页日期2年前访问691评论0

上代码

 //获取小程序access_token(测试用文件的方式存储微信AccessToken)


 private function getAccessToken1()
    {
        $appid = config('wx_lite')['appid'];
        $appsecret = config('wx_lite')['appSecret'];
        $token_file = 'wxtoken.txt';//dirname(dirname(__FILE__)) . 
        if (!file_exists($token_file) || ((time() - filemtime($token_file)) > 7000)) {
            $TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
            $json = file_get_contents($TOKEN_URL);
            $result = json_decode($json);
            $ACC_TOKEN = $result->access_token;
            file_put_contents($token_file, $ACC_TOKEN);
        } else {
            $ACC_TOKEN = file_get_contents($token_file);
        }
        return $ACC_TOKEN;
    }
//用自定义配置文件的方式存储微信AccessToken
    private function getAccessToken()
    {
        $appid = config('wx_lite')['appid'];
        $appsecret = config('wx_lite')['appSecret'];
        $token_file = Config('extraconfig');//适用于TP5.0,获取extra下面的extraconfig.php配置文件,不需要手动创建,用extraconfig方法创建
        if(empty($token_file['wx_expiretime'])||(int) $token_file['wx_expiretime']<time()){
            $TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
            $json = file_get_contents($TOKEN_URL);
            $result = json_decode($json);
            if(empty($result->access_token)){
                $this->error($result->errmsg);
            }
            $ACC_TOKEN = $result->access_token;
            $this->extraconfig(['wx_expiretime'=>time()+7000,'wx_token'=>$ACC_TOKEN]);
        }else{
            $ACC_TOKEN = $token_file['wx_token'];
        }
        return $ACC_TOKEN;
    }
   
    private function extraconfig($arr = [], $file = 'extraconfig')
    {
        if (is_array($arr)) {
            $filename = $file . EXT;
    
            $filepath = APP_PATH . 'extra/' . $filename;
            if (!file_exists($filepath)) {
                $conf = "<?php return [];";
                file_put_contents($filepath, $conf);
            }
    
            $conf = include $filepath;
            foreach ($arr as $key => $value) {
                $conf[$key] = $value;
            }
    
            $time = date('Y/m/d H:i:s');
            $str = "<?php\r\n/**\r\n * 由config建立.\r\n * $time\r\n */\r\nreturn [\r\n";
            foreach ($conf as $key => $value) {
                $str .= "\t'$key' => '$value',";
                $str .= "\r\n";
            }
            $str .= '];';
    
            file_put_contents($filepath, $str);
            
            return true;
        } else {
            return false;
        }
    }