gpt4 book ai didi

php - Google PHP 客户端库 - 'Login Required' 异常

转载 作者:搜寻专家 更新时间:2023-10-31 21:06:37 25 4
gpt4 key购买 nike

我在尝试访问我的 Google Analytics 数据时遇到以下错误:异常“Google_Service_Exception”,消息为“调用 GET 时出错...我的查询...”:(401) 需要登录

我不确定如何解决这个问题,我已经花了几个小时尝试设置它但没有成功。

这是我的代码:

        $client = new \Google_Client();
$client->setApplicationName("My App");
$client->setDeveloperKey('my API key');

$analytics = new \Google_Service_Analytics($client);

$OBJresult = $analytics->data_ga->get(
'ga:myprofileid' .,
'2012-01-01',
date("Y-m-d"),
'ga:visits',
array(
'filters' => 'ga:pagePath==/home',
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'sort' => '-ga:pageviews'
)
);

最佳答案

如果您只是访问自己的数据,那么您应该使用服务帐户。如果您希望能够登录并查看其他人的数据,那么您应该使用 Oauth2。

服务帐户示例:

<?php
require_once 'Google/autoload.php';
session_start();
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.

In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '[Your client id]';
$Email_address = '[YOur Service account email address Address]';
$key_file_location = '[Locatkon of key file]';

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);

// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";

$cred = new Google_Auth_AssertionCredentials($Email_address,
array($scopes),
$key);

$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}

$service = new Google_Service_Analytics($client);



//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );
?>

<html>
Results for date: 2014-12-14<br>
<table border="1">
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td><b>".$header['name']."</b></td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>

有用的链接:

  1. Service account tutorial 中提取的代码
  2. Google Analytics oauth2 tutorial
  3. 谷歌新官方教程Hello Analytics php

关于php - Google PHP 客户端库 - 'Login Required' 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31259836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com