2014-09-12 2 views
0

Google에서 두 계정을 가지고 있습니다. 하나는 개인용이고 다른 하나는 회사에서 사용하는 계정입니다. 회사 계정에서 드라이브 할당량을 구입했으며 200GB (생각합니다)이므로 파일 저장소 클라우드 서버로 사용하고 있습니다. 내 아이디어는 Google 드라이브 php api를 사용하여 회사 웹 사이트에 파일 중 일부를 구현하는 것입니다. 오랫동안 내가 할 수있는 한 좋은 소리는 Use Application-Owned Accounts 알지만, 일반 계정으로 사용하려면 새 계정을 만들어야하고 서버 측에서 사용하려면 사용하지 못할 것입니다. 회사 계정은 일반 계정에 있습니다. 그래서,이 상황에 붙어있어!? 제발, 조언 좀 해줘. 이것은 나에게 모두 새로운 것이므로 귀하의 도움이 필요합니다.서비스 계정을 사용하는 방법? Google에서 기존 계정을 서비스 계정으로 사용할 수 있습니까?

편집 : 그것은 내가 위의 게시 된 링크에서 말하는 이 있습니다 :

당신은 어떤 사용자와 같은 일반 Google 계정을 만들 수 있습니다

것, 구글 계정 가입 흐름을 통과하거나 Google Apps 도메인에 계정을 만들면됩니다. 실제 사람이 사용하지 말고 응용 프로그램에서만 사용하십시오.

그래,하지만 내 계정은 새로운 것이 아니며 이전에는 사용되었습니다. 즉, 내 회사 계좌를 사용할 수 없으며, 이것이 사실이라면 어떻게하면 내 목표를 달성 할 수 있습니까?

답변

0

마침내 내가 어떻게 이것을 할 수 있는지 연구 한 후, 액세스 토큰을 얻는 방법에 대한 매우 간단한 코드와 액세스하기 위해 필요한 새로 고침 토큰을 가져 오는 방법이 있습니다. 사용자가 오프라인 상태 일 때 난 아직도 어떻게 내가 데이터베이스에서 그 값을 저장할 때 알아야 할 수있는 구글 아이디와 함께이 사용자는 데이터베이스에서 동일한 사용자와 PHP에 새로 고침 토큰을 넣어, 그래서 사용자가 없다는 것을 알 수 있습니까? 다시 인증하고 그는이 작업을 한 번만 수행 할 수 있습니다 (서비스 계정). 따라서이 간단한 코드는 액세스 토큰과 새로 고침 토큰을 저장하기 위해 SESSIONS를 사용합니다. 그것은 스토리지에 대한 데이터베이스를 사용하지 않지만, 당신이 원한다면 내가 어떻게 이런 일을 알아낼 내가 여기뿐만 아니라 코드를 게시 할 수 있습니다. 코드는 다음과 같습니다.

<?php 
session_start(); 

// Set error reporting 
error_reporting(E_ALL | E_STRICT); 
// Display errors 
ini_set("display_errors", 1); 

// require pages, you have to change it if your pages are somewhere else! 
require_once 'src/Google_Client.php'; 
require_once "src/contrib/Google_Oauth2Service.php"; 
require_once "src/contrib/Google_DriveService.php"; 

/** 
* Retrieved stored credentials for the provided user ID. 
* 
* @param String $userId User's ID. 
* @return String Json representation of the OAuth 2.0 credentials. 
*/ 
function getStoredCredentials($userId) { 
    if (!empty($_SESSION['userid'])) { 
    return $_SESSION['userid']; 
    } 
} 

/** 
* Store OAuth 2.0 credentials in the application's database. 
* 
* @param String $userId User's ID. 
* @param String $credentials Json representation of the OAuth 2.0 credentials to store. 
*/ 
function storeCredentials($userId, $credentials) { 
    $_SERVER['userid'] = $userId; 
} 

/** 
* Build a Drive service object. 
* 
* @param String credentials Json representation of the OAuth 2.0 credentials. 
* @return Google_DriveService service object. 
*/ 
function buildService($credentials) { 
    $apiClient = new Google_Client(); 
    $apiClient->setUseObjects(true); 
    $apiClient->setAccessToken($credentials); 
    return new Google_DriveService($apiClient); 
} 

/** 
* Send a request to the UserInfo API to retrieve the user's information. 
* 
* @param String credentials OAuth 2.0 credentials to authorize the request. 
* @return Userinfo User's information. 
* @throws NoUserIdException An error occurred. 
*/ 
function getUserInfo($credentials) { 
    $apiClient = new Google_Client(); 
    $apiClient->setUseObjects(true); 
    $apiClient->setAccessToken($credentials); 
    $userInfoService = new Google_Oauth2Service($apiClient); 
    $userInfo = null; 
    try { 
    $userInfo = $userInfoService->userinfo->get(); 
    } catch (Google_Exception $e) { 
    print 'An error occurred: ' . $e->getMessage(); 
    } 
    if ($userInfo != null && $userInfo->getId() != null) { 
    return $userInfo; 
    } else { 
    throw new NoUserIdException(); 
    } 
} 


