web analytics

Get a User’s Google Email Address via OAuth2 in PHP

By: Arvin
June 17, 2011

google oauth2 grant access page

OAuth2 is far easier to do than the original OAuth which requires that all data is signed each time. Here is an example script to retrieve a user’s Google email address (GMail or Google Apps account) which is useful if you want to authenticate users for your application but do not want to make them sign up with another account; or if you want to get the user’s email address and not worry about sending verification emails.

Before making OAuth2 requests on Google data, you first need to register an application on Google’s API Console to get a client_id and client_secret. You also need to setup valid redirect_uri‘s that your application will use.

Download the files used in this article
http://codecri.me/download/sources/script-google-oauth2-php

You can follow the OAuth2 verification process flow via the comments, or read the full documentation by Google on Using OAuth 2.0 to Access Google APIs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php

# Arvin Castro, arvin@codecri.me
# 16 June 2011
# http://codecri.me/case/430/get-a-users-google-email-address-via-oauth2-in-php

session_name('googleoauth2');
session_start();

# require 'class-xhttp-php/class.xhttp.php';

# http://code.google.com/apis/console#access
$client_id = '';
$client_secret = '';
$redirect_uri = '';

# Scope for getting the user's email address https://sites.google.com/site/oauthgoog/Home/emaildisplayscope
$scope = 'https://www.googleapis.com/auth/userinfo#email';

if(isset($_GET['signin'])) {

   # STEP 2:
   # Build URL for OAuth2 authorization
   $url = "https://accounts.google.com/o/oauth2/auth?".http_build_query(array(
      'client_id' => $client_id,
      'redirect_uri' => $redirect_uri,
      'scope' => $scope,
      'response_type' => 'code'
   ));

   # STEP 3:
   # Redirect user to URL for authorization;
   header('Location: '.$url, true, 302);
   die();

} elseif(isset($_GET['code'])) {

   # STEP 4:
   # User granted access to us; User is redirected back to our application; code parameter is included

   # STEP 5:
   # Exchange code for access token and secret
   $data = array('post' => array(
      'code' => $_GET['code'],
      'client_id' => $client_id,
      'client_secret' => $client_secret,
      'redirect_uri' => $redirect_uri,
      'grant_type' => 'authorization_code',
   ));
   $response = xhttp::fetch('https://accounts.google.com/o/oauth2/token', $data);

   if($response['successful']) {

      # STEP 6:
      # We got the access token; User is now logged in
      $_SESSION['loggedin'] = true;
      $_SESSION = array_merge($_SESSION, $response['json']);

      # Redirect user to remove code parameter in URL, Optional
      header('Location: '.$redirect_uri);
      die();

   } else {

      # STEP 6: Alternate
      # Unable to get access token; repeat STEP 5 or give up
   }

} elseif(isset($_GET['error'])) {

   # STEP 4: Alternate
   # User refused to give access to his email address; Ask feedback, optional; Repeat STEP 1

} elseif(isset($_GET['logout'])) {

   # STEP 10:
   # Log out of session; delete cookies
   $_SESSION = array();
   session_destroy();
   setcookie(session_name(), null, time() - 3600);
}

if($_SESSION['loggedin']) {

   # STEP 7:
   # Retrieve user's email; Pass access token via the Authorization header field
   $response = xhttp::fetch('https://www.googleapis.com/userinfo/email?alt=json', array(
      'headers' => array(
         'Authorization' => "OAuth $_SESSION[access_token]"
      )));

   if($response['successful']) {
      # STEP 8:
      # We got the user's email
      echo $response['json']['data']['email'];

   } else {
      # STEP 8: Alternate
      # Error getting user's email; repeat STEP 7 or Refresh token (not included) or repeat STEP 2 or repeat STEP 1
      echo $response['body'];
   }

   # STEP 9:
   # Provide logout link to discard session
   echo '<br/><a href="?logout">Logout</a>.';

} else {
   # STEP 1: Provide link to user to Sign in with Google
   echo '<a href="?signin">Sign in with Google</a>.';
}

?>
About the Author

Arvin was an overdue college crammer, occasional programmer, ever-newbie mashup coder, romantic long-distance lover, retired blogger, and ex-puppy-love-fiction writer. arvin@codecri.me, @codecrime

Category: Low-level | Comments RSS | Leave a Response | Short link

6 Comments

  • Dennis

    Great Post! I am studying this now and I need some help.
    I put the php file on my web server and send a request, when it responses to my server, the URL is “http://mydomain.com/oauth2callback#code=qwerty…..”
    My problem is how can I get the query string from this URL? I have no idea about this. Should I create a folder called “oauth2callback”? My problem now is I don’t know how to get this string, Can anybody help me? thanks a lot!

  • Dr.Lightman

    Thanks to Arvin for the article and thanks to Gerardo for the additional information to fetch more user info, I was looking for how to do it but didn’t manage to find it anywhere.

  • Gerardo

    Good post! I tested for 4 hours to find one PHP script that works…none of them really works…Your script work seamlessy at first run!
    I added this to get more infos about the user:

    $scope = 'https://www.googleapis.com/auth/userinfo#email';
    $scope .= ' https://www.googleapis.com/auth/userinfo.profile';

    and on the loggedin section:

    $response = xhttp::fetch('https://www.googleapis.com/oauth2/v1/userinfo?alt=json', array(

    and to read data:

    echo "-->name ".$response['json']['name'];
    echo "-->given_name ".$response['json']['given_name'];
    echo "-->family_name ".$response['json']['family_name'];
    echo "-->email ".$response['json']['email'];
    echo "-->link ".$response['json']['link'];
    echo "-->picture ".$response['json']['picture'];
    echo "-->gender ".$response['json']['gender'];
    • JAHAJEE.com

      Great post …thanks a lot ….
      but after getting all the User info if I am redirecting with session variable and header() redirect this session variable is not carried to the next page….
      I checked everything all pages have session_start()…tried session_write_close() and session_destroy() prior redirect but nothing works….can you please advise ???
      But a great script and thanks a lot again….

    • Alex

      This is great, thanks for the extra userdata you mentioned above, however there is one item missing that I am struggling to hunt down: Birthdate. Can anyone tell me where this can be found as I cannot find any details as to which scope to use and what it may be labelled as.

      Thanks!

    • Dennis

      Hello! I am studying this now and I need some help.
      I put the php file on my web server and send a request, when it responses to my server, the URL is “http://mydomain.com/oauth2callback#code=qwerty…..”
      My problem is how can I get the query string from this URL? I have no idea about this. Should I create a folder called “oauth2callback”? My problem now is I don’t know how to get this string, Can anybody help me? thanks a lot!

Leave a Reply

For posting PHP code, or any language for that matter, use
<code lang="php"> {your code goes here} </code>

This site also uses Gravatars to show avatars based on email addresses, but an email address is not required to post comments.

All pages are cached, so you might not be able to see your comment right away after you submit it.