Google Drive Api与php整合

时间:2016-07-08 07:54:31

标签: php google-drive-api

我想将我的谷歌驱动器显示到网站上。这意味着如果有人使用我的网站可以看到谷歌驱动器文件和文件夹而无需登录。这是我试图实现的一些代码。

include_once 'google-api-php-client/src/Google/autoload.php';
    $scopes = array( 'https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appdata',
    'https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.metadata','https://www.googleapis.com/auth/drive.metadata.readonly','https://www.googleapis.com/auth/drive.photos.readonly','https://www.googleapis.com/auth/drive.readonly');

    /**
     * Create AssertionCredentails object for use with Google_Client
     */
    $creds = new Google_Auth_AssertionCredentials(
        $serviceAccountName,
        $scopes,
        file_get_contents($keyFile)
    );

    $creds->sub = $delegatedAdmin;

    /**
     * Create Google_Client for making API calls with
     */
    $client = new Google_Client();
    $client->setApplicationName($appName);
    $client->setClientId($clientId);
    $client->setAssertionCredentials($creds);

    /**
     * Get an instance of the Directory object for making Directory API related calls
     */
    $service = new Google_Service_Drive($client);

    $optParams = array(
      'pageSize' => 10,
      'fields' => "nextPageToken, files(id, name)"
    );
    $results = $service->files->listFiles($optParams);
    print_r($results); exit;
    /**

任何人都可以告诉我如何实现这一目标。我收到此错误

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." } 

1 个答案:

答案 0 :(得分:0)

您需要添加

if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion();
}

$client->setAssertionCredentials($creds);