gpt4 book ai didi

OAuth 2.0 与 Google Analytics API v3

转载 作者:行者123 更新时间:2023-12-03 09:49:54 25 4
gpt4 key购买 nike

我曾经能够使用我帐户的登录名和密码查询 Google Analytics API。
Google 现在正在使用 OAuth 进行身份验证,这很棒......
唯一的问题是我只需要一个访问 token 。
我不想让其他用户获取他们的分析数据。

我只想能够获取我的数据。
有没有办法只为我的应用程序或我的分析帐户生成访问 token ?

我知道存在这样的解决方案……例如,Twitter 为不需要特定用户登录的应用程序提供了他们所谓的“单用户 oauth”。

再一次,我在这里试图完成的是通过 API 获取我自己的分析数据。

有没有办法正确地做到这一点?

最佳答案

我正在添加一个 PHP 答案 - 您可以将其调整或转换为 garb/ruby​​ 代码。

您现在应该可以通过服务帐户使用 Analytics。您确实必须使用私钥而不是访问 token 。

在 API 控制台中创建应用
基本上,您转到 Google API 控制台并创建一个应用程序。
在服务选项卡中启用 Google Analytics。
在 API 访问选项卡中,创建一个新的 OAuth ID(创建另一个客户端 ID... 按钮),选择 服务帐号并下载您的私钥(生成新 key ...链接)。稍后您必须将 key 上传到您的网络服务器。

在 API 访问页面的服务帐户部分,复制电子邮件地址 (@developer.gserviceaccount.com) 并将使用此电子邮件地址的新用户添加到您的 Google Analytics 配置文件。 如果你不这样做,你会得到一些很好的错误

代码
从 SVN 下载最新的 Google PHP 客户端(从命令行 svn checkout http://google-api-php-client.googlecode.com/svn/trunk/ google-api-php-client-read-only )。

您现在可以通过代码访问 Analytics API:

require_once 'Google_Client.php';              
require_once 'contrib/Google_AnalyticsService.php';

$keyfile = 'dsdfdss0sdfsdsdfsdf44923dfs9023-privatekey.p12';

// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Your product name');

$client->setAssertionCredentials(
new Google_AssertionCredentials(
'11122233344@developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyfile)
)
);

// Get this from the Google Console, API Access page
$client->setClientId('11122233344.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);

// We have finished setting up the connection,
// now get some data and output the number of visits this week.

// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:1234';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');

try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}

关于OAuth 2.0 与 Google Analytics API v3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10057928/

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