且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Bigquery API php授权

更新时间:2023-02-17 09:16:52

为我们工作:

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