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登陆

后端授权方式

 static function getGoogleLoginData($code = '')
 {
     $googleConfig = config('app.google');
     // init configuration
     $clientID = $googleConfig['web_client_id'] ?? '';
     $clientSecret = $googleConfig['web_client_secret'] ?? '';
     $redirectUri = ''; // 'https://' . $_SERVER['HTTP_HOST']

     // create Client Request to access Google API
     $client = new Google_Client();
     $client->setClientId($clientID);
     $client->setClientSecret($clientSecret);
     $client->setRedirectUri($redirectUri);
     $client->addScope("email");
     $client->addScope("profile");

     // authenticate code from Google OAuth Flow
     if (!empty($code)) {
         $token = $client->fetchAccessTokenWithAuthCode($code);
         $client->setAccessToken($token['access_token']);
         // get profile info
         $google_oauth = new Google_Service_Oauth2($client);
         $google_account_info = $google_oauth->userinfo->get();
         return [
             'id' => $google_account_info->id,
             'email' => $google_account_info->email,
             'name' => $google_account_info->name,
             'picture' => $google_account_info->picture,
         ];
     } else {
         return $client->createAuthUrl();
     }
 }



// 调用
$code = input('code', '', 'strip_tags');
$googleLoginData = StoreLoginLogic::getGoogleLoginData($code);
if (empty($code)) {
	header("Location: $googleLoginData");
	exit();
}
后端调用api方式-不推荐
 $code = input('code', '', 'strip_tags');

$googleConfig = config('app.google');
$clientID = $googleConfig['web_client_id'] ?? '';
$redirect_uri = ''; // 'https://' . $_SERVER['HTTP_HOST']

if (empty($code)) {
	$authUrl = 'https://accounts.google.com/o/oauth2/auth';
	$scope = 'email profile';
	$response_type = 'code';
	$authUrl .= '?' . http_build_query([
	       'client_id' => $clientID,
	       'redirect_uri' => $redirect_uri,
	       'scope' => $scope,
	       'response_type' => $response_type,
	   ]);
	header("Location: $authUrl ");
	exit();
}


 $data = [
    'code' => $code,
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri' => $redirect_uri,
    'grant_type' => 'authorization_code',
];

$tokenUrl = 'https://www.googleapis.com/oauth2/v4/token';
$options = [
    'http' => [
        'header' => "Content-type: application/x-www-form-urlencoded",
        'method' => 'POST',
        'content' => http_build_query($data),
    ],
];
$context = stream_context_create($options);
$response = file_get_contents($tokenUrl, false, $context);
// $response = CurlUtil::postForm($tokenUrl, $data);
$token = json_decode($response, true);
$access_token = $token['access_token'] ?? '';
if (empty($access_token)) {
    return redirect("/?v=1");
}
$userInfoUrl = 'https://www.googleapis.com/oauth2/v2/userinfo';
  $options = [
            'http' => [
                'header' => "Authorization: Bearer $access_token",
            ],
        ];
$context = stream_context_create($options);
$response = file_get_contents($userInfoUrl, false, $context);    
// $response = CurlUtil::get($userInfoUrl, ["Authorization: Bearer $access_token"]);
$userInfo = json_decode($response, true);
$googleId = $userInfo['id'] ?? '';
if (empty($googleId)) {
    return redirect("/?v=2");
}
$params = [
    'email' => $userInfo['email'],
    'name' => $userInfo['name'],
];

JavaScrip 方式
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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