“Google MC Funnels API”(401未经授权)

时间:2015-12-01 00:40:13

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

我设置了一个MC漏斗示例,一切正常!!:

  • 从git下载Master。
  • 放一个帐户就行了!
  • 没关系!返回一些书籍样本的结果......

所以,我把新代码放到了" mcf:"但接受" 401未经授权"

问题:如何/在何处授权查询" mcf:xxxxxxx"指标和维度?

我使用的代码:

include_once __DIR__ . '/../vendor/autoload.php';
include_once "templates/base.php";
// $client->setApplicationName("Client_Library_Examples");
// $client->setScopes(['https://www.googleapis.com/auth/books']);    //not sure here..

// $service = new Google_Service_Books($client);
   $service = new Google_Service_Analytics($client);      //not sure here..

        $mcf = $service->data_mcf(
            'ga:80456636',
            '2015-02-22',
            '2015-02-23',
            'mcf:totalConversionValue',
            array(
                'dimensions' => 'mcf:source,mcf:medium'
            )
        );

        echo"<pre>";
        var_dump($mcf);
        echo"</pre>";

1 个答案:

答案 0 :(得分:1)

首先,你注释掉了$ client的所有代码。 Google图书是公共API,这意味着您可以使用公共API密钥进行身份验证。 Google Analytics数据是私有数据,这意味着您需要使用Oauth2或服务帐户。

服务帐户示例

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

$mcf = $service->data_mcf->get('ga:80456636',
            '2015-02-22',
            '2015-02-23',
            'mcf:totalConversionValue',
            array(
                'dimensions' => 'mcf:source,mcf:medium'
            )
        );

        echo"<pre>";
        var_dump($mcf);
        echo"</pre>";