使用访问令牌访问驱动器

时间:2015-06-03 03:52:52

标签: php google-drive-api google-sheets google-oauth

努力理解oauth2令牌并刷新令牌进程

我有这个代码

    $url = 'https://www.googleapis.com/oauth2/v3/token';
$data = array('client_id' => 'clientid', 'client_secret' => 'secret','refresh_token' => 'token','grant_type' => 'refresh_token');
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded",
        'method'  => 'POST',
        'approval_prompt'=>'force',
        'access_type'=>'offline',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

上面的代码给了我一个访问令牌,我按照这个link建议由一个伙伴stackoverflower,pinoyyid,但是我很高兴如何正确使用生成的访问令牌来访问驱动器并复制文件。 ..

我见过的所有过程通常都涉及$client = new Google_Client(),我不确定如何使用整个POST http:// .....的东西,所以基本上我需要弄清楚我是否使用访问令牌我在谷歌客户端的一个新实例中得到了上面的代码,或者我只是发布了一个带有必要信息的网址的帖子(我也不清楚)任何帮助/澄清是值得赞赏的人真的

编辑#1 我想要实现的是允许最终用户通过我的网页访问我的驱动器,让他们在我的驱动器中复制电子表格,并通过我的网站访问它,将数据存储在电子表格中,电子表格将始终在我的驱动,永远不会在最终用户

编辑#2

根据您的帖子的代码如下,使用服务帐户,,,,文件在我在api控制台上创建的服务帐户的gmail帐户内

<?php
require 'Google/autoload.php';
$client = new Google_Client();
// Replace this with your application name.
$client->setApplicationName("TEST");
// Replace this with the service you are using.
$service = new Google_Service_Drive($client);

// This file location should point to the private key file.
$key = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/number-privatekey.p12');
$user_to_impersonate = 'admin@testpr.com';
$cred = new Google_Auth_AssertionCredentials(
  'number@developer.gserviceaccount.com',
  array('https://www.googleapis.com/auth/drive'),  ****//this here has to be drive not drive.file
  $key,
  'notasecret',
  'http://oauth.net/grant_type/jwt/1.0/bearer',
  $user_to_impersonate
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion();
}
$originFileId = "longnumber";
$copyTitle = 'copied';
$newfile = copyFile($service, $originFileId, $copyTitle);
print_r($newfile);
function copyFile($service, $originFileId, $copyTitle) 
{
  $copiedFile = new Google_Service_Drive_DriveFile();
  $copiedFile->setTitle($copyTitle);
  try {
    return $service->files->copy($originFileId, $copiedFile);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}
?>

所以现在才开始工作,所有人都非常适合你的时间,并编辑我的帖子以反映当事人

1 个答案:

答案 0 :(得分:0)

如果您想让最终用户访问您的驱动器,您必须授权您的应用程序代表您域中的用户(在本例中为您)进行API调用。为此,您必须在Google Developers Console中设置服务帐户并生成p12密钥。您还必须在管理控制台中输入https://www.googleapis.com/auth/drive API范围。

可以在此处找到完整的解释和示例:https://developers.google.com/api-client-library/php/auth/service-accounts

要实现这一目标,您还需要Google API的客户端库:https://github.com/google/google-api-php-client(也在Google手册中提及)。

允许用户代表您的某个帐户进行API调用的代码示例:https://developers.google.com/api-client-library/php/guide/aaa_oauth2_service