使用PHP无需用户交互即可连接到Google Drive API

问题描述 投票:1回答:1

我想使用API​​将文件上传到Google云端硬盘,但我需要使用cron作业(将webfiles + sql自动备份到Google云端硬盘)。

这意味着(我想)我需要使用除用户交互方法之外的其他东西进行身份验证。

我一直在使用的示例:https://developers.google.com/api-client-library/php/auth/web-app让我继续,并使用用户身份验证。

我会很感激有关如何在没有用户交互的情况下执行此操作的一些提示,因此它可以在cronjob上运行。

以下是用于验证和上传文件的PHP代码(具有手动用户身份验证和单个文件上载的工作示例)

  <?php

    require_once 'google-api-php-client/vendor/autoload.php';

    /* Config */
    $servername = 'content here';
    $redirect_uri = 'https://example.com/';

    $client = new Google_Client();
    $client->setAuthConfig('client_manual_authentiation.json');
    $client->addScope(Google_Service_Drive::DRIVE);

    if(isset($_SESSION['access_token']) && $_SESSION['access_token']) {

        $client->setAccessToken($_SESSION['access_token']);
        $drive = new Google_Service_Drive($client);

        foreach($drive->files->listFiles(array("q" => "name = '{$servername}'"))->getFiles() as $key => $element){

            if($element->name == $servername){

                //create todays folder on Google Drive
                $today_folder_meta = new Google_Service_Drive_DriveFile(array(
                    'name' => 'myfile.txt',
                    'mimeType' => 'application/vnd.google-apps.folder',
                    'parents' => array($element['id'])
                ));

                $today_folder = $drive->files->create($today_folder_meta, array(
                    'fields' => 'id'
                ));

            }
        }
    }else{

        if (!isset($_GET['code'])) {
            $auth_url = $client->createAuthUrl();
            header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
        } else {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        }
    }

?>
php oauth-2.0 google-drive-sdk
1个回答
0
投票

为此,您需要创建Google OAuth2服务帐户。然后,您可以下载一组JSON凭据,您的应用将在没有用户交互的情况下进行身份验证。

这在以下文章中描述:

将OAuth 2.0用于服务器到服务器应用程序

然后,您就可以下载以下凭据,以便在您的应用中使用:

{
    "type":"service_account",
    "project_id":"your-project-id",
    "private_key_id":"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
    "private_key":"-----BEGIN PRIVATE KEY-----\nMIIEv...4XIk=\n-----END PRIVATE KEY-----\n",
    "client_email":"[email protected]",
    "client_id":"12345678901234567890",
    "auth_uri":"https://accounts.google.com/o/oauth2/auth",
    "token_uri":"https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/foobar%40bazqux.iam.gserviceaccount.com"
}

这是一个如何使用它的Google PHP示例:

您可以在Google API控制台中创建服务帐户,如下所示:

enter image description here

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