Get Userinfo from Google OAuth 2.0 PHP API

前端 未结 3 1986
天涯浪人
天涯浪人 2020-12-09 08:56

I am trying to use Google Oauth API to get userinfo. It works perfectly for Google Plus API but I am trying to create a backup in case the user doesn\'t have google plus acc

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 09:53

    The Google API PHP client library has changed - here is how you fetch user information:

    setApplicationName(TITLE);
    $client->setClientId('REPLACE_ME.apps.googleusercontent.com');
    $client->setClientSecret('REPLACE_ME');
    $client->setRedirectUri(REDIRECT);
    $client->setScopes(array(Google_Service_Plus::PLUS_ME));
    $plus = new Google_Service_Plus($client);
    
    if (isset($_REQUEST['logout'])) {
            unset($_SESSION['access_token']);
    }
    
    if (isset($_GET['code'])) {
            if (strval($_SESSION['state']) !== strval($_GET['state'])) {
                    error_log('The session state did not match.');
                    exit(1);
            }
    
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
            header('Location: ' . REDIRECT);
    }
    
    if (isset($_SESSION['access_token'])) {
            $client->setAccessToken($_SESSION['access_token']);
    }
    
    if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
            try {
                    $me = $plus->people->get('me');
                    $body = '
    ' . print_r($me, TRUE) . '
    '; } catch (Google_Exception $e) { error_log($e); $body = htmlspecialchars($e->getMessage()); } # the access token may have been updated lazily $_SESSION['access_token'] = $client->getAccessToken(); } else { $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $body = sprintf('

    Login

    ', $client->createAuthUrl()); } ?> <?= TITLE ?>

    Logout

    Do not forget to -

    1. Get web client id and secret at Google API console
    2. Authorize the https://example.com/myapp/ at the same place

    You can find official examples at Youtube GitHub.

    UPDATE 2017:

    You can add the fields to be retrieved with:

    const FIELDS       = 'id,name,image';
    $me = $plus->people->get('me', array('fields' => FIELDS));
    

提交回复
热议问题