我正在编写一个应用程序,使用Google Drive API和Google表格API,使用从单个帐户的Google云端硬盘收集的数据对数据库执行例行更新。
使用此How do I authorise an app (web or installed) without user intervention? (canonical ?)问题中的答案,我已经能够创建自己的PHP函数来获取访问令牌。
function get_access_token() {
$request_url = "https://www.googleapis.com/oauth2/v4/token";
$refresh_token = "1/XgTqiwrGHJ3LOh-verververververv-q2qIF3Aq_ENrzhH6IQA4u4X";
$params = [
'client_id' => "1073411048819-vergewrgergergewrgerwgewr.apps.googleusercontent.com",
'client_secret' => "b8oPhmVrevervvreverviA37aipaB",
'refresh_token' => $refresh_token,
'grant_type' => "refresh_token"
];
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER,'Content-Type: application/x-www-form-urlencoded');
$postData = "";
//This is needed to properly form post the credentials object
foreach($params as $k => $v) {
$postData .= $k . '='.urlencode($v).'&';
}
$postData = rtrim($postData, '&');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
$json_response = curl_exec($curl);
$response = (array) json_decode( $json_response );
$response["refresh_token"] = $refresh_token;
$date = new DateTime();
$response["created"] = $date->getTimestamp();
return $response;
}
哪个有效并产生如下所示的访问令牌:
array(5) {
["access_token"]=>
string(129) "ya29.GlsEBWfC-cdO1F80MjNB_oNVp87fojEWILclEfbgbgbgbbgbgbgbgzXNFV3xSmMSI733HvdTrXd6wgbDB0u3ACLfRaNkitIQPOdF3T2jSH3NTjCEndH0fBYXy"
["token_type"]=>
string(6) "Bearer"
["expires_in"]=>
int(3600)
["refresh_token"]=>
string(45) "1/XgTqiwrGHJ3LOh-verververververv-q2qIF3Aq_ENrzhH6IQA4u4X"
["created"]=>
int(1510654966)
}
我可以使用此access_token来发出请求,例如......
GET https://www.googleapis.com/drive/v3/files
Authorization: Bearer ya29.GlsEBWfC-cdO1F80MjNB_oNVp87fojEWILclEfbgbgbgbbgbgbgbgzXNFV3xSmMSI733HvdTrXd6wgbDB0u3ACLfRaNkitIQPOdF3T2jSH3NTjCEndH0fBYXy
...所以该函数肯定会生成一个有效的令牌。
但是,我无法弄清楚如何使用Google Drive API客户端库。
以下是Google Drive API的PHP Quickstart。
这是我破碎的代码:
define('APPLICATION_NAME', 'My Plugin');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE_METADATA_READONLY)
));
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$accessToken = get_access_token();
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode(get_access_token()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
$client = getClient();
$driveService = new Google_Service_Drive($client);
产生:
$client = NULL;
$driveService = NULL;
是否可以在PHP库中使用此方法?如果是这样,我的例子出了什么问题?
如果没有,我该怎么做呢:
$response = $driveService->changes->getStartPageToken();
进入HTTP / REST调用(类似于GET https://www.googleapis.com/drive/v3/files)?
答案 0 :(得分:0)
$token='access_token_here';
$url="https://www.googleapis.com/upload/drive/v3/files?uploadType=media";
$method='POST';
$filepath='file_to_upload_path.pdf'
$data['name']='file_title_here.pdf';
$data['title']='file_title_here.pdf';
$p1=(object)[];
$p1->id='parent_folder_id_here';
$data['parents'][]=$p1;
$body=file_get_contents($filepath);
$timeout=30;
$verify_ssl = false;
$headers = array(
'Content-Type: application/pdf',
'Cache-Control: no-cache',
'Authorization: Bearer '.$token ,
'Content-Length: '.strlen($body)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
echo $result = curl_exec($ch);
//echo $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);