【准备工作】
api库:https://console.developers.google.com/apis/library?
①在google的API库,找到:google+API,【创建项目】
②创建凭据或选择一个已有的OAuth2.0客户端ID
【html部分】
<div class="login-other" >
<img class="btn2" id="customBtn" style="cursor:pointer;" alt="login-Google" title="Google+" src="../image/G+.png">
</div>
【js部分】
$.getScript("https://apis.google.com/js/api:client.js",function (res) {
startApp();
});
var googleUser = {};
var startApp = function () {
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
//726009858027-1fuqkvl234ehdode55mhr90msp9ovuvt.apps.googleusercontent.com
client_id: '726009858027-1fuqkvl234ehdode55mhr90msp9ovuvt.apps.googleusercontent.com', //客户端ID
cookiepolicy: 'single_host_origin',
scope: 'profile' //可以请求除了默认的'profile' and 'email'之外的数据
});
attachSignin(document.getElementById('customBtn'));
});
};
function attachSignin(element) {
auth2.attachClickHandler(element, {},
function (googleUser) {
var profile = auth2.currentUser.get().getBasicProfile();
var userId = profile.getId();
var FullName = profile.getName();
var GivenName = profile.getGivenName();
var FamilyName = profile.getFamilyName();
var Email = profile.getEmail();
var ImageURL = profile.getImageUrl();
var data = {
userId: userId,
Headpic: ImageURL,
FullName: FullName,
GivenName: GivenName,
FamilyName: FamilyName,
Email: Email,
loginTye: 'google+'
};
if (userId > 0) {
$.ajax({
url: "index.php?route=account/login/otherLogin",//后台处理逻辑
data: {
firstname: FamilyName,
lastname: GivenName,
email: Email,
openid: userId,
loginType: data.loginTye
},
type: "post",
dataType: 'json',
success: function (data) {
if (data['redirect']) {
location = data['redirect'];
}
},
error: function (error) {
//console.log(error);
}
});
}
layer.msg('Login successful, page jump...', {icon: 1});
//console.log('Successful login for: ' + JSON.stringify(data));
},
function (error) {
console.log(JSON.stringify(error, undefined, 2));
});
}
//注销
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
alert('用户注销成功');
});
}