php - 在哪里获取 Google Analytics API access_token?

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

根据Google Analytics API Reference OAuth 以及访问 token 可用于访问页面的统计信息。使用 OAuth 相当复杂,或者至少在我看来,在 php 中是这样的。但是根据文档,我也应该能够使用 access_code 作为获取参数。

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

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

因此,我想知道如何为我的谷歌分析页面属性获取一个永不过期的 api 访问代码?如果可能的话?

最佳答案

您需要在 Google Developer console 上注册您的应用程序第一的。它是使用 Oauth2 获取访问 token 的问题。您首先要求用户授予访问其数据的权限,从而获得访问 token 。获得许可后,您将收到一个刷新 token ,您可以使用它来获取访问 token 。

以下示例使用位于 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']; 
?>

关于php - 在哪里获取 Google Analytics API access_token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26399357/

相关文章:

json - Twitter 流 api OAuth 未经授权

oauth - 所有这些字段是什么意思?

java - 防止 Cassandra 转储 hprof 文件

php - 在 php 变量上调用 javascript 函数

php - 将特定格式的日期插入 MySQL 数据库

android - Unity Ads 4.0 - 奖励广告的多个 OnUnityAdsShowComplete 回调

python - 如何使用 github-flask 为 {+path} 提供 URL 参数?

android - Chrome 自定义标签页重定向到 Android 应用程序将关闭该应用程序

php - PHP 中的 Exception 和 RuntimeException 有区别吗?

python - 我需要使用 pylast 的 library.add_album 功能的帮助(python last.fm api 包装器)