Php 如何仅使用Google Drive';检查访问令牌是否有效;什么是RESTAPI?
我正在用PHP实现对的答案,其中已经有转换的代码 但是,当我运行该代码时,我会收到:Php 如何仅使用Google Drive';检查访问令牌是否有效;什么是RESTAPI?,php,node.js,rest,oauth-2.0,google-drive-api,Php,Node.js,Rest,Oauth 2.0,Google Drive Api,我正在用PHP实现对的答案,其中已经有转换的代码 但是,当我运行该代码时,我会收到: HTTP/1.1 400 Bad Request Vary: X-Origin Content-Type: application/json; charset=UTF-8 Date: Wed, 06 Sep 2017 22:29:24 GMT Expires: Wed, 06 Sep 2017 22:29:24 GMT Cache-Control: private, max-age=0 X-Content-Ty
HTTP/1.1 400 Bad Request
Vary: X-Origin
Content-Type: application/json; charset=UTF-8
Date: Wed, 06 Sep 2017 22:29:24 GMT
Expires: Wed, 06 Sep 2017 22:29:24 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alt-Svc: quic=":443"; ma=2592000; v="39,38,37,35"
Accept-Ranges: none
Vary: Origin,Accept-Encoding
Transfer-Encoding: chunked
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
我的帖子字段的格式与JavaScript答案中的格式完全相同,甚至URL编码的格式与PHP中的格式完全相同。我在中打开了相同的刷新令牌,在尝试刷新访问令牌时收到了相同的消息。两周前完成了此操作,但忘记发布我自己的答案。以下是我创建的用于获取令牌和下载文件的方法:
const CLIENT_ID = "";
const CLIENT_SECRET = "";
private $refresh_token;
private $access_token;
private $file_id;
private $output_path;
private $token_filename;
public function is_token_valid() {
$startTime = new \DateTime();
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Checking if access token ' . trim($this->access_token) . ' is valid...');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=" . urlencode($this->access_token));
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Checking token information...');
if ($response === false) {
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Error while checking access token...');
throw new \Exception("Token check triggered cURL error " + curl_errno($ch) . ": " . curl_error($ch));
}
$response = json_decode($response, true);
return !(isset($response['error']) || isset($response['error_description']));
}
public function get_access_token() {
$startTime = new \DateTime();
$post_fields = "grant_type=refresh_token&client_id=" . urlencode(self::CLIENT_ID) . "&client_secret=" . urlencode(self::CLIENT_SECRET) . "&refresh_token=" . urlencode($this->refresh_token);
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Getting access token for refresh token ' . urlencode($this->refresh_token) . ' ...');
//error_log($post_fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v4/token");
curl_setopt($ch, CURLOPT_PORT , 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
$response = curl_exec($ch);
$response = json_decode($response, true);
if ($response === false) {
throw new \Exception("Fetching access token triggered cURL error " + curl_errno($ch) . ": " . curl_error($ch));
}
if (!isset($response['access_token'])) {
throw new \Exception("Error fetching access token: " . json_encode($response));
}
$this->access_token = $response['access_token'];
file_put_contents($this->token_filename, $this->access_token);
return $this->access_token;
}
public function download_file() {
$startTime = new \DateTime();
$url = "https://www.googleapis.com/drive/v3/files/{$this->file_id}/export?mimeType=text/csv";
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Downloading CSV with URL ' . $url . ' ...');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT , 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $this->access_token));
$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
$response = json_decode($response);
throw new \Exception("CSV download was not successful: " + json_encode($response));
}
$tmp = tmpfile();
$path = stream_get_meta_data($tmp)['uri'];
file_put_contents($path, $response);
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Saved URL to ' . $path . ' ...');
return $path;
}
// ...
if (!$this->is_token_valid()) {
$this->get_access_token();
}
$this->download_file();
为什么不试试这个?它有一个用于在到期时刷新令牌的示例。@noogui这必须自动执行,据我所知,PHP库需要同意。请先尝试一下。@noogui我应该更具体一些。在我们的系统中,我们目前正在使用google api php客户端在用户同意的情况下在前端从google下载CSV,但对于新客户端,我们需要每小时自动下载CSV。我可以获得一个新的访问令牌,但我不知道如何在运行API调用之前验证我当前的访问令牌是否有效。
const CLIENT_ID = "";
const CLIENT_SECRET = "";
private $refresh_token;
private $access_token;
private $file_id;
private $output_path;
private $token_filename;
public function is_token_valid() {
$startTime = new \DateTime();
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Checking if access token ' . trim($this->access_token) . ' is valid...');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=" . urlencode($this->access_token));
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Checking token information...');
if ($response === false) {
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Error while checking access token...');
throw new \Exception("Token check triggered cURL error " + curl_errno($ch) . ": " . curl_error($ch));
}
$response = json_decode($response, true);
return !(isset($response['error']) || isset($response['error_description']));
}
public function get_access_token() {
$startTime = new \DateTime();
$post_fields = "grant_type=refresh_token&client_id=" . urlencode(self::CLIENT_ID) . "&client_secret=" . urlencode(self::CLIENT_SECRET) . "&refresh_token=" . urlencode($this->refresh_token);
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Getting access token for refresh token ' . urlencode($this->refresh_token) . ' ...');
//error_log($post_fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v4/token");
curl_setopt($ch, CURLOPT_PORT , 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
$response = curl_exec($ch);
$response = json_decode($response, true);
if ($response === false) {
throw new \Exception("Fetching access token triggered cURL error " + curl_errno($ch) . ": " . curl_error($ch));
}
if (!isset($response['access_token'])) {
throw new \Exception("Error fetching access token: " . json_encode($response));
}
$this->access_token = $response['access_token'];
file_put_contents($this->token_filename, $this->access_token);
return $this->access_token;
}
public function download_file() {
$startTime = new \DateTime();
$url = "https://www.googleapis.com/drive/v3/files/{$this->file_id}/export?mimeType=text/csv";
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Downloading CSV with URL ' . $url . ' ...');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT , 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $this->access_token));
$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
$response = json_decode($response);
throw new \Exception("CSV download was not successful: " + json_encode($response));
}
$tmp = tmpfile();
$path = stream_get_meta_data($tmp)['uri'];
file_put_contents($path, $response);
error_log('[' . $startTime->format('Y-m-d h:i:s') . '] Saved URL to ' . $path . ' ...');
return $path;
}
// ...
if (!$this->is_token_valid()) {
$this->get_access_token();
}
$this->download_file();