메뉴 건너뛰기

infra

[Gdata] API v4 사용 for PHP

lispro062017.10.01 20:36조회 수 536댓글 0

  • 3
    • 글자 크기

그전에 테스트 했던, v3는 종료될 예정이다.


PHP 7.0에서 테스트 해 봤는데, 웹에서는 사용이 안되는 건지 의문이다.


  457  wget https://getcomposer.org/composer.phar

  458  php composer.phar require google/apiclient:^2.0

  459  sudo /etc/init.d/apache2 stop

  460  php composer.phar require google/apiclient:^2.0


아파치를 종료 시킨 후 다시 실행한 이유는 메모리가 부족해서 이다. 이상하게 google cloud 는 메모리가 적다.

itop도 잘 안돌아 간다.


여기까지 설치가 되면, 기본적으로 vendor라는 폴더에 필요한 파일들이 다운로드 된다.


https://developers.google.com/sheets/quickstart/php

위 사이트의 아래 코드를 만들어 1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms (공개 문서) 의 데이터를 읽는 코드를 실행해 볼 수 있다.


getClient 함수에서 터미널에서 실행한 값에 대해 authcode를 입력하게 되면, cli에서 확인이 가능하다.

웹 브라우저에서는 안된다. 모르겠다.

코드는 만료가 1440초로 생각된다. accessToken을 자동으로 받아 입력하려고 하면, 500 에러가 나서 웹에서는 확인이 안된다. cli에서만 할 거라면 사용자에게 제공하는 서비스로는 적당하지 않은데, 좀 더 시간이 필요하다.


1.jpg 2.jpg 3.jpg

<?php
require_once __DIR__
. '/vendor/autoload.php';


define
('APPLICATION_NAME', 'Google Sheets API PHP Quickstart');
define
('CREDENTIALS_PATH', '~/.credentials/sheets.googleapis.com-php-quickstart.json');
define
('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-php-quickstart.json
define
('SCOPES', implode(' ', array(
 
Google_Service_Sheets::SPREADSHEETS_READONLY)
));

if (php_sapi_name() != 'cli') {
 
throw new Exception('This application must be run on the command line.');
}

/**
 * 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
->setAuthConfig(CLIENT_SECRET_PATH);
  $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 {
   
// Request authorization from the user.
    $authUrl
= $client->createAuthUrl();
    printf
("Open the following link in your browser:n%sn", $authUrl);
   
print 'Enter verification code: ';
    $authCode
= trim(fgets(STDIN));

   
// Exchange authorization code for an access token.
    $accessToken
= $client->fetchAccessTokenWithAuthCode($authCode);

   
// 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 %sn", $credentialsPath);
 
}
  $client
->setAccessToken($accessToken);

 
// Refresh the token if it's expired.
 
if ($client->isAccessTokenExpired()) {
    $client
->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents
($credentialsPath, json_encode($client->getAccessToken()));
 
}
 
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);
}

// Get the API client and construct the service object.
$client
= getClient();
$service
= new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId
= '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range
= 'Class Data!A2:E';
$response
= $service->spreadsheets_values->get($spreadsheetId, $range);
$values
= $response->getValues();

if (count($values) == 0) {
 
print "No data found.n";
} else {
 
print "Name, Major:n";
 
foreach ($values as $row) {
   
// Print columns A and E, which correspond to indices 0 and 4.
    printf
("%s, %sn", $row[0], $row[4]);
 
}
}

lispro06 (비회원)
  • 3
    • 글자 크기
[slack] 파이선을 이용한 api 서버 (by lispro06) [apache] tomcat 으로 proxypass (by lispro06)

댓글 달기

첨부 (3)
1.jpg
48.4KB / Download 59
2.jpg
52.1KB / Download 65
3.jpg
39.9KB / Download 59
위로