如何使用服务帐户?我可以将我在谷歌的现有帐户用作服务帐户吗?

时间:2014-09-12 08:53:11

标签: php google-drive-api

所以,我在谷歌有两个帐户,一个是个人使用,一个是公司使用。在公司帐户我已经购买了驱动器配额,它是200gb(我认为),因此我将其用作文件存储云服务器。我的想法是使用google drive php api将一些文件实现到公司网站。只要我知道我可以Use Application-Owned Accounts听起来很棒,但我必须创建新帐户才能将它与普通帐户一起使用,如果我想在服务器端使用它我将不会能够在常规帐户中使用公司文件。所以,我坚持这种情况!?拜托,给我一些建议。这对我来说都是新手,所以我需要你的帮助。

修改 它从上面发布的链接中说的是:

  

您可以通过Google帐户注册流程或在Google Apps域上创建帐户,像任何用户一样创建常规Google帐户。 确保它永远不会被真人使用,只能由您的应用程序使用。

好的,但是我的帐户不是新的,之前已经使用过了。这意味着我将无法使用我的公司账户,如果这是真的,我怎样才能实现我的目标?

1 个答案:

答案 0 :(得分:0)

我经过几天研究如何做到这一点后终于做到了,这里有一个非常简单的代码,用于获取访问令牌,并在您拥有它之后如何获取您需要的刷新令牌以便访问用户离线时。我仍然需要了解我怎么知道什么时候我在数据库中存储这些值,我怎么知道这个用户与google id是来自数据库的同一个用户并将刷新令牌放在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";

?>