2016-06-10 107 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

相关问题