PHP-авторизация Bigquery API

Я пытаюсь получить доступ к bigquery api с помощью библиотеки PHP, но у меня всегда возникает эта ошибка:

Неустранимая ошибка: необработанное исключение «Google_Service_Exception» с сообщением «Ошибка при вызове GET https://www.googleapis.com/bigquery/v2/projects/primeval-shadow-571/datasets/Test/tables: (401) Требуется вход" в ...

У меня есть веб-приложение, которому нужно получить данные из таблицы в bigquery. Учетная запись Remote не моя, но ее создал какой-то парень (и у меня нет логина и пароля для входа), который дал мне файл .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 два дня назад, поэтому только начинаю его изучать.

Большое спасибо.


person Alex Bondarenko    schedule 30.07.2014    source источник


Ответы (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
person Pentium10    schedule 30.07.2014