繁体   English   中英

如何使用服务帐户和 php 上传到谷歌驱动器

[英]How to upload to google drive with service account and php

下来你可以看到我的代码,它将文件上传到我的谷歌驱动器。 现在我正在尝试使用服务帐户让人们在没有他们的谷歌帐户的情况下将文件上传到我的谷歌驱动器(访问者将使用他们的文件提交 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);

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

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

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

// 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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM