ChatGPT解决这个技术问题 Extra ChatGPT

Get user info via Google API

Is it possible to get information from user's profile via Google API? If it is possible, which API should I use?

I'm interesting in such information:

Url to the user profile (e.g. https://profiles.google.com/115063121183536852887);

Gender (sex);

Profile photo.

Also it would be cool to get other information from user's profile.


A
Abhinav Manchanda

Add this to the scope - https://www.googleapis.com/auth/userinfo.profile

And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json

It has loads of stuff - including name, public profile url, gender, photo etc.


I used the above Urls but unable to get user's profile. Getting '{' only. Plz can u post some code or links. Thanks in advance.
The url you provided works perfectly, i.e googleapis.com/oauth2/v1/userinfo . But can you tell where from did you get this url. I tried searching for it but didn't find it anywhere. Does Google document these urls at some place?
Where can I see specification of data returned for specific scope ?
Scope "userinfo.profile" seems to be deprecated, instead you should use "profile" and "email". developers.google.com/+/web/api/rest/oauth#authorization-scopes
You can just query this url, using the access token you get after user has authorized you to access this scope. Example: curl -X GET "https://www.googleapis.com/oauth2/v1/userinfo?alt=json" -H"Authorization: Bearer accessTokenHere"
C
Community

scope - https://www.googleapis.com/auth/userinfo.profile

return youraccess_token = access_token

get https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token

you will get json:

{
 "id": "xx",
 "name": "xx",
 "given_name": "xx",
 "family_name": "xx",
 "link": "xx",
 "picture": "xx",
 "gender": "xx",
 "locale": "xx"
}

To Tahir Yasin:

This is a php example. You can use json_decode function to get userInfo array.

$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];

how to can I use their response?
How can i get the email address along with the other information that you have mentioned ?
Please, update the code to have correct format to access $userInfoArray properties. It should be like $userInfoArray['email'] to get the email address from the $userInfoArray. NOTE THE SINGLE QUOTATION TO ACCESS RPOPERTIES.
@Shantha Kumara you could have edited it yourself, but don't worry as I have done it now. For all we know they could have omitted the code define(email, 'email') ;)
i want to get phone number and age/birthday
u
user872858

This scope https://www.googleapis.com/auth/userinfo.profile has been deprecated now. Please look at https://developers.google.com/+/api/auth-migration#timetable.

New scope you will be using to get profile info is: profile or https://www.googleapis.com/auth/plus.login

and the endpoint is - https://www.googleapis.com/plus/v1/people/{userId} - userId can be just 'me' for currently logged in user.


This one is important peace of information towards having integration future proof. more information about deprecated scopes developers.google.com/+/web/api/rest/oauth
and yet ... If you are directly requesting the “plus.me” scope, any other Google+ OAuth scopes, or making any Google+ API calls, please ensure that you remove these requests from your project before March 7, 2019. -- Google
Z
Zooly

I'm using PHP and solved this by using version 1.1.4 of google-api-php-client

Assuming the following code is used to redirect a user to the Google authentication page:

 $client = new Google_Client();
 $client->setAuthConfigFile('/path/to/config/file/here');
 $client->setRedirectUri('https://redirect/url/here');
 $client->setAccessType('offline'); //optional
 $client->setScopes(['profile']); //or email
 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
 exit();

Assuming a valid authentication code is returned to the redirect_url, the following will generate a token from the authentication code as well as provide basic profile information:

 //assuming a successful authentication code is return
 $authentication_code = 'code-returned-by-google';
 $client = new Google_Client();
 //.... configure $client object code goes here
 $client->authenticate($authentication_code);
 $token_data = $client->getAccessToken();

 //get user email address
 $google_oauth =new Google_Service_Oauth2($client);
 $google_account_email = $google_oauth->userinfo->get()->email;
 //$google_oauth->userinfo->get()->familyName;
 //$google_oauth->userinfo->get()->givenName;
 //$google_oauth->userinfo->get()->name;
 //$google_oauth->userinfo->get()->gender;
 //$google_oauth->userinfo->get()->picture; //profile picture

However, location is not returned. New YouTube accounts don't have YouTube specific usernames


how to get Location?
i can't get gender info (i have kept gender info public) using this scope. i have tried oauth playground developers.google.com/oauthplayground for this. i want to do this using REST API on server side. can you help me on this?
Can't get gender neither. And on some account, nothing except email are returned. Ideas ?
G
Glen Thompson

This is poorly document / there have been changes. I would reference this https://developers.google.com/oauthplayground for up to date endpoints.

As of 2021 the correct endpoint for userinfo is

https://www.googleapis.com/oauth2/v1/userinfo

So once you get the access_token you can do

curl -X GET "https://www.googleapis.com/oauth2/v1/userinfo" \
   -H "Authorization: Bearer <access_token>"

Important: To get all the information you need scope of openid email profile.

{
 'sub': '<unique_id>',
 'name': '<full>',
 'given_name': '<first>',
 'family_name': '<last>',
 'picture': '<pic>',
 'email': '<email>',
 'email_verified': True,
 'locale': 'en'
}

I was struggling to find the email field specifically, and this answer solved my problem! I can verify this works. Thank you!
super helpful and correct 2021 answer--in my case the 'sub' field was id and 'email_verified' was verified_email, using a GET with Bearer token of v2 and v1 urls googleapis.com/oauth2/v2/userinfo however v3 url shows the sub and email_verified fields, try with GET+Bearer for googleapis.com/oauth2/v3/userinfo
Ah interesting wasn't paying too much attention to the version but sounds like there is some differences in response between them.
@GlenThompson We need age and gender as well, how we get it from gmail?
C
Community

I am using Google API for .Net, but no doubt you can find the same way to obtain this information using other version of API. As user872858 mentioned, scope userinfo.profile has been deprecated (google article) .

To obtain user profile info I use following code (re-written part from google's example):

IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                                  new GoogleAuthorizationCodeFlow.Initializer
                                      {
                                            ClientSecrets = Secrets,
                                            Scopes = new[] { PlusService.Scope.PlusLogin,"https://www.googleapis.com/auth/plus.profile.emails.read"  }
                                       });    
TokenResponse _token = flow.ExchangeCodeForTokenAsync("", code, "postmessage", 
                              CancellationToken.None).Result;

                    // Create an authorization state from the returned token.
                    context.Session["authState"] = _token;

                    // Get tokeninfo for the access token if you want to verify.
                    Oauth2Service service = new Oauth2Service(
                     new Google.Apis.Services.BaseClientService.Initializer());
                    Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
                    request.AccessToken = _token.AccessToken;
                    Tokeninfo info = request.Execute();
                    if (info.VerifiedEmail.HasValue && info.VerifiedEmail.Value)
                    {
                        flow = new GoogleAuthorizationCodeFlow(
                                    new GoogleAuthorizationCodeFlow.Initializer
                                         {
                                             ClientSecrets = Secrets,
                                             Scopes = new[] { PlusService.Scope.PlusLogin }
                                          });

                        UserCredential credential = new UserCredential(flow, 
                                                              "me", _token);
                        _token = credential.Token;
                        _ps = new PlusService(
                              new Google.Apis.Services.BaseClientService.Initializer()
                               {
                                   ApplicationName = "Your app name",
                                   HttpClientInitializer = credential
                               });
                        Person userProfile = _ps.People.Get("me").Execute();
                    }

Than, you can access almost anything using userProfile.

UPDATE: To get this code working you have to use appropriate scopes on google sign in button. For example my button:

     <button class="g-signin"
             data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read"
             data-clientid="646361778467-nb2uipj05c4adlk0vo66k96bv8inqles.apps.googleusercontent.com"
             data-accesstype="offline"
             data-redirecturi="postmessage"
             data-theme="dark"
             data-callback="onSignInCallback"
             data-cookiepolicy="single_host_origin"
             data-width="iconOnly">
     </button>

M
Mehmet Kaplan

There are 3 steps that needs to be run.

Register your app's client id from Google API console Ask your end user to give consent using this api https://developers.google.com/identity/protocols/OpenIDConnect#sendauthrequest Use google's oauth2 api as described at https://any-api.com/googleapis_com/oauth2/docs/userinfo/oauth2_userinfo_v2_me_get using the token obtained in step 2. (Though still I could not find how to fill "fields" parameter properly).

It is very interesting that this simplest usage is not clearly described anywhere. And i believe there is a danger, you should pay attention to the verified_emailparameter coming in the response. Because if I am not wrong it may yield fake emails to register your application. (This is just my interpretation, has a fair chance that I may be wrong!)

I find facebook's OAuth mechanics much much clearly described.


A
Alexander Farber

If you only want to fetch the Google user id, name and picture for a visitor of your web app - here is my pure PHP service side solution for the year 2020 with no external libraries used -

If you read the Using OAuth 2.0 for Web Server Applications guide by Google (and beware, Google likes to change links to its own documentation), then you have to perform only 2 steps:

Present the visitor a web page asking for the consent to share her name with your web app Then take the "code" passed by the above web page to your web app and fetch a token (actually 2) from Google.

One of the returned tokens is called "id_token" and contains the user id, name and photo of the visitor.

Here is the PHP code of a web game by me. Initially I was using Javascript SDK, but then I have noticed that fake user data could be passed to my web game, when using client side SDK only (especially the user id, which is important for my game), so I have switched to using PHP on the server side:

<?php

const APP_ID       = '1234567890-abcdefghijklmnop.apps.googleusercontent.com';
const APP_SECRET   = 'abcdefghijklmnopq';

const REDIRECT_URI = 'https://the/url/of/this/PHP/script/';
const LOCATION     = 'Location: https://accounts.google.com/o/oauth2/v2/auth?';
const TOKEN_URL    = 'https://oauth2.googleapis.com/token';
const ERROR        = 'error';
const CODE         = 'code';
const STATE        = 'state';
const ID_TOKEN     = 'id_token';

# use a "random" string based on the current date as protection against CSRF
$CSRF_PROTECTION   = md5(date('m.d.y'));

if (isset($_REQUEST[ERROR]) && $_REQUEST[ERROR]) {
    exit($_REQUEST[ERROR]);
}

if (isset($_REQUEST[CODE]) && $_REQUEST[CODE] && $CSRF_PROTECTION == $_REQUEST[STATE]) {
    $tokenRequest = [
        'code'          => $_REQUEST[CODE],
        'client_id'     => APP_ID,
        'client_secret' => APP_SECRET,
        'redirect_uri'  => REDIRECT_URI,
        'grant_type'    => 'authorization_code',
    ];

    $postContext = stream_context_create([
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($tokenRequest)
        ]
    ]);

    # Step #2: send POST request to token URL and decode the returned JWT id_token
    $tokenResult = json_decode(file_get_contents(TOKEN_URL, false, $postContext), true);
    error_log(print_r($tokenResult, true));
    $id_token    = $tokenResult[ID_TOKEN];
    # Beware - the following code does not verify the JWT signature! 
    $userResult  = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', $id_token)[1]))), true);

    $user_id     = $userResult['sub'];
    $given_name  = $userResult['given_name'];
    $family_name = $userResult['family_name'];
    $photo       = $userResult['picture'];

    if ($user_id != NULL && $given_name != NULL) {
        # print your web app or game here, based on $user_id etc.
        exit();
    }
}

