Domanda

I'm kind of building a website and I want to allow Google login. I don't want my customers upload their profile pictures again to my website. I have some clue on how to do it with facebook, but how do I fetch a profile picture from a google plus account once the user has been authenticated via a Google account? Is there any API for this? If yes, kindly share.

È stato utile?

Soluzione 6

There is an API provided by https://www.avatarapi.com/ which returns the user's name and profile pic based on Google's public info.

Here's the latest docs; https://docs.avatarapi.com/

One of the benefits of this API is that it does not require the user to be authenticated with Google. However, in your particular case this would not be an issue.

Altri suggerimenti

We can easily get it with plus client When plus client is connected i.e

if(plusClient.isConnected){

            plusClient.getCurrentPerson().getImage().getUrl();

}

It will provide you the url of the image.

You can get the Google profile image URL by using given tricks:

Old Trick

https://plus.google.com/s2/photos/profile/(user_id)?sz=150

But this is not working now because Google had changed their policy so new trick for doing this is given below

New Trick

Request URL

https://www.googleapis.com/plus/v1/people/115950284...320?fields=image&key={YOUR_API_KEY}

That will give the Google profile image url in json format as given below

Response :

{
    "image": 
    {
         "url": "https://lh3.googleusercontent.com/-OkM...AANA/ltpH4BFZ2as/photo.jpg?sz=50"
    }
}


For more detail you can also check this How to get user image through user id in Google plus?

Happy Coding!!

See https://developers.google.com/+/api/latest/people/get for details, but generally you'll need to do the following steps:

  1. Using OAuth2, authenticate them with the plus.login scope.
  2. Once they're logged in, you can use the people.get method with the userId value of "me". This gives their complete profile
  3. Their photo will be in the image.url field

+1 to what @Prisoner said, you should be authenticating the user with plus.login and then retrieve the user with the special string me.

A full example of getting the Photo URL and Cover Photo URL.

<html>
  <head>
  <script src="https://apis.google.com/js/client:plusone.js"></script>
  </head>
  <body>
    <span id="signinButton">
      <span
        class="g-signin"
        data-callback="signinCallback"
        data-clientid="YOUR_CLIENT_ID"
        data-cookiepolicy="single_host_origin"
        data-requestvisibleactions="http://schemas.google.com/AddActivity"
        data-scope="https://www.googleapis.com/auth/plus.login">
      </span>
    </span>
    <script>
      function signinCallback (resp) {
        gapi.client.load('plus', 'v1', function() {
          gapi.client.plus.people.get({userId: 'me'}).execute(getProfilePic);
        });
      }
      function getProfilePic(person){
        console.log(person.image.url);
        console.log(person.cover.coverPhoto.url);
      }
    </script>
  </body>
</html>

When the page loads, the sign-in button renders, when the user signs in, the callback is triggered. When the callback is triggered, the plus client is loaded. After the plus client loads, the API call to people.get is made.

May this code help you To Fetch Google+ Profile Info with pic

<?php  
  /* * Copyright 2011 Google Inc. 
  * 
  * Licensed under the Apache License, Version 2.0 (the "License"); 
  * you may not use this file except in compliance with the License. 
  * You may obtain a copy of the License at 
  * 
  * http://www.apache.org/licenses/LICENSE-2.0 
  * 
  * Unless required by applicable law or agreed to in writing, software 
  * distributed under the License is distributed on an "AS IS" BASIS, 
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  * See the License for the specific language governing permissions and 
  * limitations under the License. 
  */  
  require_once 'google-api-php-client/src/apiClient.php';  
  require_once 'google-api-php-client/src/contrib/apiPlusService.php';  
session_start();  
$id = $_POST['id'];  
$client = new apiClient();  
  $client->setApplicationName("Google+ PHP Starter Application");  
  // oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.  
  $client->setClientId('357142505911.apps.googleusercontent.com');  
  $client->setClientSecret('LbJa7YOJ1Th-e-TOosEJxI4A');  
  $client->setRedirectUri('http://www.w3resource.com/API/google-plus/example.php');  
  $client->setDeveloperKey('AIzaSyD3stLpkt7jJw0mkMsJtM9m_zrgg26rrsI');  
  $plus = new apiPlusService($client);  
if (isset($_REQUEST['logout'])) {  
  unset($_SESSION['access_token']);  
  }  
if (isset($_GET['code'])) {  
  $client->authenticate();  
  $_SESSION['access_token'] = $client->getAccessToken();  
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);  
  }  
if (isset($_SESSION['access_token'])) {  
  $client->setAccessToken($_SESSION['access_token']);  
  }  
if ($client->getAccessToken()) {  
  $me = $plus->people->get($id);  
$optParams = array('maxResults' => 100);  
  $activities = $plus->activities->listActivities($id, 'public', $optParams);  
// The access token may have been updated lazily.  
  $_SESSION['access_token'] = $client->getAccessToken();  
  } else {  
  $authUrl = $client->createAuthUrl();  
  }  
  ?>  
<!doctype html>  
  <html>  
  <head><link rel='stylesheet' href='style.css' /></head>  
  <body>  
  <header><h1>Google+ Sample App</h1></header>  
  <div class="box">  
<?php if(isset($me) && isset($activities)): ?>  
  <div class="me">  
  <p><a rel="me" href="<?php echo $me['url'] ?>"><?php print $me['displayName'] ?></a></p>  
  <p><?php print $me['tagline'] ?></p>   
  <p><?php print $me['aboutMe'] ?></p>   
  <div><img src="<?php echo $me['image']['url']; ?>?sz=82" /></div>  
  </div>  
  <div class="activities">Your Activities:  
  <?php foreach($activities['items'] as $activity): ?>  
  <div class="activity">  
  <p><a href="<?php print $activity['url'] ?>"><?php print $activity['title'] ?></a></p>  
  </div>  
  <?php endforeach ?>  
  </div>  
  <?php endif ?>  
  <?php  
  if(isset($authUrl)) {  
  print "<a class='login' href='$authUrl'>Connect Me!</a>";  
  } else {  
  //print "<a class='logout' href='?logout'>Logout</a>";  
  }  
  ?>  
  </div>  
  </body>  
  </html>  

Source :http://www.w3resource.com/API/google-plus/tutorial.php#

Accourding to Documentation of New way to Sign In Google, It says

public Uri getPhotoUrl ()

Returns the photo url of the signed in user if the user has a profile picture and you built your configuration either starting from new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)} or with requestProfile() configured; null otherwise. Not guaranteed to be present for all users, even when configured.

As last line says Not guaranteed to be present for all users, even when configured , you should handle null case.

P/S: sometimes, if Google+ profile picture has been created already but after the time you add Google account in your device, perhaps you need to delete that existing Google account from your device, then re-add.

The following url is suggested here:

https://plus.google.com/s2/photos/profile/GOOGLE-ID?sz=100

I've never seen that before in any documentation, so that's probably not supported by Google+, but working right now.

Maybe +class or +Prisoner can say something about the support of this url to get profile pic?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top