我得到" webView:didFailLoadWithError -1004:无法连接到服务器"在获取个人资料数据之前接受google plus身份验证时出错。这些代码以前工作正常。现在我正面临这些错误。不知道为什么我无法连接。请帮我摆脱这些错误。我的代码是我在iPhone的Phonegap(3.4.0)中集成google plus。
var googleapi = {
//alert('ready');
authorize: function(options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open the OAuth consent page in the InAppBrowser
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=yes');
$(authWindow).on(' ', function(e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function(data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function(response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
function callGoogle()
{
alert('starting');
googleapi.authorize({
client_id: 'CLIENT_ID',
client_secret: 'CLIENT_SECRET',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function(data) {
accessToken=data.access_token;
alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
getDataProfile();
});
}
function getDataProfile()
{
var term=null;
//accessToken=null;
//alert("getting user data="+accessToken);
$.ajax({
url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken,
type:'GET',
data:term,
dataType:'json',
error:function(jqXHR,text_status,strError){
},
success:function(data)
{
var item;
var dat=data.properties;
alert("first name="+data.given_name+" last name="+data.family_name+" gender="+data.gender+" email="+data.email);
console.log(data);
}
});
}
答案 0 :(得分:1)
您可以使用以下代码获取访问令牌和用户个人资料数据。 只需将您的按钮事件附加到" onGooglePlusLogin" function并替换client_id和screte_id。
我已经在带有phonegap 3.4.0项目的iPhone和Android设备上进行了测试。
干杯!
var GoogleLogin = function (id, secret) {
var clientId = id;
var clientSecret = secret;
var accessToken = {};
var authWindow = null;
var endSignin = {};
var openAuthWindow = function () {
var urlAuth = "https://accounts.google.com/o/oauth2/auth?" + "scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&" + "redirect_uri=http://localhost&" + "response_type=code&" + "client_id=" + clientId;
// Open InAppBrowser to get authorization code
authWindow = window.open(urlAuth, '_blank', 'location=yes,closebuttoncaption=Done');
authWindow.addEventListener('loadstart', parseRedirectUrl);
};
var parseRedirectUrl = function (e) {
var url = e.url;
var thereIsCode = url.indexOf("code=");
var thereIsError = url.indexOf("error=");
if (thereIsCode != -1) {
authWindow.close();
var toMatch = "code=([^&#]*)";
var regex = new RegExp(toMatch);
var result = regex.exec(url);
if (result != null) {
var code = result[1];
exchangeCodeForTokens(code);
}
} else if (thereIsError != -1) {
authWindow.close();
localStorage["accessToken"] = null;
endSignin(-1);
}
};
var exchangeCodeForTokens = function (code) {
var dataQuery = "code=" + code + "&" + "client_id=" + clientId + "&" + "client_secret=" + clientSecret + "&" + "redirect_uri=http://localhost&" + "grant_type=authorization_code";
requestTokens("https://accounts.google.com/o/oauth2/token", dataQuery, callBackTokens);
};
var callBackTokens = function (resp) {
var tokensResp = eval('(' + resp + ')');
if (tokensResp.access_token) {
localStorage["accessToken"] = tokensResp.access_token;
localStorage["refreshToken"] = tokensResp.refresh_token;
localStorage["refreshTime"] = (new Date()).getTime() + 1000 * tokensResp.expires_in;
accessToken = tokensResp.access_token;
endSignin(accessToken);
} else {
accessToken = null;
localStorage["accessToken"] = null;
endSignin(-1);
}
};
var getAccessToken = function (refreshToken) {
var dataQuery = "client_id=" + clientId + "&" + "client_secret=" + clientSecret + "&" + "refresh_token=" + refreshToken + "&" + "grant_type=refresh_token";
requestTokens("https://accounts.google.com/o/oauth2/token", dataQuery, callBackRefreshToken);
};
var callBackRefreshToken = function (resp) {
var tokensResp = eval('(' + resp + ')');
if (tokensResp.access_token) {
localStorage["accessToken"] = tokensResp.access_token;
localStorage["refreshTime"] = (new Date()).getTime() + 1000 * tokensResp.expires_in;
accessToken = tokensResp.access_token;
endSignin(accessToken);
} else {
accessToken = null;
localStorage["accessToken"] = null;
endSignin(-1);
}
};
var requestTokens = function (url, data, callback) {
var xmlreq = new XMLHttpRequest();
xmlreq.onreadystatechange = function () {
if (xmlreq.readyState == 4) {
callback(xmlreq.responseText);
}
};
xmlreq.open("POST", url, true);
xmlreq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlreq.send(data);
};
var isLoggedIn = function (callback) {
endSignin = callback;
accessToken = localStorage["accessToken"];
if (accessToken == "null") {
accessToken = null;
}
if (accessToken !== null && typeof (accessToken) !== 'undefined') {
var refreshTime = localStorage["refreshTime"];
var refreshToken = localStorage["refreshToken"];
var currentTime = (new Date()).getTime();
if (currentTime < refreshTime) {
endSignin(accessToken);
} else {
getAccessToken(refreshToken);
}
} else {
endSignin(-1);
}
};
var startSignin = function (callbackEnd) {
endSignin = callbackEnd;
openAuthWindow();
};
var logOut = function () {
accessToken = null;
localStorage["accessToken"] = null;
localStorage["refreshToken"] = null;
};
return {
startSignin: startSignin,
isLoggedIn: isLoggedIn,
logOut: logOut
};
};
function onGooglePlusLogin() {
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "SECRET_ID";
// Create login object and initialize it with your app client id and secret
var gl = new GoogleLogin(clientId, clientSecret);
gl.startSignin(endLogin);
}
function endLogin(result) {
if (result === -1) {
// Login was not successful :(
alert('Google Login failed!');
} else {
// If successful login, use access_token to get profile name
getProfileData(result);
}
}
function getProfileData(result) {
if (result !== null && typeof (result) !== 'undefined') {
var urlAPI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + result;
var xmlreq = new XMLHttpRequest();
xmlreq.onreadystatechange = function () {
if (xmlreq.readyState == 4 && xmlreq.status == 200) {
var response = eval('(' + xmlreq.responseText + ')');
if (response && response.email && response.id) {
// Profile data
alert(JSON.stringify(response));
} else {
alert("Google Login failed!");
}
}
};
xmlreq.open("GET", urlAPI, true);
xmlreq.send();
}
}
答案 1 :(得分:1)
将此代码添加到一个js文件中并包含在您的项目中。当您想要访问google login api按钮时,单击调用function callGoogle()
将通过此代码完成休息。别忘了添加您的客户端ID和Client_Secret密钥。它对我来说很好。你需要inappbrowser cordova插件。
var googleapi = {
authorize: function(options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open the OAuth consent page in the InAppBrowser
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
//The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
//which sets the authorization code in the browser's title. However, we can't
//access the title of the InAppBrowser.
//
//Instead, we pass a bogus redirect_uri of "http://localhost", which means the
//authorization code will get set in the url. We can access the url in the
//loadstart and loadstop events. So if we bind the loadstart event, we can
//find the authorization code and close the InAppBrowser after the user
//has granted us access to their data.
$(authWindow).on('loadstart', function(e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function(data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function(response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData=null;
function callGoogle()
{
// alert('starting');
googleapi.authorize({
client_id: 'client_id',
client_secret: 'Client_Secret',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function(data) {
accessToken=data.access_token;
// alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
console.log(JSON.stringify(data));
getDataProfile();
});
}
// This function gets data of user.
function getDataProfile()
{
var term=null;
// alert("getting user data="+accessToken);
$.ajax({
url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken,
type:'GET',
data:term,
dataType:'json',
error:function(jqXHR,text_status,strError){
},
success:function(data)
{
var item;
console.log(JSON.stringify(data));
// Save the userprofile data in your localStorage.
localStorage.gmailLogin="true";
localStorage.gmailID=data.id;
localStorage.gmailEmail=data.email;
localStorage.gmailFirstName=data.given_name;
localStorage.gmailLastName=data.family_name;
localStorage.gmailProfilePicture=data.picture;
localStorage.gmailGender=data.gender;
}
});
disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='+accessToken;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
accessToken=null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----"+accessToken);
},
error: function(e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
}
});
}