7

我正在尝试在我们的网站上执行Google登录。我已经阅读了文档并在apis控制台上设置了一个应用程序。Google身份验证javascript

我更喜欢在弹出窗口中显示注册对话框,并在用户登录后接受我将获得JavaScript回调的权限。这个API也支持根据文档。因此,我在文档的帮助下构建了以下内容;-)

第一部分是加载google客户端脚本异步和init脚本以及正确的clientid和apikey。

$gp = new googlePlus('@Trustpilot.Web.Social.Google.ClientID', '@Trustpilot.Web.Social.Google.ApiKey'); 
(function() { 
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; 
    po.src = 'https://apis.google.com/js/client.js?onload=googlePlusClientLoad'; 
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); 
})(); 

下一部分它使用了谷歌的客户端API的一部分。 handleClientLoad()在加载client.js时调用。该方法检查使用是否通过身份验证。如果用户是,我的想法是我想登录用户。 如果用户还没有被认证,将会有一个按钮,当点击handleAuthClick()被调用时,它的基本功能与handleClientLoad()相同,但会弹出一个用户最多登录(使用谷歌帐户)和接受权限。登录后,handleAuthResult()被称为登录用户。

function googlePlus(clientId, apiKey) { 
    this.clientId = clientId; 
    this.apiKey = apiKey; 
    this.scopes = 'https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email'; 

    /// This method is called when the javascript is loaded async 
    this.handleClientLoad = function() { 
     gapi.client.setApiKey(this.apiKey); 
     window.setTimeout(this.authorize(true), 1); 
    }; 

this.handleAuthResult = function (authResult) { 
    console.log(authResult); 
    if (authResult && !authResult.error) { 
     var token = gapi.auth.getToken(); 
     console.log(token); 
    } 
    else if (authResult && authResult.error) { 
     alert(authResult.error); 
    } 
}; 

this.handleAuthClick = function(event) { 
    this.authorize(false); 
    return false; 
}; 

this.makeApiCall = function() { 
    gapi.client.load('plus', 'v1', function() { 
     var request = gapi.client.plus.people.get({ 
      'userId': 'me' 
     }); 
     request.execute(function (resp) { 
      console.log(resp); 
     }); 
    }); 
}; 

    this.authorize = function (immediate) { 
     gapi.auth.authorize({ client_id: this.clientId, scope: this.scopes, immediate: immediate }, this.handleAuthResult()); 
     //gapi.auth.authorize({ client_id: this.clientId, scope: this.scopes, immediate: immediate }, this.handleAuthResult()); 
    }; 
} 
var googlePlusClientLoad = function() { 
    $gp.handleClientLoad(); 
}; 

所以,现在的问题:

  1. 当handleClientLoad被称为如果用户已经拥有autehnticated用户从未认证甚至 。
  2. 如果用户使用handleAuthClick()弹出显示并登录,则将权限和回调函数handleAuthResult()工作。但参数authResult是 总是没有任何东西(应该是赞美文档的东西)。
  3. 如果我尝试多次不重新加载页面,我有时可以通过 获取makeApiCall()和gapi.auth.getToken()以获得我需要的信息。
+0

我有使用JavaScript API相同的问题。如果你已经解决了问题,请分享你的答案。 – xrnd

回答

1

有在你的代码的两个问题:

  • 不是必需的API密钥,您可以将其删除。通过OAuth2获得用户令牌就足够了。
  • authorize()中,handleAuthResult方法未正确调用,请在函数名称末尾删除括号。您不想执行该功能,只需传递其参考。这里的authorize方法必须是什么样子:

    gapi.auth.authorize({ client_id: this.clientId, scope: this.scopes, immediate: immediate }, this.handleAuthResult);

注意括号中的差异。