Google one tap sign in – PHP, Javascript
Google one tap sign in allows your website users to quickly log in to your site without having to enter a lot of form fields.
Video tutorial:
First, you need to go to Google Developer Console, from there you need to select or create a new project.
After a project is selected, you need to create its credentials.
In the credentials screen, you need to create OAuth Client ID credentials.
After that, you can specify:
- The type of application as “Web Application”.
- Set the name of the credential as per your desire.
- Add your website domain in “Authorized Javascript origins”.
- Goto OAuth Consent Screen.
OAuth Consent Screen will show you a form where you can enter the text you want to show to the user in the login prompt.
After everything is done, click “Save and Continue”. It will show you your Client ID and Client Secret.
Install Google OAuth Library
You need to copy both Google Client ID and Client Secret values as your PHP variables.
<?php
// use sessions, to show the login prompt only if the user is not logged-in
session_start();
// paste google client ID and client secret keys
$google_oauth_client_id = "";
$google_oauth_client_secret = "";
?>
We will be using PHP sessions because we will show this prompt only if the user is not logged in.
Make sure you have Composer installed. You can download and install Composer from here.
After that, you need to run the following command at your root folder:
composer require google/apiclient
Display Google One-tap Sign In Prompt
Paste the following lines in the file where you want to show the one-tap sign-in prompt. If you want to show it to all the pages of your website, simply paste it into your header or footer file.
<!-- check if the user is not logged in -->
<?php if (!isset($_SESSION["user"])): ?>
<!-- display the login prompt -->
<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="<?php echo $google_oauth_client_id; ?>"
data-context="signin"
data-callback="googleLoginEndpoint"
data-close_on_tap_outside="false">
</div>
<?php endif; ?>
This will make sure to show the prompt to the user only if he is not logged in. data-callback will be our Javascript function that will be called when the user taps the login button.
<script>
// callback function that will be called when the user is successfully logged-in with Google
function googleLoginEndpoint(googleUser) {
// get user information from Google
console.log(googleUser);
// send an AJAX request to register the user in your website
var ajax = new XMLHttpRequest();
// path of server file
ajax.open("POST", "google-sign-in.php", true);
// callback when the status of AJAX is changed
ajax.onreadystatechange = function () {
// when the request is completed
if (this.readyState == 4) {
// when the response is okay
if (this.status == 200) {
console.log(this.responseText);
}
// if there is any server error
if (this.status == 500) {
console.log(this.responseText);
}
}
};
// send google credentials in the AJAX request
var formData = new FormData();
formData.append("id_token", googleUser.credential);
ajax.send(formData);
}
</script>
We are sending an AJAX request to our server so we can verify the user using his Google Credentials Token. The server must do the verification because anyone can exploit the client-side variables.
Verify Google Credentials Token – PHP
We are creating a file named “google-sign-in.php” where we will do this verification.
<?php
// use sessions
session_start();
// include google API client
require_once "vendor/autoload.php";
// set google client ID
$google_oauth_client_id = "";
// create google client object with client ID
$client = new Google_Client([
'client_id' => $google_oauth_client_id
]);
// verify the token sent from AJAX
$id_token = $_POST["id_token"];
$payload = $client->verifyIdToken($id_token);
if ($payload && $payload['aud'] == $google_oauth_client_id)
{
// get user information from Google
$user_google_id = $payload['sub'];
$name = $payload["name"];
$email = $payload["email"];
$picture = $payload["picture"];
// login the user
$_SESSION["user"] = $user_google_id;
// send the response back to client side
echo "Successfully logged in. " . $user_google_id . ", " . $name . ", " . $email . ", " . $picture;
}
else
{
// token is not verified or expired
echo "Failed to login.";
}
?>
Here, you need to place your Google Client ID again. This will verify the Google Credentials Token. This will also start the user session so the next time user refreshes the page, it will not show the login prompt.
You can learn about saving the data in the database from here.
amazing article, i will try to integrate with my php website.
Thanks adnan.
You are welcome. Glad it helped.
A PHP Error was encountered
Severity: Notice
Message: Undefined index: id_token
Filename: controllers/Google.php
Line Number: 18
Backtrace:
File: D:\Projects\sd\application\controllers\Google.php
Line: 18
Function: _error_handler
File: D:\Projects\sd\index.php
Line: 315
Function: require_once
You need to run “composer update” first.