2015-07-20 53 views
0

我有一個應用程序使用Google JS API以oauth登錄用戶,然後從他們的gmail acct等獲取信息。該應用程序在網上工作正常,但有問題與Trigger.io(Android和iOS版本)。腳本通過google js api在trigger.io應用程序

<script src="https://apis.google.com/js/client.js?onload=ginit"></script> 

加載,然後ginit函數調用gapi客戶通過client.js加載:

if (!!gapi) { 
    gapi.client.setApiKey(GoogleApp.apiKey); 
} 

在Android上,gapi存在,但不知何故gapi.client不,導致錯誤。

在iOS上,庫加載工作正常,但隨後調用gapi.auth.authorize(這可能會導致打開新窗口)會導致Webview錯誤:Error Domain=NSURLErrorDomain Code=-999 "The operation couldn’t be completed."我正在使用子瀏覽器和跨域ajax模塊,但當然無法改變Google庫實現調用的方式。我把代碼忽略每this和類似的錯誤,但仍然在auth不起作用:

try { 
    gapi.auth.authorize({client_id: GoogleApp.clientId, scope: GoogleApp.scopes, response_type: 'token id_token', immediate: false, approval_prompt: 'force'}, gHandleAuthResult); 
} catch (e) { 
    if (e.indexOf('NSURLErrorCancelled') === -1) { // iOS error on cancelled window, ignore 
     throw e; 
    } 
} 

有沒有使用谷歌API從Trigger.io應用更好的辦法?或者使用Google API的Trigger.io應用的示例?

我的下一個問題可能會與確定js的起源,which is already covered in another post,但還沒有答案。感謝您的幫助!

回答

0

我做了一個詳細的寫了關於如何得到這個工作在這裏:

Using OAuth 2.0 and the Google API Client Library for Javascript with Trigger.io Forge

基本上,該解決方案可以歸結爲:

  1. 使用僞造httpd模塊來解決Google的庫加載程序中的錯誤,導致它從具有始發協議的頁面運行時出現故障,此頁面不是http:,https:file:

  2. 使用僞造tabs模塊來處理OAuth流程而不是Google的gapi.auth.authorize函數,以避免嘗試在混合應用程序中打開彈出式瀏覽器窗口而導致的問題。

示例代碼:

function OAuthorize(options, success, error) { 
    options.response_type = "token"; 
    var url = options.url; 
    delete options.url; 

    forge.tabs.openWithOptions({ 
     url: url + "?" + $.param(options), 
     pattern: (options.redirect_uri + "*") 
    }, function (data) { 
     if (data.userCancelled) { 
      return error("Login failed: User Cancelled"); 
     } 

     // parse token from the url encoded response 
     var token = {}, queryString = data.url.substring(data.url.indexOf("#") + 1), 
     regex = /([^&=]+)=([^&]*)/g, m; 
     while ((m = regex.exec(queryString))) { 
      token[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); 
     } 

     if (token.error) { 
      return error("Login failed: " + token.error); 
     } 

     success(token); 
    }); 
} 

...你可以使用它像這樣:

OAuthorize({ 
    url: "https://accounts.google.com/o/oauth2/auth", 
    client_id: "your google client id", 
    redirect_uri: "http://localhost/oauth2callback", 
    scope: "https://www.googleapis.com/auth/plus.me" 
}, function (token) { 
    // set auth token for gapi 
    gapi.auth.setToken(token); 

}, function (e) { 
    forge.logging.error("Auth failed: " + e); 
}); 
相關問題