2016-06-10 100 views
0

我對瀏覽器的Google API訪問有一種「哲學上的疑問」(在我的例子中是Google Calendar API,但這並不重要)。Javascript:如何使用Google API從Web應用訪問*特定用戶*數據?

我正在寫一個不錯的(angular.js)Web應用程序的一個小酒店;它包含預訂表單。
我想將預訂表格鏈接到酒店的Google日曆帳戶,以便能夠顯示已經預訂的日期不可用,以及在哪裏編寫最終預訂。

我的疑問是:從瀏覽器訪問Google API需要oAuth2。精細。但我不希望Web應用程序的用戶給我訪問自己帳戶,但我希望能夠訪問酒店帳戶,它的clientId我知道......

我敢肯定我很困惑,請給我一些建議... :-(

+0

聽起來像你需要一個[服務帳戶](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) - 該帳戶將屬於應用程序,而不是最終用戶 - 所以你會配置你的應用程序只與酒店帳戶交互 – Und3rTow

+0

所以我需要一個服務器端組件(例如一個node.js + express.JS腳本)運行,對吧?如此簡單的網絡空間不足以發佈應用程序,但我需要某種Web服務器運行模式應用程序,對吧? – MarcoS

+0

不,您可以構建localy並部署到普通的Web服務器,但它將取決於您使用何種語言訪問服務帳戶 – Und3rTow

回答

1

我有一個應用程序使用類似的情況,但使用谷歌分析,所以我所做的是設立一個谷歌服務帳戶,然後下載並使用php auth library設置處理auth的端點,並向我提供我從應用請求的數據。

相關代碼是s omething這樣的:

谷歌,data.php

<?php 

    require_once '/path-to/google/src/Google/autoload.php'; 

    $veiwId = $_GET['viewid']; // Sent from the app 
    $client_email = 'YOUR_SERVICE_ACCOUNT_EMAIL_HERE'; //looks something like - [email protected] 
    $private_key = file_get_contents('/path-to/APIProject-c5bfsdf45d54d.p12'); // downloaded from Google dev console 
    // Define the service you want to use (Calendar, Analytics, etc.) 
    $scopes  = array(Google_Service_Analytics::ANALYTICS_READONLY); 
    $credentials = new Google_Auth_AssertionCredentials(
     $client_email, 
     $scopes, 
     $private_key 
    ); 

    $client = new Google_Client(); 
    $client->setAssertionCredentials($credentials); 
    // Grab token if it's set 
    if (isset($_SESSION['service_token'])) { 
     $client->setAccessToken($_SESSION['service_token']); 
    } 
    // Refresh if expired 
    if ($client->getAuth()->isAccessTokenExpired()) { 
     $client->getAuth()->refreshTokenWithAssertion(); 
    } 
    // Pin to Session 
    $_SESSION['service_token'] = $client->getAccessToken(); 

    // Here is where you will start using the service, such as Google Calendar, etc. 
    $service = new Google_Service_Analytics($client); 
    // Adding Dimensions 
    $params = array('dimensions' => 'ga:medium'); 
    // requesting the data (methods will depend on the service) 
    $data = $service->data_ga->get(
     // params from get request 
     // request logic, etc. 
    ); 
    // Return to client as JSON 
    echo json_encode($data); 
?> 

你顯然不需要,因爲有很多others available,但是概念是相同的使用PHP庫。我的用例很簡單,所以PHP是最重要的。

那個設定我能夠從我的角度應用程序發送一個簡單的GET請求的數據:

app.factory('DataLoader', function($http, $log) { 

    return { 
     getGoogleData: function(toDate, fromDate, viewId) { 
     // Pass in some dates and a profile id 
     return $http.get('path-to/google-data.php?todate='+toDate+'&fromdate='+fromDate+'&viewid='+viewId); 
     } 

    } 
}) 

希望這可以幫助您瞭解如何讓你的應用程序與谷歌API的交互你的最終用戶與api交互。

+1

我只能設置節點。 js應用程序,但是您的回答對於讓我瞭解Google API邏輯的用例非常有用...謝謝! – MarcoS

+0

最後,我正在使用PHP解決方案來解決此問題,以避免重複節點公共節點服務器成本... – MarcoS

相關問題