Google API를 통해 사용자 정보 얻기
Google API를 통해 사용자 프로필에서 정보를 얻을 수 있습니까? 가능하다면 어떤 API를 사용해야합니까?
나는 다음 정보에 흥미가 있습니다.
- 사용자 프로필 URL (예 : https://profiles.google.com/115063121183536852887 )
- 성별 (성별)
- 프로필 사진.
또한 사용자의 프로필에서 다른 정보를 얻는 것도 좋습니다.
이것을 범위에 추가하십시오-https: //www.googleapis.com/auth/userinfo.profile
승인이 완료되면 https://www.googleapis.com/oauth2/v1/userinfo?alt=json 에서 정보를 가져옵니다.
이름, 공개 프로필 URL, 성별, 사진 등 많은 항목이 있습니다.
범위-https: //www.googleapis.com/auth/userinfo.profile
return youraccess_token = access_token
https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token 받기
json을 얻을 수 있습니다.
{
"id": "xx",
"name": "xx",
"given_name": "xx",
"family_name": "xx",
"link": "xx",
"picture": "xx",
"gender": "xx",
"locale": "xx"
}
Tahir Yasin에게 :
이것은 PHP 예제입니다.
json_decode 함수를 사용하여 userInfo 배열을 가져올 수 있습니다.
$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'];
이 범위 https://www.googleapis.com/auth/userinfo.profile 은 이제 더 이상 사용되지 않습니다. https://developers.google.com/+/api/auth-migration#timetable 을 참조하십시오 .
프로필 정보를 가져 오는 데 사용할 새 범위는 프로필 또는 https://www.googleapis.com/auth/plus.login입니다.
및 엔드 포인트입니다 - https://www.googleapis.com/plus/v1/people/가 {userId를가} - 현재 로그인 한 사용자에 대한 userId를 그냥 '나'가 될 수 있습니다.
내가 사용하고 PHP
그리고 버전 1.1.4을 사용하여이 문제를 해결 구글-API-PHP 클라이언트
사용자를 Google 인증 페이지로 리디렉션하는 데 다음 코드가 사용된다고 가정합니다.
$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();
유효한 인증 코드가에 반환되었다고 가정하면 redirect_url
다음은 인증 코드에서 토큰을 생성하고 기본 프로필 정보를 제공합니다.
//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
그러나 위치는 반환되지 않습니다. 새 YouTube 계정에는 YouTube 전용 사용자 이름이 없습니다.
.Net 용 Google API를 사용하고 있지만 다른 버전의 API를 사용하여이 정보를 얻는 동일한 방법을 찾을 수 있습니다. 으로 user872858가 언급 범위 userinfo.profile는 (사용되지 기사를 구글 ).
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>
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
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_email
parameter 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.
참고URL : https://stackoverflow.com/questions/7130648/get-user-info-via-google-api
'development' 카테고리의 다른 글
반응 렌더링 기능에서 동적 href를 만드는 방법은 무엇입니까? (0) | 2020.09.04 |
---|---|
조건부 변수 대 세마포 (0) | 2020.09.04 |
if 문-단락 평가 대 가독성 (0) | 2020.09.04 |
부트 스트랩에는 여전히 외부 지원이 필요합니다. (0) | 2020.09.03 |
ACTION_SEND를 통해 Android 앱에서 Facebook에 텍스트 공유 (0) | 2020.09.03 |