如何使用Google API PHP客户端获取OAuth2访问令牌?

时间:2012-11-22 06:23:23

标签: php google-api google-fusion-tables google-oauth

我正在尝试获取OAuth访问令牌以将一些数据导入到融合表中。我正在尝试使用Google API PHP客户端。我已经为此目的创建了一个服务帐户,并且正在使用代码,主要来自serviceAccount示例:

function access_token()
{
    $client = new Google_Client();
    $client->setAuthClass ('Google_OAuth2');
    // ^ Don't know if this line is required,
    // ^ but it fails just as well without it.
    $client->setApplicationName ('Mysite.dom.ain');
    $client->setAssertionCredentials (new Google_AssertionCredentials
        (   'MANY-NUMBERS-LETTERS-DASHES@developer.gserviceaccount.com',
            array ('https://www.googleapis.com/auth/fusiontables'),
            file_get_contents ('path/to/my/privatekey.p12') ));
    $client->setClientId ('NUMBERS-LETTERS-DASHES.apps.googleusercontent.com');
    $client->authenticate();
    // ^ Also fails equally good with and without this line.
    return $client->getAccessToken();
}

一点调试输出显示$client->authenticate()返回true,但$client->getAcessToken()返回null。没有异常被抛出。我觉得我做的事情从根本上是错误的。如果是这样,请原谅我的愚蠢,并指出我正确的方向。

2 个答案:

答案 0 :(得分:5)

您不需要authenticate()调用,但是您需要调用refreshTokenWithAssertion()来刷新底层访问令牌。如果您使用客户端库来发出签名请求,那么如果基础访问令牌已过期,它将懒惰地为您进行此调用。

刷新access_token的API请求很昂贵,且配额很低,因此您需要缓存access_token。

// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME';

// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';

$client = new Google_Client();
$client->setApplicationName("Google FusionTable Sample");

// Set your cached access token. Remember to store the token in a real database instead of $_SESSION.
session_start();
if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
    SERVICE_ACCOUNT_NAME,
    array('https://www.googleapis.com/auth/fusiontables'),
    $key)
);

$client->setClientId(CLIENT_ID);

if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion();
}

// Get the json encoded access token.
$token = $client->getAccessToken();

答案 1 :(得分:1)

我认为你所做的一切都是正确的,现在你还有两个选择:

  • 使用您的$client拨打类似
  • 的服务电话
    $service = new Google_FusiontablesService($client);
    $selectQuery = "select * from 1AwxQ46kfmPoYoq38e5CopJOWkCo_9GUU_ucD6zI";
    $service->query->sql($selectQuery)
  • 或者调用内部函数refreshTokenWithAssertion()以获取令牌:
    $client::$auth->refreshTokenWithAssertion();
    $token = $client->getAccessToken(); //this should work now

both cases我的GitHub回购中有例子。