0

Google 드라이브 API 및 Google 스프레드 시트 API를 사용하여 단일 계정의 Google 드라이브에서 수집 한 데이터로 데이터베이스를 정기적으로 업데이트하는 앱을 작성 중입니다.PHP의 Google 드라이브 API에 대한 액세스 토큰 새로 고침 (오프라인 액세스)

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; 
} 
작동하고 다음과 같습니다 액세스 토큰 생성

: 나는 다음과 같은 요청을이 access_token은 사용할 수

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

을 ...

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

... 그래서 함수는 유효한 토큰을 확실히 생성합니다.

그러나 Google 드라이브 API 클라이언트 라이브러리를 사용하는 방법을 알 수 없습니다.

여기 Google 드라이브 API의 경우 PHP Quickstart입니다.

$client = NULL; 
$driveService = NULL; 

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

:

그리고 여기 내 고장 코드? 그렇다면 나의 예는 무엇이 잘못 되었습니까?

하지 않으면 어떻게이 설정할 수 있습니다 : (https://www.googleapis.com/drive/v3/files를 얻을 수 유사) HTTP/REST 호출을 한

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

를?

+0

부분적인 대답으로 생성 된 액세스 토큰을 사용하여 GET https://www.googleapis.com/drive/v3/changes/startPageToken 끝점을 호출 할 수 있습니다. 여전히 내 코드 깔끔함을 개선하기 위해 Google PHP 클라이언트 내부에서이를 사용하는 방법을 알고 싶습니다. –

+0

'setAccessType'을 오프라인 (이미 완료)으로 설정하고'setApprovalPrompt'를 강제로 설정해야합니다. Google에 새로 고침 토큰을 반환하라는 메시지를 포함시켜야합니다. 새로 고침 토큰과 관련하여보고 된 문제 목록과 올바르게 요청하는 방법은 다음과 같습니다. [issue 1] (https://github.com/google/apap-php-client/issues/1064), [issue 2] (https://github.com/google/google-api-php-client/issues/1102), [새로 고침 토큰이 액세스 토큰에 다시 추가되도록합니다.] (https : // github .com/google/google-api-php-client/pull/1121). 희망이 도움이됩니다. –

답변

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); 
관련 문제