Skip to content

AdnanTech

Programming tutorials

Menu
  • Python
  • PHP
    • Laravel
    • WordPress
  • Javascript
    • React JS
    • Node.js
    • Vue JS
  • Databases
    • MySQL
    • MongoDB
  • Mobile apps
    • Android
    • iOS
  • Tutorials
    • Ticketing system
    • Chat app
  • Blog
  • Projects
  • API
    • Social network API
  • Services
    • Hash Generator
    • World Clock
    • Word Counter
    • Currency Converter
    • Financial Ledger
    • Time Difference
    • Stopwatch & Timer
    • Google Maps
  • SAAS
    • Job Entry

Google Sign In Button – Javascript, PHP

by adnanafzal565Posted onDecember 6, 2023December 6, 2023

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:

  1. Create an OAuth Client ID on the Google developer console
  2. Install Google OAuth Library
  3. Render Google sign-in button
  4. 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.

Post Views: 607
Posted in Javascript, PHPTagged google, google developer console, google login, javascript, oauth client, php

Published by adnanafzal565

View all posts by adnanafzal565

Post navigation

Prev Dynamic FAQ – PHP and MySQL
Next Change title text – PHP, MySQL, Node JS

Recent Posts

  • SAAS in React + Laravel – Job Entry
  • Show selected images from input type file – React
  • Add dynamic rows in React
  • Soft Delete 🗑 – Node.js, MongoDB
  • 2 ways to loop through a number in React

Recent Comments

  1. canada pharmaceuticals online generic on PDF view in browser and export as file – PHP
  2. System on (no title)
  3. adnanafzal565 on (no title)
  4. adnanafzal565 on (no title)
  5. System on (no title)

Archives

  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • November 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • November 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020

Categories

  • Android
  • Complete Projects
  • CSS
  • FFmpeg
  • Git
  • htaccess
  • HTML
  • iOS
  • Javascript
  • Laravel
  • Leap Motion Controller
  • MEVN
  • MongoDB
  • MySQL
  • Node.js
  • PHP
  • Python
  • React JS
  • Swift
  • Tips & Tricks
  • Uncategorized
  • Vue JS
  • WordPress
AdnanTech © All rights reserved. 2013 - 2025
Looking for a web developer ?