php - Google Analytics API - 无需使用 "consent screen"进行身份验证即可获取访问 token

标签 php google-analytics google-analytics-api access-token

我正在开发一个使用 Google Analytics API 的网站。我遵循了本教程 -> https://developers.google.com/analytics/solutions/articles/hello-analytics-api?hl=pt-PT

一切正常。我看到“同意屏幕”,我授予“权限”,然后我被重定向到我的网站,其中包含所有信息。

但是,我想稍微改变一下。我想获取 Google Analytics 的所有信息,而不使用“同意屏幕”,即仅使用 Google Analytics 代码 (UA-XXXXXXXX-X) 或任何其他方式。

有什么帮助吗?

谢谢

最佳答案

为了使用 Google Analytics API,您需要获得授权(访问数据的权限)。因为您只想查看自己的数据,所以我建议您查看 service account .通过在 Google api 控制台中设置服务帐户,您可以访问自己的数据,而无需始终登录和验证代码。


这是一个如何在 php 中使用服务帐户的示例 ServiceAccount

该示例项目适用于 PredictionService 而不是 Google Analytics 服务。你需要稍微编辑一下。

require_once '../../src/Google/Client.php'; 
require_once '../../src/Google/Service/Analytics.php'; 

// Set your client id, service account name, and the path to your private key. 
// For more information about obtaining these keys, visit: 
// https://developers.google.com/console/help/#service_accounts

const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID'; 
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME'; 


// Make sure you keep your key.p12 file in a secure location, and isn't 
// readable by others.

const KEY_FILE = '/super/secret/path/to/key.p12'; 


$client = new Google_Client(); 
$client->setApplicationName("Google Analytics Sample"); 


// Load the key in PKCS 12 format (you need to download this from the 
// Google API Console when the service account was created. 


$client->setAssertionCredentials(new Google_AssertionCredentials( 
    SERVICE_ACCOUNT_NAME(Email), 
    array('https://www.googleapis.com/auth/analytics.readonly'), 
    file_get_contents(KEY_FILE)) 
); 


$client->setClientId(CLIENT_ID); 
$service = new Google_Service_Analytics($client);

现在您有了 $service,您可以在其余的调用中使用它。

关于php - Google Analytics API - 无需使用 "consent screen"进行身份验证即可获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708305/

相关文章:

php - 从 Paypal 捐赠按钮取回捐赠值(value)?

php - 使用 php 给下拉列表一个默认值

javascript - target=_blank 不适用于 GA 出站链接跟踪

google-analytics - 是否有任何 Google 分析流/实时 API?

google-analytics - Google Analytics API登录由于网络服务器IP更改而导致安全漏洞

PHP 比较二维数组

php 发送邮件(邮件正文取自数据库)

google-analytics - 谷歌分析检查 "Unique Visitors"PHP

google-analytics - Google Analytics 崩溃报告 iOS - 不清楚错误是什么

asp.net - 使用 Analytics Api 显示 'Pure HTML Dashboards' 或 'Custom Components'