Login with Google Account OAuth
Wall Script
Wall Script
Sunday, September 23, 2012

Login with Google Account OAuth

We covered almost all the Open Authentication (OAuth) login systems for Facebook, Twitter, Google plus and Instagram, but unfortunately I missed most important Google Open Authentication login. Today I want explain how to implement this for your web project, this script is very quick and sure it helps you to increase your web project registrations.

Login with Google Account OAuth.


Download Script
     Live Demo

Previous Tutorial Login with Google Account OpenID and Login with Google Plus OAuth

Database
Sample database design
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(50) UNIQUE,
fullname VARCHAR(100),
firstname VARCHAR(50),
lastname VARCHAR(50),
google_id VARCHAR(50),
gender VARCHAR(10),
dob VARCHAR(15),
profile_image TEXT,
gpluslink TEXT
)

Step 1: Domain Registration
Add or register your domain at click here.

Importing GMail Contacts Google OAuth Connect with PHP.

Step 2: Ownership verification
Verify your domain ownership with HTML file upload or including META tag.

Importing GMail Contacts Google OAuth Connect with PHP.

Step 3: OAuth Keys
Google will provide you OAuth consumer key and OAuth consumer secret key.
Importing GMail Contacts Google OAuth Connect with PHP.

Step 4: Google APIConsole
Create client ID OAuth Console here.
Login with Google Plus Oauth

Step 5:
Create client ID.
Login with Google Plus OAuth.

Step 6
Here the application OAuth client ID and client secret.
Login with Google Plus OAuth.

config.php
You can find this in src folder, here you have to configure application OAuth keys, Consumer keys and redirection callback URL.
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console Step 6 keys 
'oauth2_client_id' => 'App Client ID',
'oauth2_client_secret' => 'App Client Secret',
'oauth2_redirect_uri' => 'http://yoursite.com/gplus/index.php',

// OAuth1 Settings Step 3  keys.
'oauth_consumer_key' => 'OAuth Consumer Key',
'oauth_consumer_secret' => 'OAuth Consumer Secret',

google_login.php
Google plus login system. Just include the file in index.php
<?php
require_once 'src/apiClient.php';
require_once 'src/contrib/apiOauth2Service.php';
session_start();
$client = new apiClient();
setApplicationName("Google Account Login");
$oauth2 = new apiOauth2Service($client);
if (isset($_GET['code']))
{
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
unset($_SESSION['google_data']); //Google session data unset
$client->revokeToken();
}

if ($client->getAccessToken())
{
$user = $oauth2->userinfo->get();
$_SESSION['google_data']=$user; // Storing Google User Data in Session
header("location: home.php");
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}

if(isset($personMarkup)):
print $personMarkup;
endif

if(isset($authUrl))
{
echo "<a class="login" href="$authUrl">Google Account Login</a>";
} else {
echo "<a class="logout" href="?logout">Logout</a>";
}
?>

home.php
Contains PHP code inserting Google plus session details into users table.
<?php
session_start();
include('db.php'); //Database Connection.
if (!isset($_SESSION['google_data'])) {
// Redirection to application home page. 
header("location: index.php");
}
else
{
//echo print_r($userdata);
$userdata=$_SESSION['google_data'];
$email =$userdata['email'];
$googleid =$userdata['id'];
$fullName =$userdata['name'];
$firstName=$userdata['given_name'];
$lastName=$userdata['family_name'];
$gplusURL=$userdata['link'];
$avatar=$userdata['picture'];
$gender=$userdata['gender'];
$dob=$userdata['birthday'];
//Execture query
$sql=mysqli_query("insert into users(email,fullname,firstname,lastname,google_id,gender,dob,profile_image,gpluslink) values('$email','$fullName','$firstName','$lastName','$googleid','$gender','$dob','$avatar','$gplusURL')");
}
?>

db.php
Database configuration file, modify username, password, database and base url values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$base_url='http://www.youwebsite.com/email_activation/';
?>
web notification

