2015-07-20 67 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); 
}); 
相关问题