2

我试图找回从谷歌分析我们的内容的实验数据...谷歌Analytics(分析)API返回401示例代码

我使用下面的代码,我creds都不错,并已审查了这帖子...

<?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的任何想法未经授权?需要登录吗?

+0

您如何获得授权?您是否尝试使用绕过登录的服务帐户?看起来您的代码需要通过Google进行登录。 –

+0

有没有机会提供一些示例代码?我一直在这一整天.. = [ –

+0

那么,你是否尝试使用绕过登录或代码,需要通过谷歌登录的服务帐户? –

回答

4

问题是你还没有授权访问你的数据呢。既然你说只有你自己的数据你想访问我sugest你看看service account。通过在Google apis console中设置服务帐户,它将允许您访问自己的数据,而无需始终登录并验证代码。

检查以下链接。 虽然在之前开始阅读,但请确保您完成所有工作。

  1. 注册在谷歌开发者控制台
  2. 您的应用程序授权访问谷歌Analytics的数据。
  3. 创建Analytics服务对象

你skiped前两个步骤,直接去第3步创建的服务对象。一旦你完成了第1步中,你可以使用下面的代码为第2步


下面是如何在PHP ServiceAccount

这样的项目是针对PredictionService不是使用服务帐户的例子谷歌分析服务。你需要稍微修改它。

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,你可以使用你的其他呼叫。注意:我没有时间测试该代码让我知道它是否无效,我会帮你解决它。

+1

你是男人! –

+0

我喜欢它的工作? – DaImTo

+0

带有几个修改代码,我会编辑一次,我完全工作,目前遇到另一个错误。 –