如何从 Google PHP API payload 获取额外的作用域信息?

How to get additional scope information from Google PHP API payload?

我正在努力从 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);

        }
    );
});

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

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变量returns:

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"

在 Google 开发人员 API 控制台搜索 Google 人 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

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

我设法弄明白了。主要问题是我试图通过 id_token 访问数据,但我需要做的是使用 access_token 并通过其他 Google 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 来获取额外范围信息的问题。