簡體   English   中英

刷新PHP中Google Drive API的訪問令牌(離線訪問)

[英]Refreshing an access token (offline access) for Google Drive API in PHP

我正在編寫一個應用程序,該應用程序使用Google Drive API和Google Sheets API使用從單個帳戶的Google Drive收集的數據對數據庫進行例行更新。

使用此“我如何在沒有用戶干預的情況下授權應用程序(網絡或已安裝)”中找到的答案 (規范?)問題,我已經能夠創建自己的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快速入門

這是我的損壞代碼:

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 )?

   $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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM