Google Drive API不允许未经PHP身份验证上传文件

时间:2018-09-02 18:51:00

标签: php google-api google-drive-api google-api-php-client

我正在将该库用作Google php客户端库,并遵循google drive quickstart教程。

$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');

我正在尝试将文件从PHP应用程序上传到Google云端硬盘。当我运行要上传的应用程序时,它正在请求授权。为此,要求我登录我的Google帐户并同意访问我的驱动器帐户,然后再返回我的应用程序。

我想跳过此步骤。我如何在无需获得Google授权的情况下上传到Google云端硬盘。

1 个答案:

答案 0 :(得分:0)

您首先需要了解的是私有数据与公共数据之间的差异。私有数据归用户所有,而公共数据则是任何人都可以访问的公共数据。

Google云端硬盘数据是私人用户数据。为了访问它,您必须拥有它的用户的许可。获得该权限的最常见方法是使用Oauth2,然后弹出您在现有代码中看到的同意屏幕。不过还有另一种选择。

如果您要访问的帐户是您自己的帐户,则开发人员可以控制该帐户,那么您可以使用服务帐户。服务帐户用于服务器到服务器的身份验证。服务帐户已预先授权。您将要做的就是获取服务帐户的电子邮件地址,并在您的Google Drive帐户上共享一个您希望它可以访问的目录或文件。授予它访问权限后,便无需登录。

require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

我在服务帐户上的样本。 serviceaccount.php