Google PHP客户端库 - '需要登录'例外

时间:2015-07-07 04:38:42

标签: php google-api google-oauth google-analytics-api google-api-php-client

尝试访问我的Google Analytics数据时出现以下错误:exception 'Google_Service_Exception' with message 'Error calling GET ...my query...': (401) login required

我不确定如何解决这个问题,而且我已经花了好几个小时试图解决这个问题但没有成功。

这是我的代码:

        $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'
            )
        );

4 个答案:

答案 0 :(得分:2)

如果您只访问自己的数据,那么您应该使用服务帐户。如果您希望能够登录并查看其他人的数据,那么您应该使用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. Google的新官方教程Hello Analytics php

答案 1 :(得分:0)

显示的代码不会在任何地方进行身份验证。

我不是此API的专家,但根据this link,您缺少以下某些选项。

$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('My Application name');
$client->setClientId('INSERT HERE');
$client->setClientSecret('INSERT HERE');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('INSERT HERE'); // API key

答案 2 :(得分:0)

接受的答案对我的服务帐户不起作用。取而代之的是:

  1. IAM & Admin panel创建服务帐户。确保以JSON格式获取密钥文件。
  2. 将该密钥文件下载到可从您的脚本访问的位置(但无法从Web访问!)
  3. 运行以下代码:
  4. $service_url = "https://www.googleapis.com/auth/analytics.readonly"; $client = new Google_Client(); $client->setAuthConfigFile($key_file_location); // path to your json key file $client->addScope($service_url); // URL to the service you're planning to use // Run your queries here

答案 3 :(得分:0)

DalmTo's answer为我做了诀窍,但是如果你不想硬编码$client_id,那么你可以稍微简化一下:

public function __construct() {
    $this->client = new Google_Client();
    $credentials = $this->client->loadServiceAccountJson(__DIR__.'/../../google-service-account.json', [Google_Service_Calendar::CALENDAR]);
    $this->client->setAssertionCredentials($credentials);

    if($this->getAuth()->isAccessTokenExpired()) {
        $this->getAuth()->refreshTokenWithAssertion($credentials);
    }
}

/**
 * @return \Google_Auth_OAuth2
 */
public function getAuth() {
    return $this->client->getAuth();
}

google-service-account.json是您在创建服务帐户时为其提供的密钥文件。它看起来像这样:

{
  "type": "service_account",
  "project_id": "xxxxxxxxxx",
  "private_key_id": "xxxxxxxxxxxxxxxxxxx",
  "private_key": "-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n",
  "client_email": "xxxxxxxxxx@xxxxxxx.iam.gserviceaccount.com",
  "client_id": "xxxxxxxxxxxxxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxxx.iam.gserviceaccount.com"
}