我已经下载了google-api-php-client来访问google api。
我的代码是
include_once "templates/base.php";
echo pageHeader("Simple API Access");
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Bigquery.php';
$client = new Google_Client();
$client->setApplicationName("my application name");
$apiKey = "--------my api key----";
$client->setDeveloperKey($apiKey);
define("PROJECT_ID", my project ID);
define("DATASET_ID", "my data set ID");
$service = new Google_Service_Bigquery($client);
$results = $service->tables->listTables(PROJECT_ID, DATASET_ID);
print_r($results);
如果我运行上面的文件,它会给出错误:致命错误:未捕获的异常'Google_Service_Exception',消息'错误调用GET https://www.googleapis.com/bigquery/v2/projects/projectID/datasets/datasetname/tables?key=API键:(401)需要登录'在C:\ xampp \ htdocs \ test \ google- api-php-client-master(2)\ google-api-php-client-master \ src \ Google \ Http \ REST.php:80堆栈跟踪:#0 C:\ xampp \ htdocs \ test \ google-api- php-client-master(2)\ google-api-php-client-master \ src \ Google \ Http \ REST.php(44):Google_Http_REST :: decodeHttpResponse(Object(Google_Http_Request))#1 C:\ xampp \ htdocs \ test \ google-api-php-client-master(2)\ google-api-php-client-master \ src \ Google \ Client.php(499):Google_Http_REST :: execute(Object(Google_Client),Object(Google_Http_Request) ))#2 C:\ xampp \ htdocs \ test \ google-api-php-client-master(2)\ google-api-php-client-master \ src \ Google \ Service \ Resource.php(195):Google_Client - >执行(对象(Google_Http_Request))#3 C:\ xampp \ htdocs \ test \ google-api-php-client-master(2)\ google-api-php-client-master \ src \ Google \ Service \ B在C:\ xampp \ htdocs \ test \ google-api-php-clien中第80行的t-master(2)\ google-api-php-client-master \ src \ Google \ Http \ REST.php
答案 0 :(得分:1)
您需要使用OAUTH 2.0验证您的应用
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$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);
}
$_SESSION['service_token'] = $client->getAccessToken();
var_dump($_SESSION);
$bq = new Google_Service_Bigquery($client);