我正在尝试在我们的网站上执行google登录。我已经阅读了文档并在apis控制台上设置了一个应用程序。
我更喜欢注册对话框显示在弹出窗口中,并且在用户登录并接受我将获得javascript回调的权限之后。这个api也支持根据文档。所以我在文档的帮助下构建了以下内容; - )
第一部分是使用正确的clientid和apikey加载google客户端脚本async和init脚本。
$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的部分。加载client.js时调用handleClientLoad()。该方法检查使用是否经过身份验证。如果用户是,我的想法是我想登录用户。 如果用户尚未经过身份验证,则会有一个按钮,当单击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();
};
现在解决问题:
答案 0 :(得分:1)
您的代码中存在两个问题:
在authorize()
中,未正确调用handleAuthResult
方法,请删除函数名末尾的括号。您不想执行该函数,只需传递其引用即可。以下是authorize
方法的含义:
gapi.auth.authorize({ client_id: this.clientId, scope: this.scopes, immediate: immediate }, this.handleAuthResult);
请注意括号中的差异。