Google Analytics(分析)API返回示例代码401



我试图从Google Analytics(分析)中检索我们的内容实验的数据...

我正在使用以下代码,我的信誉很好,并且对此文章进行了审查...

<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://cloud.google.com/console to generate your
// client id, client secret, and to register your redirect uri.
$client->setDeveloperKey('xxxxx');
$service = new Google_Service_Analytics($client);
try {
$results = $service->management_experiments->listManagementExperiments('xxxx', 'xxxx', 'xxxx');
} catch (apiServiceException $e) {
  print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
  print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
echo '<pre>';
print_r($results);
echo '</pre>';

我正在使用以下示例....

https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtexperimentsguide#list

关于我为什么要获得401的任何想法?需要登录?

问题是您尚未授权访问数据。由于您说这只是您自己的数据,因此您想访问我,我会求助于服务帐户。通过在Google APIS控制台中设置服务帐户,它将允许您访问自己的数据,并且不需要始终登录和自动登录代码。

检查以下链接。虽然在之前先阅读,请确保做所有这些。

https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtexperimentsguide#service

  1. 在Google开发人员控制台中注册您的应用程序
  2. 授权访问Google Analytics(分析数据)。
  3. 创建一个分析服务对象

您已经跳过了前两个步骤,直接转到了步骤3创建服务对象。完成步骤1后,您可以将以下代码用于步骤2。


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

该示例项目用于预测服务,而不是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,可以与其余的呼叫一起使用。注意:我没有时间测试该代码,让我知道它是否不起作用,我会为您提供修复。

最新更新