function retrieveAllFiles($service) { 
    $result = array(); 
    $pageToken = NULL; 

    do { 
    try { 
     $parameters = array(); 
     if ($pageToken) { 
     $parameters['pageToken'] = $pageToken; 
     } 
     $files = $service->files->listFiles($parameters); 

     $result = array_merge($result, $files->getItems()); 
     $pageToken = $files->getNextPageToken(); 
    } catch (Exception $e) { 
     print "An error occurred: " . $e->getMessage(); 
     $pageToken = NULL; 
    } 
    } while ($pageToken); 
    return $result; 
} 

function printFile($service, $fileId) { 
    try { 
    $file = $service->files->get($fileId); 

    print "Title: " . $file->getTitle(); 
    print "Description: " . $file->getDescription(); 
    print "MIME type: " . $file->getMimeType(); 
    } catch (apiException $e) { 
    print "An error occurred: " . $e->getMessage(); 
    } 
} 

// fill your details from the google console: 
$client = new Google_Client(); 
$client->setApplicationName('***************'); 
$client->setScopes(array(
         'https://www.googleapis.com/auth/drive', 
         'https://www.googleapis.com/auth/userinfo.email', 
         'https://www.googleapis.com/auth/userinfo.profile')); 
$client->setClientId('***************'); 
$client->setClientSecret('***************'); 
$client->setRedirectUri('***************/google-drive-api-php-client/serverside.php'); 
$client->setApprovalPrompt('force'); 
$client->setAccessType('offline'); 
$client->setDeveloperKey('***************'); 

// a simple code to check if the user have already login to the site and authenticate the site and if he does the site will not ask the user again for authentification and it will use the refresh token to "log" the user in 
if (empty($_GET['code'])) { 
    // if the user visit the website for the first time he need to authentificate (redirecting the website to google)! 
    if (empty($_SESSION['access_token']) && !isset($_SESSION['refresh_token'])) { 
     header('Location: ' . $client->createAuthUrl()); 
    // if the user have already visited the site, but the access token have expired use this code 
    } elseif (empty($_SESSION['access_token']) && isset($_SESSION['refresh_token'])) { 
     echo "refresh token1" . "<br>"; 
     $google_token = json_decode($_SESSION['refresh_token'], true); 
     $client->refreshToken($google_token['refresh_token']); 
     $_SESSION['access_token']= $client->getAccessToken(); 
    } 
} elseif (!empty($_GET['code']) && empty($_SESSION['access_token'])) { 
    // if the user is visiting the website for the first time and dont have refresh token: 
    if (!isset($_SESSION['refresh_token'])) { 
     echo "access token" . "<br>"; 
     $client->authenticate($_GET['code']); 
     $_SESSION['access_token'] = $client->getAccessToken(); 
     $_SESSION['refresh_token'] = $_SESSION['access_token']; 
     // this will never execute, but i put it anyway :) if the user have already visited the site, but the access token have expired use this code (its the same as the above) 
    } elseif (isset($_SESSION['refresh_token'])) { 
     echo "refresh token2" . "<br>"; 
     $google_token = json_decode($_SESSION['refresh_token'], true); 
     $client->refreshToken($google_token['refresh_token']); 
     $_SESSION['access_token']= $client->getAccessToken(); 
    } 
} 

// if the access token have expired use the refresh token to gain access instead: 
if ($client->isAccessTokenExpired()) { 
    $google_token = json_decode($_SESSION['refresh_token'], true); 
    $client->refreshToken($google_token['refresh_token']); 
    $_SESSION['access_token']= $client->getAccessToken(); 
} 

// unset the sessions for testing: 
// unset($_SESSION['access_token']); 
// unset($_SESSION['refresh_token']); 

// get some info from the user Google API like the file info 
if (!empty($_SESSION['access_token'])) { 

    // create the service in this case Google Drive 
    $service = buildService($_SESSION['access_token']); 
    // mark the file ID 
    $fileid = "*******************"; 

// print the access token 
    echo "<pre>"; 
    print_r(getUserInfo($_SESSION['access_token'])); 
    echo "</pre>"; 

    // print file metadata from google drive 
    // echo "<pre>"; 
    // print_r(printFile($service, $fileid)); 
    // echo "</pre>"; 


} 

// printing the session for testing... 
echo "<pre>"; 
print_r($_SESSION); 
echo "</pre>"; 

// print the refresh token for testing 
print_r($_SESSION['refresh_token']); 

// print echo to see if the code is executing till the end or there is a fatal error someone in the code :) 
echo "string"; 

?> 
관련 문제