首页 > 解决方案 > 从 google drive api 获取响应代码?

问题描述

我正在尝试使用 PHP 代码将文件上传到谷歌驱动器。不管它是什么,我都无法获得 API 响应。如果成功上传响应应该是 200 和不同的错误代码。我只想收到错误代码。任何人都可以帮助我。贝娄我已经粘贴了我的完整代码。我正在使用检查文件夹是否已经存在以及是否将文件放入其中的功能,否则只需创建新文件夹并将文件放入其中。我试图让我的代码安全失败,如果遇到错误,它会保存特定的文件和错误代码。现在它只是返回严重错误并破坏 AJAX。

function getClient(){

    $authdata = array (
        'web' => 
            array (
            'client_id' => get_option("csc_gdrive_clientid"),
            'project_id' => get_option("csc_gdrive_projectid"),
            'auth_uri' => "https://accounts.google.com/o/oauth2/auth",
            'token_uri' => "https://oauth2.googleapis.com/token",
            'auth_provider_x509_cert_url' => "https://www.googleapis.com/oauth2/v1/certs",
            'client_secret' => get_option("csc_gdrive_clientsecret"), 
        ),
    );

    include( plugin_dir_path( __FILE__ ) . '../vendor/autoload.php');
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE);
    $client->setAuthConfig($authdata);
    $client->setAccessType('offline');
    // $client->setPrompt('select_account consent');
    $client->setRedirectUri(get_option("csc_gdrive_redirecturi"));

    // Load previously authorized token from a file, if it exists.
    // The file key_config.txt stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = plugin_dir_path( __FILE__ ) .'111key_config.txt';
    
    if (!file_exists($tokenPath)) {
        return;
    } else{
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }
    if (file_exists($tokenPath)){   
        // If there is no previous token or it's expired.
        if ($client->isAccessTokenExpired()) {
            
            // Refresh the token if possible, else fetch a new one.
            if ($client->getRefreshToken()) {
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            } else {
                
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();
                
                $authCode = get_option('csc_gdrive_token');
                // Exchange authorization code for an access token.
                $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
                $client->setAccessToken($accessToken);
                // Check to see if there was an error.
                if (array_key_exists('error', $accessToken)) {
                    throw new Exception(join(', ', $accessToken));
                }
            }
            
        }
    }
return $client;
}enter code here


function create_folder( $folder_name, $parent_folder_id=null ){
    
    //$folder_list = $this->check_folder_exists( $folder_name );
    // if folder does not exists
    //if( count( $folder_list ) == 0 ){
    $client = $this->getClient();
    if($client){
        $service = new Google_Service_Drive( $client );
        $folder = new Google_Service_Drive_DriveFile();
        $folder->setName( $folder_name );
        $folder->setMimeType('application/vnd.google-apps.folder');
        if( !empty( $parent_folder_id ) ){
            $folder->setParents( [ $parent_folder_id ] );        
        }
        $result = $service->files->create( $folder );
        $folder_id = null;
        if( isset( $result['id'] ) && !empty( $result['id'] ) ){
            $folder_id = $result['id'];
        }
        return $folder_id;
    }
    //}
    //return $folder_list[0]['id'];
}

// This will check folders and sub folders by name
function check_folder_exists( $folder_name, $parent_folder_id=null){

    $client = $this->getClient();
    if($client){    
        $service = new Google_Service_Drive( $client );

        if ($parent_folder_id){
        
            $parameters['q'] = "mimeType='application/vnd.google-apps.folder' and name='$folder_name' and trashed=false and '$parent_folder_id' in parents";
        } else {
            
            $parameters['q'] = "mimeType='application/vnd.google-apps.folder' and name='$folder_name' and trashed=false";
        }
        $files = $service->files->listFiles($parameters);
        $op = [];
        foreach( $files as $k => $file ){
            $op[] = $file;
        }
        return $op;
    }
}

// This will insert file into drive and returns boolean values.
function insert_file_to_drive( $file_path, $file_name, $parent_file_id = null ){
    $client = $this->getClient();
    if($client){
        $service = new Google_Service_Drive( $client );
        $file = new Google_Service_Drive_DriveFile();
        $file->setName( $file_name );
        if( !empty( $parent_file_id ) ){
            $file->setParents( [ $parent_file_id ] );        
        }
    
        $result = $service->files->create(
            $file,
            array(
                'data' => file_get_contents($file_path.'/'.$file_name),
                'mimeType' => 'application/octet-stream',
            )
        );
        $is_success = false;
        if( isset( $result['name'] ) && !empty( $result['name'] ) ){
            $is_success = true;
        }
        return $is_success;
    }

}

标签: phpwordpresspluginsgoogle-drive-api

解决方案


推荐阅读