After reading the Wikipedia introduction mentioned by @Izzy, you can have a look at google's Oauth2 introduction and then jump into google's quick start sample app; it gives a fully working commented php app of using oauth 2.0 to authenticate with a google account and fetch user data.
The code in the example uses the package google-api-php-client as well as a js library to reduce the boilerplate to simpler API calls. For the client/frontend side, javascript calls such as:
auth2.signIn().then(function(googleUser) {
onSignInCallback(googleUser.getAuthResponse());
}, function(error) {
alert(JSON.stringify(error, undefined, 2));
});
And on the server, php side:
$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// You can read the Google user ID in the ID token.
// "sub" represents the ID token subscriber which in our case
// is the user ID. This sample does not use the user ID.
$attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)
->getAttributes();
$gplus_id = $attributes["payload"]["sub"];
// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Successfully connected with token: ' . print_r($token, true);
Please note that requesting an email address will require asking further the permission (named Authorization scopes
) from the client, as seen in this SO question:
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
You can then use any number of APIs that expose userinfo.email. One of these, Google_Service_Oauth2
, has the helpful public method userinfo
$oauth2Service = new Google_Service_Oauth2(...);
$userinfo = $oauth2Service->userinfo;