Google API重定向URI无法正常运行

时间:2014-11-06 08:40:59

标签: php google-analytics-api

我是Google API新手,无法使Analytics API正常运行。到目前为止,我已经设置了开发者控制台,创建了一个项目,并生成了相关的凭据。我的注册电子邮件ID为myname@mycompany.com,默认情况下,重定向URI设置为http://www.mycompany.com/oauth2callback。 JavaScript起源设置为http://www.mycompany.com

当我从localhost运行项目时,我能够启动OAuth程序。但当我点击"允许"按钮,我已发送到http://www.mycompany.com但没有任何反应。我能做错什么?我是否需要从mycompany.com doamin运行此脚本才能使用它?最后,我如何从localhost运行它?

<?php
include_once "google_api/autoload.php";

session_start();

$client = new Google_Client();
$client->setApplicationName("Hello Analytics API Example");

$client->setClientId('XXXXXXXXXXXXXXXXX');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXX');
//$client->setRedirectUri('XXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXX');
$client->setDeveloperKey('XXXXXXXXXXXXXXXXXXXX');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

// Magic. Returns objects from the Analytics Service instead of associative arrays.
//print_r($client);
//$client->setUseObjects(true);

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

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if (!$client->getAccessToken()) 
{
    $authUrl = $client->createAuthUrl();
    print "<a class='login' href='$authUrl'>Connect Me!</a>";
} 
else 
{
    // Create analytics service object. See next step below.
    $analytics = new apiAnalyticsService($client);
    runMainDemo($analytics);
}

function runMainDemo(&$analytics) {
    try {

        // Step 2. Get the user's first view (profile) ID.
        $profileId = getFirstProfileId($analytics);

        if (isset($profileId)) {

            // Step 3. Query the Core Reporting API.
            $results = getResults($analytics, $profileId);

            // Step 4. Output the results.
            printResults($results);
        }

    } catch (apiServiceException $e) {
        // Error from the API.
        print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();

    } catch (Exception $e) {
        print 'There wan a general error : ' . $e->getMessage();
    }
}

function getFirstprofileId(&$analytics) {
    $accounts = $analytics->management_accounts->listManagementAccounts();

    if (count($accounts->getItems()) > 0) {
        $items = $accounts->getItems();
        $firstAccountId = $items[0]->getId();

        $webproperties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

        if (count($webproperties->getItems()) > 0) {
            $items = $webproperties->getItems();
            $firstWebpropertyId = $items[0]->getId();

            $profiles = $analytics->management_profiles
            ->listManagementProfiles($firstAccountId, $firstWebpropertyId);

            if (count($profiles->getItems()) > 0) {
                $items = $profiles->getItems();
                return $items[0]->getId();

            } else {
                throw new Exception('No views (profiles) found for this user.');
            }
        } else {
            throw new Exception('No webproperties found for this user.');
        }
    } else {
        throw new Exception('No accounts found for this user.');
    }
}

function getResults(&$analytics, $profileId) {
    return $analytics->data_ga->get(
            'ga:' . $profileId,
            '2012-03-03',
            '2012-03-03',
            'ga:sessions');
}

function printResults(&$results) {
    if (count($results->getRows()) > 0) {
        $profileName = $results->getProfileInfo()->getProfileName();
        $rows = $results->getRows();
        $sessions = $rows[0][0];

        print "<p>First view (profile) found: $profileName</p>";
        print "<p>Total sessions: $sessions</p>";

    } else {
    print '<p>No results found.</p>';
  }
}

1 个答案:

答案 0 :(得分:0)

如果您希望能够自动请求数据,则需要存储refreshtoken。如果您只希望他们能够访问您网站上的数据,那么这应该可以帮助您入门。

可以在此处找到最新的Google PHP客户端库。 Github

<?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']; 
?>

代码从教程Google Analytics Oauth2 with php中删除。

更新:查看您的代码后,我认为您的部分问题可能是您没有将redirectURi链接到页面。它不能只是一个目录,你必须给它应该重定向到的PHP页面。