2014-11-06 39 views
1

我是Google API的新手,並且無法使Google Analytics API正常工作。到目前爲止,我已經設置了開發者控制檯,創建了一個項目,並生成了相關的證書。我註冊的電子郵件ID是[email protected],默認情況下重定向URI設置爲http://www.mycompany.com/oauth2callback。 JavaScript起源設置爲http://www.mycompany.comGoogle API重定向URI無法正常工作

當我從localhost運行項目時,我可以啓動OAuth過程。但是當我點擊「允許」按鈕時,我被髮送到http://www.mycompany.com並沒有任何反應。我可能做錯了什麼?我是否需要從mycompany.com doamin運行此腳本才能正常工作?最後,我如何從本地主機運行它?

<?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>'; 
    } 
} 
+0

你想讓別人能看到Google Analytics(分析)數據,或者您想讓其他人訪問您的Google Analytics(分析)數據嗎?在我們可以幫助您之前,您確實需要添加一些代碼。 – DaImTo 2014-11-06 08:45:03

+0

@DalmTo我想創建一個請求用戶權限並從其Analytics(分析)中提取只讀數據的應用程序。現在我正在通過自己的帳戶進行測試,因此開發人員和用戶帳戶都是'myname @ mycompany.com'。代碼補充,雖然它只是官方教程。 – dotslash 2014-11-06 08:48:24

回答

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頁面,它應該重定向。

+0

@達爾我認爲是這樣。對不起,我的無知,但redirectURI PHP腳本應該做什麼?我的意思是登錄憑證存儲在源腳本中。 。 。我需要從會話中檢索嗎? – dotslash 2014-11-06 08:58:39

+0

重定向URI基本上告訴認證服務器在哪裏返回認證。一個文件應該能夠漢德爾全部檢查步驟2. – DaImTo 2014-11-06 09:00:32

+0

@達姆謝謝!我現在已經接受了答案。將盡快嘗試。 :) – dotslash 2014-11-06 09:13:11

相關問題