Bigquery API php授权

时间:2014-07-30 08:08:40

标签: php oauth-2.0 google-bigquery google-api-php-client

我试图使用PHP库访问bigquery api,但我总是有这个错误:

  

致命错误:未捕获的异常' Google_Service_Exception'有消息'错误调用GET https://www.googleapis.com/bigquery/v2/projects/primeval-shadow-571/datasets/Test/tables :( 401)需要登录'在......

我有一个Web应用程序,需要从bigquery中的表中获取一些数据。远程帐户不是我的,但它是由一些人创建的(我没有登录并通过登录),他们给了我.json文件,其中包含了参数:

auth_uri, 
client_secret, 
token_uri, 
client_email, 
client_x509_cert_url, 
client_id and 
auth_provider_x509_cert_url.

这是我的php代码:

<?php

require_once 'Google/Client.php';
require_once 'Google/Service/Bigquery.php';

$client = new Google_Client();
$client->setAuthConfigFile('google-config.json');

$service = new Google_Service_Bigquery($client);

$service->tables->listTables('primeval-shadow-571', 'Test');

但最后我得到了上面的错误。

有谁可以告诉我哪里错了?

P.S。我两天前刚刚开始使用google api,所以我才开始学习它。

非常感谢。

1 个答案:

答案 0 :(得分:1)

以下是适用于我们的示例代码:

session_start();

define('PROJECT_ID', 'edited');
define('DATASET_ID', 'edited');
define('API_KEY', 'edited');

$client_id = 'edited';
$service_account_name = 'edited';
$key_file_location = '.ssh/privatekey-bigquery.p12';
$service_token_file_location = 'bigquery_current_service_token.json';

set_include_path("google-api-php/src/" . PATH_SEPARATOR . get_include_path());
require_once 'google-api-php/src/Google/Client.php';
require_once 'google-api-php/src/Google/Service/Bigquery.php';

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
//$client->setDeveloperKey(API_KEY);

if (!is_file($service_token_file_location)) {
    if (!is_writable($service_token_file_location)) {
        @chmod($service_token_file_location, 0777);
        if (!is_writable($service_token_file_location)) {
            die('Service token file is not writable: ' . $service_token_file_location);
        }
    }
    file_put_contents($service_token_file_location, '');
} else {
    if (!is_writable($service_token_file_location)) {
        @chmod($service_token_file_location, 0777);
        if (!is_writable($service_token_file_location)) {
            die('Service token file is not writable: ' . $service_token_file_location);
        }
    }
}
$service_token = @file_get_contents($service_token_file_location);
if (!empty($service_token)) {
    $client->setAccessToken($service_token);
}
if (!file_exists($key_file_location)) {
    die('Key file is missing: ' . $key_file_location);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
        $service_account_name, array(
    'https://www.googleapis.com/auth/bigquery',
        ), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
}
$service_token = $client->getAccessToken();
file_put_contents($service_token_file_location, $service_token);

// start using $client