1、配置好谷歌应用
2、执行 composer require google/apiclient
/**
* google login
* composer require google/apiclient
*/
public function google()
{
$id_token = $this->request->param('id_token', '', 'trim');
if (!$id_token ) {
$this->ThrowExcption('服务器错误', 400);
}
//client_id需要和客户端一致
$client_id = '应用ID';
//1.根据token获取用户信息
try {
$gg_client = new Client(['client_id' => $client_id]);
$google_user = $gg_client->verifyIdToken($id_token);
} catch (\Exception $e) {
// 有时候使用谷歌库获取用户信息失败,再次使用谷歌api获取用户信息
$google_user = http_get("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=".$id_token);
$google_user = json_decode($google_user,true);
}
/**
* 成功校验后的返回json
* // These six fields are included in all Google ID Tokens.
* "iss": "https://accounts.google.com",
* "sub": "110169484474386276334",
* "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
* "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
* "iat": "1433978353",
* "exp": "1433981953",
* // These seven fields are only included when the user has granted the "profile" and
* // "email" OAuth scopes to the application.
* "email": "testuser@gmail.com",
* "email_verified": "true",
* "name" : "Test User",
* "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
* "given_name": "Test",
* "family_name": "User",
* "locale": "en"
*/
$nickname = $google_user['name'] ?? ''; // 头像
$avatar_url = $google_user['picture'] ?? ''; // 头像
$googleUid = $google_user['sub'] ?? ''; // google_uid
$email = $google_user['email'] ?? '';
if (empty($googleUid)) {
$this->ThrowExcption('获取Google信息失败', 109);
}
//2.拿到用户信息进行用户登录or用户创建流程
}
web登陆
googleInit(){
let _this = this;
(function (d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "https://accounts.google.com/gsi/client";
fjs.parentNode.insertBefore(js, fjs);
js.onload = ()=>{
google.accounts.id.initialize({
client_id: _this.clientId,
callback: _this.googleSignCallBack
});
setTimeout(() => {
google.accounts.id.renderButton(document.getElementById("googleBnt"), {
theme: 'outline',
size: 'large',
click_listener: _this.onClickHandler
})
}, 200);
_this.isGoogleInit = true;
}
})(document, "script", "google-jssdk");
},onClickHandler(e){
},
googleSignCallBack(res){
const id_token = res.credential;
const spread_id = this.$cookies.get('spread_id');
const params = { id_token };
if(spread_id) params.spread_id = spread_id;
this.$api.googleLogin(params).then((res) => {
this.loginSuccess(res.data)
});
},
官方文档 https://developers.google.cn/identity/gsi/web/reference/js-reference?hl=zh-cn