从哪里获取Google Analytics API access_token?

时间:2014-10-16 08:13:54

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

根据Google Analytics API Reference OAuth以及访问令牌可用于访问网页的统计信息。使用OAuth非常复杂,或者至少在我看来像在PHP中。但是根据文档我还应该能够使用access_code作为get参数。

我尝试了几种方法从google developer console获取access_token,但两种方法都不能正常返回以下错误:

{"error":{"errors":[{"domain":"global","reason":"required","message":"Login Required","locationType":"header","location":"Authorization"}],"code":401,"message":"Login Required"}}

因此,我想知道如何为我的Google Analytics分析页面属性获取无效的api访问代码?如果可能的话?

1 个答案:

答案 0 :(得分:1)

您需要先在Google Developer console注册您的申请。这是使用Oauth2获取访问令牌的问题。您首先要求用户获得访问其数据的权限,从而获得访问令牌。获得许可后,您将收到一个可用于获取访问令牌的刷新令牌。

以下示例使用GitHub上的Google PHP客户端库。代码是从我的Google Oauth2 PHP Tutorial教程中复制的。

<?php         
require_once 'Google/Client.php';     
require_once 'Google/Service/Analytics.php';       
session_start();      
$client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $client->setDeveloperKey("{devkey}");  
    $client->setClientId('{clientid}.apps.googleusercontent.com');
    $client->setClientSecret('{clientsecret}');
    $client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
    $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

    //For loging out.
    if ($_GET['logout'] == "1") {
    unset($_SESSION['token']);
       }   

    // Step 2: The user accepted your access now you need to exchange it.
    if (isset($_GET['code'])) {

        $client->authenticate($_GET['code']);  
        $_SESSION['token'] = $client->getAccessToken();
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    // Step 1:  The user has not authenticated we give them a link to login    
    if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
        $authUrl = $client->createAuthUrl();
        print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }        

    // Step 3: We have access we can now create our service
    if (isset($_SESSION['token'])) {
        print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
        $client->setAccessToken($_SESSION['token']);
        $service = new Google_Service_Analytics($client);    

        // request user accounts
        $accounts = $service->management_accountSummaries->listManagementAccountSummaries();

       foreach ($accounts->getItems() as $item) {
        echo "Account: ",$item['name'], "  " , $item['id'], "<br /> \n";        
        foreach($item->getWebProperties() as $wp) {
            echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WebProperty: ' ,$wp['name'], "  " , $wp['id'], "<br /> \n";    

            $views = $wp->getProfiles();
            if (!is_null($views)) {
                foreach($wp->getProfiles() as $view) {
                //  echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;View: ' ,$view['name'], "  " , $view['id'], "<br /> \n";    
                }
            }
        }
    } // closes account summaries

    }
 print "<br><br><br>";
 print "Access from google: " . $_SESSION['token']; 
?>