Google Sign In Button – Javascript, PHP
In this article, we are going to show you how you can implement a Google sign in on your website using Javascript and PHP. We will use Javascript to render the button. And we will use PHP to verify the token generated by the Google client because anyone can try to tamper with the client-side code.
Table of content:
- Create an OAuth Client ID on the Google developer console
- Install Google OAuth Library
- Render Google sign-in button
- Verify token generated after successful sign in
1. Create an OAuth Client ID
Follow this tutorial to create an OAuth Client ID on the Google developer console.
2. Install Google OAuth Library
You can install the Google OAuth library by running the following command at the root of your project:
composer require google/apiclient
3. Render Google sign in button
Then we need to create a container where we will display the sign-in button at the appropriate place on your website.
<!-- include bootstrap -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<!-- google signin button -->
<div class="container" style="margin-top: 50px;">
<div class="row">
<div class="col-md-12">
<div id="myGoogleButton" onclick="googleSigninClick();"></div>
</div>
</div>
</div>
<!-- initialize google API -->
<script src="https://apis.google.com/js/platform.js?onload=googleInit" async defer></script>
Then we need to render the <div> tag with the sign in button. Make sure to replace the {your_google_client_id} code with your Google client ID generated from 1st step.
<script>
// variable to check that the button must be clicked manually
var googleSigninClicked = false;
// when the button is clicked by user
function googleSigninClick() {
googleSigninClicked = true;
}
// called when the google API is initialized
function googleInit() {
// load the auth API
gapi.load('auth2', () => {
// initialize the auth library
gapi.auth2.init({ client_id: "{your_google_client_id}" }).then(() => {
// render the google sign in button
gapi.signin2.render('myGoogleButton', {
'scope': 'profile email',
'width': 240,
'height': 40,
'longtitle': true,
'theme': 'dark',
onsuccess: (googleUser) => {
// this function is called when the page is loaded too,
// so we must login the user when the button is manually clicked
if (!googleSigninClicked) {
return false;
}
googleSigninClicked = false;
// get user profile
console.log(googleUser);
var profile = googleUser.getBasicProfile();
console.log({
"id": profile.getId(),
"name": profile.getName(),
"picture": profile.getImageUrl(),
"email": profile.getEmail()
});
// get token to be verified from server
var id_token = googleUser.getAuthResponse().id_token;
// send an AJAX request to the server to verify the token
var ajax = new XMLHttpRequest();
ajax.open("POST", "google-sign-in.php", true);
// when the status of request is changed
ajax.onreadystatechange = function () {
// when the response is received from server
if (this.readyState == 4) {
// if the server is successfull
if (this.status == 200) {
// the response will be a JSON string, convert that into javascript object
var data = JSON.parse(this.responseText);
console.log(data);
}
// if there is any internal server error
if (this.status == 500) {
console.log(this.responseText);
}
}
};
// create form data object
var formData = new FormData();
// append the token in the request
formData.append("id_token", id_token);
// send the request
ajax.send(formData);
},
onfailure: (error) => {
console.log(error);
}
});
});
});
}
</script>
Refresh the page now and you will be able to see a Google sign-in button. By default, you will see the message “Sign-in with Google”. Once you click the button and sign in with your Google account, you will see your profile information in the browser console.
4. Verify token
The token generated from the sign-in button must be verified from the server-side because anyone can tamper with the client-side code. To verify this token we are already sending an AJAX request. Now we need to create a new file named “google-sign-in.php” and paste the following code into it.
Make sure to replace the value of $google_oauth_client_id variable with your own client ID.
<?php
// 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"];
// send the response back to client side
echo json_encode([
"status" => "success"
]);
}
else
{
// token is not verified or expired
echo json_encode([
"status" => "error"
]);
}
Refresh the page now and try to log in again. Now we will also see a success response in your browser console, that is because of an AJAX request. On the server side, you can register the user if he is not already registered or you can start his session if he is already registered.
So that’s how you can implement a Google sign-in button in your website using plain Javascript and PHP. Try to implement this in your live site and let us know in the comments section if there is any problem.