代码之家  ›  专栏  ›  技术社区  ›  Swen

如何从Google PHP API负载中获取其他范围信息?

  •  10
  • Swen  · 技术社区  · 7 年前

    我正在努力从Google PHP API获取更多范围信息。我将其与JavaScript结合使用以获取访问令牌(不确定这是否是正确的方法,但它对我有效)

    我的页面上有一个Google注册按钮,它连接到以下功能。基本上,它会获得一个响应令牌,通过AJAX发送到我的PHP服务器。

    gapi.load('auth2', function() {
        // Retrieve the singleton for the GoogleAuth library and set up the client.
        auth2 = gapi.auth2.init({
            client_id: 'XXXX',
            cookie_policy: 'single_host_origin',
            // Requesting additional scopes
            scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.login'
        });
    
        auth2.attachClickHandler(document.getElementById('google-login-signup'), {},
            function(googleUser) {
    
                if ( auth2.isSignedIn.get() ) {
    
                    var data = {
                        'action': 'social_google_login',
                        '_nonce': $('#google-login-signup').attr('data-nonce'),
                        'redirect_to': $('#google-login-signup').attr('data-redirect-to'),
                        'token': googleUser.getAuthResponse().id_token
                    }
    
                    $.ajax({
                        url: ajax_url,
                        type: 'POST',
                        data: data,
                        success: function(response) {
                            console.log(response);
    
                            if ( response.success === true ) {
                                window.location.href = response.data.redirect;                  
                            }
                        }
                    });
    
                }
    
            }, function(error) {
    
                console.log(error);
    
            }
        );
    });
    

    然后在我的服务器上,通过以下函数检索和提供令牌,该函数检查令牌是否有效并返回信息:

    public function connect() {
        $client = new Google_Client();
    
        $credentials = json_decode('XXXX', true);       
        $client->setAuthConfig($credentials);       
    
        $payload = $client->verifyIdToken($_POST['token']);
    
        if ( !$payload ) {
            return new WP_Error('invalid_payload', 'The payload was invalid.');         
        }
    
        return $payload;        
    }
    

    这一切都很好,只是它没有包含我在JavaScript函数中请求的其他作用域的信息。 我怎样才能获得这些额外的范围信息,如生日和性别?

    仅供参考,这是 $payload 可变回报:

    at_hash: "XXXX"
    aud: "XXXX.apps.googleusercontent.com"
    azp: "XXXX.apps.googleusercontent.com"
    email: "XXXX@gmail.com"
    email_verified: true
    exp: 1520189629
    family_name: "XXXX"
    given_name: "XXXX"
    iat: XXXX
    iss: "accounts.google.com"
    jti: "XXXX"
    locale: "en"
    name: "XXXX XXXX"
    picture: "XXXX"
    sub: "XXXX"
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Swen    7 年前

    我设法弄明白了。主要问题是我试图通过 id_token ,但我需要做的是使用 access_token 并通过其他谷歌API传递。

    如果有人偶然发现了这一点,下面是我的新代码和改进的代码,它还修复了一些与此问题无关的问题。

    JavaScript

    $('#google-login-signup').on('click', function(e) {
        e.preventDefault();
    
        gapi.load('auth2', function() {
    
            var scopes = [
                'https://www.googleapis.com/auth/userinfo.email',
                'https://www.googleapis.com/auth/userinfo.profile',
                'https://www.googleapis.com/auth/plus.login'
            ];
    
            // Use gapi.auth2.authorize instead of gapi.auth2.init.
            // This is because I only need the data from Google once.
            gapi.auth2.authorize({
                'client_id': 'XXXX.apps.googleusercontent.com',
                'cookie_policy': 'single_host_origin',
                'fetch_basic_profile': false,
                'ux_mode': 'popup',
                'scope': scopes.join(' '),
                'prompt': 'select_account'
            },
            function(googleResponse) {
    
                if ( googleResponse.error ) {
                    return;
                }
    
                var data = {
                    'action': 'social_google_login',
                    '_nonce': $('#google-login-signup').attr('data-nonce'),
                    'redirect_to': $('#google-login-signup').attr('data-redirect-to'),
    
                    // Instead of id_token, send the access_token.
                    // This is needed for accessing the scope info from other APIs.
                    'access_token': googleResponse.access_token
                }
    
                $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        if ( response.success === true ) {
                            window.location.href = response.data.redirect;                              
                        }
                    }
                });         
            });             
        });
    });
    

    PHP

    public function connect() {
        $client = new Google_Client();
    
        $credentials = json_decode('XXXX', true);
    
        $client->setAuthConfig($credentials);
    
        // Set Access Token
        $client->setAccessToken($_POST['access_token']);
    
        // Connect to Oauth2 API after providing access_token to client
        $oauth2 = new Google_Service_Oauth2($client);
    
        if ( !$oauth2 ) {
            return new WP_Error('invalid_access_token', 'The access_token was invalid.');   
        }
    
        // Contains basic user info
        $google_user = $this->get_user($oauth2->userinfo->get());
    
        // To get the plus.login scope we need to setup a Google_Service_Plus
        $google_plus_service = new Google_Service_Plus($client);
    
        // Contains Google+ profile info
        $profile = $google_plus_service->people->get('me');
    
    }
    

    就是这样!这基本上是一个不知道我需要访问另一个 Google_Service 获取其他范围信息。

        2
  •  1
  •   user3565145 user3565145    7 年前

    在Google Developers API控制台中搜索Google People API,启用它并使用以下范围:

    https://www.googleapis.com/auth/contacts                |   Manage your contacts
    https://www.googleapis.com/auth/contacts.readonly       |   View your contacts
    https://www.googleapis.com/auth/plus.login              |   Know the list of people in your circles, your age range, and language
    https://www.googleapis.com/auth/user.addresses.read     |   View your street addresses
    https://www.googleapis.com/auth/user.birthday.read      |   View your complete date of birth
    https://www.googleapis.com/auth/user.emails.read        |   View your email addresses
    https://www.googleapis.com/auth/user.phonenumbers.read  |   View your phone numbers
    https://www.googleapis.com/auth/userinfo.email          |   View your email address
    https://www.googleapis.com/auth/userinfo.profile        |   View your basic profile info
    

    中记录的所有可用范围的列表 here