Get user birthday with Google API

10,313

See here: How to specify the scope of Google API to get the birthday. In summary: you must request an access token with a particular scope, e.g. https://www.googleapis.com/auth/plus.login and the user must have set his/her birthday information to public.

Share:
10,313
richard
Author by

richard

Updated on June 04, 2022

Comments

  • richard
    richard almost 2 years

    I am using the Google API to help users login to my website. I can extract their name, locale, profile picture, gender and ID during the login with the API but I can't get their birthday.

    How would I go about getting their birthday with the API?

    The code:

    session_start();
    $google_client_id       = 'xx';
    $google_client_secret   = 'xx';
    $google_redirect_url    = 'xx'; 
    $google_developer_key   = 'xx';
    
    require_once 'Google_Client.php';
    require_once 'contrib/Google_Oauth2Service.php';
    
    $gClient = new Google_Client();
    $gClient->setApplicationName('xx');
    $gClient->setClientId($google_client_id);
    $gClient->setClientSecret($google_client_secret);
    $gClient->setRedirectUri($google_redirect_url);
    $gClient->setDeveloperKey($google_developer_key);
    $gClient->setScopes(array('email', 'https://www.googleapis.com/auth/plus.login'));
    $google_oauthV2 = new Google_Oauth2Service($gClient);
    if (isset($_GET['code'])) 
    { 
        $gClient->authenticate($_GET['code']);
        $_SESSION['token'] = $gClient->getAccessToken();
    }
    
    if (isset($_SESSION['token'])) 
    { 
        $gClient->setAccessToken($_SESSION['token']);
    }
    if ($gClient->getAccessToken()) 
    {   
          $user                          = $google_oauthV2->userinfo->get();
          $user_google_id                = $user['id'];
          $user_name                     = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
          $user_first_name           = filter_var($user['given_name'], FILTER_SANITIZE_SPECIAL_CHARS);
          $user_last_name                = filter_var($user['family_name'], FILTER_SANITIZE_SPECIAL_CHARS);
          $user_gender               = filter_var($user['gender'], FILTER_SANITIZE_SPECIAL_CHARS);
          $user_country                  = filter_var($user['locale'], FILTER_SANITIZE_SPECIAL_CHARS);
          $user_age                  = filter_var($user['birthday'], FILTER_SANITIZE_SPECIAL_CHARS);
          $user_email                    = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
          $profile_url               = filter_var($user['link'], FILTER_VALIDATE_URL);
          $profile_image_url             = filter_var($user['picture'], FILTER_VALIDATE_URL);
          $user_image                    = "$profile_image_url?sz=150";
          $_SESSION['token']             = $gClient->getAccessToken();  
    }