59 comments:

  1. Good job, only i recommend you, and learning readers dont use never mysql_* functions of php, its better other drivers like PDO. If you can in future posts Srinivas use PDO.

    Regardings from Valencia - Spain, in WidPlay Project ;)

    ReplyDelete
  2. what about returning clients after registering?

    ReplyDelete
  3. mysql_ functions are used throughout all tutorials and examples over the net.
    the developer is responsible for writing the proper code for his project.
    Never use an example code for live projects.
    The tutorial is only used to grasp the logic behind some action - not to be used "as is".

    Other than that .. nice tutorial Mr. Tamada

    ReplyDelete
  4. how to use response_type=token?

    ReplyDelete
  5. As always a great tutorial. Well written and easy to follow.

    Just a personal point, I already have a MySQL database and would like to integrate this function into it... That would be useful to know

    Keep the good tutorials coming

    ReplyDelete
  6. I like your tutorial, Is that the API used in this tutorial is the latest version?

    ReplyDelete
  7. Great tutorial srini...good job...

    ReplyDelete
  8. Great tutorial and demo for Google ID authentication! Rock on!
    ~Duru

    ReplyDelete
  9. keep up the good work

    ReplyDelete
  10. well explained tutorial!!!
    Grate Thanks!!!!!!

    ReplyDelete
  11. Really good post.
    Just FYI if anyone have some problem with headers, run session at index.php on first line.

    ReplyDelete
  12. Hello to all!

    How can I get someone's bio?

    Can you also give me the link to the API documentation for this Google library because I can not find.


    Thank you!

    ReplyDelete
  13. Great post Srinivas, this code was really needed after your login by twitter, Facebook script :)

    ReplyDelete
  14. you are always rocking i will try same using java thanks for explanation.....!!!

    ReplyDelete
  15. Google Feedburner is down new subscribers please be patient

    ReplyDelete
  16. Nice tutorial machi, thanks :)

    ReplyDelete
  17. @Srinivas Can you do the same thing for Twitter with API 1.1?

    Thank you!

    ReplyDelete
  18. Good tutorial.. but 1 bug??

    http://demos.9lessons.info/googlelogin/home.php loads even after i log out!!!

    ReplyDelete
  19. I am having the following error:

    Fatal error: Uncaught exception 'apiIOException' with message 'HTTP Error: (0) Couldn't resolve host 'accounts.google.com'' in /home/sellasit/public_html/google-api-php-client/src/io/apiCurlIO.php:127 Stack trace: #0 /home/sellasit/public_html/google-api-php-client/src/auth/apiOAuth2.php(93): apiCurlIO->makeRequest(Object(apiHttpRequest)) #1 /home/sellasit/public_html/google-api-php-client/src/apiClient.php(138): apiOAuth2->authenticate(Array) #2 /home/sellasit/public_html/google-site-verify.php(18): apiClient->authenticate() #3 {main} thrown in /home/sellasit/public_html/google-api-php-client/src/io/apiCurlIO.php on line 127

    Any Idea??

    ReplyDelete
  20. thanks but this only use for ssl certificate sites

    ReplyDelete

  21. Important: OAuth 1.0 has been officially deprecated as of April 20, 2012. It will continue to work as per our deprecation policy, but we encourage you to migrate to OAuth 2.0 as soon as possible.
    Please guide me

    ReplyDelete
  22. Please tell how to change the permissions???

    ReplyDelete
  23. Very nice tips, thanks for sharing!

    ReplyDelete
  24. This is simply awsome good work and it helps me alot with my web work

    thanks bro a lot me too from chennai :D

    ReplyDelete
  25. I really appreciate sharing this great post. I like this blog and have bookmarked it. Thumbs up

    ReplyDelete
  26. Thankyou for this.
    Its realy cool to use this auth method.

    ReplyDelete
  27. Nice post, thanks
    bagikode.com/jquery

    ReplyDelete
  28. Very nice
    this there a way to do this with youtube login and get channel info and Name

    ReplyDelete
  29. Hi , i have an error, can you help me?
    Error : invalid_scope

    Some requested scopes were invalid. {invalid=[https://www.googleapis.com/auth/oauth2]}

    ReplyDelete
  30. Hi..,

    Good tutorial. But how can i logout from google using this code? That is, even i logout from ur demo, I can access my other google applications (like gmail, blog, etc) diectly.

    Thanks...

    ReplyDelete
  31. how to download i can't able to download this code !!!!

    ReplyDelete
  32. I Want to recovered placelived ( country ) plz help me

    ReplyDelete
  33. when login time google Product is requesting permission to: it's should ask one time, how to do that, any pls help me

    ReplyDelete
  34. Warning: include(google_login.php) [function.include]: failed to open stream: Operation not permitted in C:\Inetpub\vhosts\7sinfotech.in\subsite\googlelogin\index.php on line 21

    Warning: include(google_login.php) [function.include]: failed to open stream: Operation not permitted in C:\Inetpub\vhosts\7sinfotech.in\subsite\googlelogin\index.php on line 21

    Warning: include() [function.include]: Failed opening 'google_login.php' for inclusion (include_path='.;./includes;./pear') in C:\Inetpub\vhosts\7sinfotech.in\subsite\googlelogin\index.php on line 21

    ReplyDelete
  35. Error: invalid_scope

    Some requested scopes were invalid. {invalid=[https://www.googleapis.com/auth/oauth2]}

    ReplyDelete
  36. It doesn't really logout! If I go back to the http://demos.9lessons.info/googlelogin/home.php after logging out it still has me logged in and displays my google account basic info.. any solution?

    ReplyDelete
  37. Hi,

    It's great tutorial! But i have problem with download source :( I have tried with 3 different accounts and nothing :( Could you help me with it?

    Best,
    Rafal

    ReplyDelete
  38. Nice script but its toooooo big with many folders and files !! for why ??. 300kb ?? wanna a script with just 2 or 3 files . i found one script but i couldnt get gender and guid from it. this script is easy but BIG.

    ReplyDelete
  39. Thanks for sharing. i need help, its always asking permission every login. how to skip it?

    ReplyDelete
  40. hi its a good tutorial it helped me. i want to display all the posts from my google plus page to website. How can i do this? i was able to get only those posts which are posted by the owner. I am trying to fetch the posts posted by others on my timeline in google plus.
    Any help is greatly appreciated. Thank you.

    ReplyDelete
  41. how to change or reset the consumer key/secret?

    ReplyDelete
  42. Nice tutorial...
    I am also using Google api but In my api it asks for two time to login (Only first time or when I delete all the history of my browser including cookies and all).
    Can you suggest me any solution?
    http://stackoverflow.com/questions/24757810/php-google-api-is-asking-to-log-in-twice

    ReplyDelete
  43. how to get country,city and state in google login

    ReplyDelete
  44. ho do I add state=THE_STATE_PARAMETERS in the above example?

    ReplyDelete
  45. i am using GOOGLE API with PHP ; My question if user is already logged in from other application or user leave the page;

    How can i Re Authenticate it so that my programme asked password

    ReplyDelete
  46. Nice Work, I have use both codigniter or php site

    ReplyDelete
  47. Good Work ,Thanks. I have implemented both codigniter or php site , no issues. Thank you very much..............

    ReplyDelete

mailxengine Youtueb channel
Make in India
X