【问题标题】:How to connect to a Google Drive API and get the AccessToken如何连接到 Google Drive API 并获取 AccessToken
【发布时间】:2022-01-28 01:45:29
【问题描述】:

我在这里遇到了一个小问题,即使用凭据 json 文件将我的脚本与 Google Drive API 连接起来。

这是我的代码:

$oauth_credentials = __DIR__.'\credentials.json';
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

$client = new Google\Client();
$client->setAccessType('offline');
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");

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

显然我使用composer将google apiclient项目添加到我的脚本中,并且我使用google的云控制台启用了Drive API并为此创建了凭据,并且我使用了Google Console下载的credentials.json文件。

显然一切都很好,我添加了一个测试帐户并使用此帐户接受使用 Drive API 的权限。

使用操场,在此 URL https://developers.google.com/oauthplayground 中,我测试了我的凭据并获得了创建刷新令牌和访问令牌的授权代码,但是当我在脚本中使用此授权代码时,结果是:“”

'error' => string 'invalid_grant' (length=13)
'error_description' => string 'Bad Request' (length=11)

有什么建议吗?此代码与 Google 示例中的代码完全相同。

【问题讨论】:

    标签: php api google-cloud-platform


    【解决方案1】:

    我的问题是焦点错误,我创建了一个服务帐户并生成了 json 凭据文件,然后我使用此代码上传文件:

    putenv('GOOGLE_APPLICATION_CREDENTIALS=credentials.json');
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->setScopes(['https://www.googleapis.com/auth/drive.file']);
    
        try {
            $service = new Google_Service_Drive($client);
            $file_path = 'example.txt';
            $file = new Google_Service_Drive_DriveFile();
            $file->setName('example.txt');
            $file->setParents([$this->folder_id]);
            $file->setDescription('Example description text');
    
            $result = $service->files->create($file,[
                'data' => file_get_contents($file_path),
                'mimeType' => 'text/plain',
                'uploadType' => 'text'
            ]);
    
            echo '<a href="https://drive.google.com/open?id='.$result->id.'" target="_blank">Link to the uploaded file</a>';
        }
        catch(Google_Service_Exception $gs)
        {
            $m = json_decode($gs->getMessage());
            echo $m->error->message;
        }
        catch(Exception $e)
        {
            echo $e->getMessage();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 2016-02-24
      相关资源
      最近更新 更多