我试图运行谷歌API嵌入服务器端授权的演示,在这里:https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/,但使用PHP,而不是Python的3步(使用JSON关键数据来请求访问令牌)。如何使用PHP运行Google Embed API服务器端授权?
我已经安装了谷歌API PHP客户端:https://github.com/google/google-api-php-client。
我创建了服务帐户(https://console.developers.google.com),为其启用了Analytics API,下载了JSON密钥文件,并将其复制到我的Web服务器(为了安全起见,位于Web根目录下)。
我已经注册了服务帐户在谷歌Analytics帐户(读&只分析)。
我尝试使用替代PHP代码从这里https://stackoverflow.com/a/32767845/1803239运行演示:
<?php
// Load the Google API PHP Client Library.
require_once 'google-api-php-client/src/Google/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('/path/to/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
// Get the results from the Core Reporting API and print the results.
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
//get the access token
$myToken = json_decode($client->getAccessToken());
?>
运行演示(在一个文件名为test3.php,用PHP代码,而不是Python代码)在失败这条线, $client->setAuthConfigFile('client_secrets.json');
, ,出现以下错误:
Fatal error: Uncaught exception 'Google_Exception' with message 'Invalid client secret JSON file.' in /var/www/vhosts/mydomain.com/google-api-php-client/src/Google/Client.php:171 Stack trace:
#0 /var/www/vhosts/mydomain.com/google-api-php-client/src/Google/Client.php(189): Google_Client->setAuthConfig('{? "type": "se...')
#1 /var/www/vhosts/mydomain.com/httpdocs/test3.php(36): Google_Client->setAuthConfigFile('/var/www/vhosts...')
#2 {main} thrown in /var/www/vhosts/mydomain.com/google-api-php-client/src/Google/Client.php on line 171
任何人都可以说明为什么我的JSON密钥文件可能会失败?
更新:OK,我一直在努力,现在得到这个工作5天。也许它可以发挥作用,但我对Google文档的信心很糟糕。谷歌,如果你正在阅读这篇文章,请整理你的文档,他们是极端sl sl。对他们进行测试。
如果任何人都可以提供API服务器端授权演示(https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/)的实际示例,但在步骤3中使用PHP而不是Python,我将永远感激不尽。谢谢。
因为你喂养它一个服务帐户JSON文件,而不是一个的oauth2 JSON文件。您的代码适用于Oauth2而不是服务帐户。 – DaImTo
演示说明确实会说“步骤1:创建服务帐户并下载JSON密钥”。他们可能是错的,还是我在这里使用错误的PHP代码? – Gavin
您正在使用错误的php代码。 https://developers.google.com/api-client-library/php/auth/service-accounts – DaImTo