【问题标题】:How to get additional scope information from Google PHP API payload?如何从 Google PHP API 有效负载中获取额外的范围信息?
【发布时间】:2018-08-12 10:00:28
【问题描述】:

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

【问题讨论】:

    标签: php google-api google-api-php-client


    【解决方案1】:

    我设法弄明白了。主要问题是我试图通过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 以获取其他范围信息的问题。

    【讨论】:

    • 帮了大忙。
    【解决方案2】:

    在 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 中记录的所有可用范围的列表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-12
      • 2017-04-14
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多