如何使用服务帐户和php上传到Google Drive

问题描述 投票:0回答:2

在下面你可以看到我的代码,它将文件上传到我的谷歌驱动器。现在我正在尝试使用服务帐户让人们无需使用 Google 帐户即可将文件上传到我的 Google 驱动器(访问者将使用其文件提交 html 表单,我的应用程序会将该文件上传到我的驱动器)。但我坚持下去。甚至找不到一个工作示例。有什么想法吗?

$client = new Google\Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google\Service\Drive::DRIVE);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);

    // store in the session also
    $_SESSION['upload_token'] = $token;

    // redirect back to the example
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if (!empty($_SESSION['upload_token'])) {
    $client->setAccessToken($_SESSION['upload_token']);
    if ($client->isAccessTokenExpired()) {
        unset($_SESSION['upload_token']);
    }
} else {
    $authUrl = $client->createAuthUrl();
}
echo $client->getAccessToken();
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $client->getAccessToken()) {
    // We'll setup an empty 1MB file to upload.
    DEFINE("TESTFILE", 'test.jpg');
    if (!file_exists(TESTFILE)) {
        $fh = fopen(TESTFILE, 'w');
        fseek($fh, 1024 * 1024);
        fwrite($fh, "!", 1);
        fclose($fh);
    }

    // This is uploading a file directly, with no metadata associated.
    $file = new Google\Service\Drive\DriveFile();
    $service = new Google_Service_Drive($client);
    $file->setName("Hello World!");
    $result = $service->files->create(
        $file,
        [
            'data' => file_get_contents(TESTFILE),
            'mimeType' => 'application/octet-stream',
            'uploadType' => 'media'
        ]
    );
    $permissionService = new Google_Service_Drive_Permission();
    $permissionService->role = "reader";
    $permissionService->type = "anyone"; // anyone with the link can view the file
    $service->permissions->create($result->id, $permissionService);
php google-drive-api service-accounts
2个回答
0
投票

以下代码将向您展示如何设置服务帐户授权。

请记住,文件将上传到服务帐户驱动器帐户。如果您希望将它们上传到您的个人云端硬盘帐户。您需要与服务帐户共享驱动器帐户上的目录。您可以像对待任何其他用户一样,通过网络应用程序使用服务帐户电子邮件地址来执行此操作。它的属性看起来像电子邮件。

您应该能够删除您现在拥有的身份验证,然后使用它。但是,您需要将上传元数据中的父级设置为您想要将填充上传到的目录的父级。

// Load the Google API PHP Client Library.
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::DRIVE)
 * 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(array(Google_Service_Analytics::DRIVE));
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

执行类似的操作将为您提供相同的服务对象。

$service = new Google_Service_Drive(getGoogleClient());

0
投票

您可以使用 https://www.npmjs.com/package/drive-upload-service-account 为此。它是一个 npm 包,允许用户使用服务帐户直接从服务器端将文件上传到驱动器。 它有详细记录,希望能回答您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.