Jack Robson
Jack Robson

Reputation: 2302

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

I am writing an app that performs routine updates to a database with data gathered from a single account's Google Drive using the Google Drive API and Google Sheets API.

Using the answer found in this How do I authorise an app (web or installed) without user intervention? (canonical ?) question, I have been able to create my own PHP function to get the access token.

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;
}

Which works and produces an access token that looks like this:

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

I can use this access_token to make requests such as...

GET https://www.googleapis.com/drive/v3/files 
Authorization: Bearer ya29.GlsEBWfC-cdO1F80MjNB_oNVp87fojEWILclEfbgbgbgbbgbgbgbgzXNFV3xSmMSI733HvdTrXd6wgbDB0u3ACLfRaNkitIQPOdF3T2jSH3NTjCEndH0fBYXy 

... so the function definitely produces a valid token.

However, I cannot figure out how to use the Google Drive API Client library with this.

Here is the PHP Quickstart for the Google Drive API.

And here is my broken code:

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

That produces:

$client = NULL;
$driveService = NULL;

Is it possible to use this approach with the PHP library? If so, what is wrong with my example?

If not, how can I turn this:

$response = $driveService->changes->getStartPageToken();

Into a HTTP/REST call (similar to GET https://www.googleapis.com/drive/v3/files)?

Upvotes: 0

Views: 1253

Answers (1)

Santosh Kshirsagar
Santosh Kshirsagar

Reputation: 186

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

Upvotes: 0

Related Questions