4

フュージョンテーブルにデータをインポートするためにOAuthアクセストークンを取得しようとしています。GoogleAPIPHPクライアントを使用しようとしています。その目的のためにサービスアカウントを作成し、主に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。例外はスローされません。根本的に間違ったことをしているような気がします。もしそうなら、私の愚かさを許し、正しい方向に私を向けてください。

4

2 に答える 2

6

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();
于 2012-11-27T17:39:20.770 に答える
1

あなたがしたことはすべて正しかったと思います。あと 2 つのオプションが残っています。

  • your$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

どちらの 場合、私の GitHub リポジトリに例があります。

于 2012-11-27T11:29:38.180 に答える