$userConsent = [
    'client_id'     => APP_ID,
    'redirect_uri'  => REDIRECT_URI,
    'response_type' => 'code',
    'scope'         => 'profile',
    'state'         => $CSRF_PROTECTION,
];

# Step #1: redirect user to a the Google page asking for user consent
header(LOCATION . http_build_query($userConsent));

?>

You could use a PHP library to add additional security by verifying the JWT signature. For my purposes it was unnecessary, because I trust that Google will not betray my little web game by sending fake visitor data.

Also, if you want to get more personal data of the visitor, then you need a third step:

const USER_INFO    = 'https://www.googleapis.com/oauth2/v3/userinfo?access_token=';
const ACCESS_TOKEN = 'access_token'; 

# Step #3: send GET request to user info URL
$access_token = $tokenResult[ACCESS_TOKEN];
$userResult = json_decode(file_get_contents(USER_INFO . $access_token), true);

Or you could get more permissions on behalf of the user - see the long list at the OAuth 2.0 Scopes for Google APIs doc.

Finally, the APP_ID and APP_SECRET constants used in my code - you get it from the Google API console:

https://i.stack.imgur.com/g4i2q.png


a
alalonde

If you're in a client-side web environment, the new auth2 javascript API contains a much-needed getBasicProfile() function, which returns the user's name, email, and image URL.

https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile


But what is the actual API URL? I looked at the documentation, I can't find the actual API URL. Google seem to be pushing us to their SDK, but not everyone wants to use the SDK.
L
Logan Lee

if you use Oath2 then client will give id_token

then you can validate it on server with this url

https://oauth2.googleapis.com/tokeninfo?id_token=your_id_token

will solve problem like lucky charm


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now