# Google APIs Client Library

{% hint style="success" %}
Refer at [github](https://github.com/techkoson/generic-code/tree/main/PHP/googleLogin) for template (updated at 24 OCT 2023)
{% endhint %}

The [Google API Client Library](https://github.com/googleapis/google-api-php-client#composer) enables you to work with Google APIs such as Gmail, Drive or YouTube on your serve.

## Installation

### Composer

You can use [Composer](https://getcomposer.org/) or simply Download the Release. Follow the [installation instructions](https://getcomposer.org/doc/00-intro.md) if you do not already have composer installed.

Once composer is installed, execute the following command in your project root to install this library:

```
composer require google/apiclient
```

Finally, be sure to include the autoloader at login\_google.php:

```php
require_once 'vendor/autoload.php';
```

\\

## Google Cloud Console Setup

Open [Google Cloud Console](https://console.cloud.google.com/), Select the **\[button]** on the left upper corner and create a new project.

<figure><img src="/files/52VxXHoBRasr4gP4d8vg" alt=""><figcaption></figcaption></figure>

Select **\[APIs and services]**

<figure><img src="/files/3CwpPcyK0IfoswpKdxCS" alt=""><figcaption></figcaption></figure>

Select **\[OAuth consent screen]**, select **\[External]** as User Type, and **\[Create]**

<figure><img src="/files/x3CyB5pQcIPeq4fh2EKQ" alt=""><figcaption></figcaption></figure>

The label which has \* is compulsary to fill in, etc **\[App name]**, **\[User support email]** and **\[Email address]**. Other is optional and can left empty.

<figure><img src="/files/wIfdkJ60pyICy9oVm6jv" alt=""><figcaption></figcaption></figure>

You can leave it blank at this **\[Scope]** page

<figure><img src="/files/Ytsp7DsAC3jFsomEueOR" alt=""><figcaption></figcaption></figure>

You can leave it blank at this **\[Test user]** page.

<figure><img src="/files/CEHF4TDnzR3Mq1wjFUOy" alt=""><figcaption></figcaption></figure>

Check the data fill in, if nothing wrong, then **\[BACK TO DASHBOARRD]**

<figure><img src="/files/ELVwEVCnJpZeLzNbrOlW" alt=""><figcaption></figcaption></figure>

Remember to set the publishing status to publish by clicking **\[PUBLISH APP]**.\
Noted: If you were not set to publish, then you have to add your test user email account to able use the google API

<figure><img src="/files/F7x7dtK69ObpwJcxXeNq" alt=""><figcaption></figcaption></figure>

Select Credentials, then **\[CREATE CREDENTIALS]** >> **\[OAuth client ID]**

<figure><img src="/files/tGwgWxUGJtsyUPd0o6UO" alt=""><figcaption></figcaption></figure>

Select **\[Application type]** as Web application, fill in the **\[Name]** and **\[Authorised redirect URLs]** of your login page. In my case, i build my login page at *<http://localhost:3000/login\\_google.php>*.

<figure><img src="/files/wNW8prysTbjYmpErW3Sx" alt=""><figcaption></figcaption></figure>

Copy the **\[client ID]** and **\[Client Secret]** here. It will be using later on.

<figure><img src="/files/Zrh3t5BddUYVOfsfahMX" alt=""><figcaption></figcaption></figure>

## Implementation on Your Website

### `login_google.php`

replace the <mark style="color:red;">$clientID</mark> and <mark style="color:red;">$clientSecret</mark> to your **\[client ID]** and **\[Client Secret]**

```php
<?php
// Include config file
require_once 'vendor/autoload.php';


// Google Login Start  ------------------------------------------------------------------------------------------------------------------------

// Initialize Google API client
$clientID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$clientSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$redirectUrl = 'http://localhost:3000/login_google.php';
$client = new Google\Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUrl);
$client->addScope('profile');
$client->addScope('email');

//Create a URL to obtain user authorization
// If user is not authenticated, redirect to Google sign-in page
if (!isset($_GET['code'])) {
    $auth_url = $client->createAuthUrl();
    header("Location:  $auth_url");
} else {
    //get user info from google account
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);
    $service = new Google\Service\Oauth2($client);
    $user = $service->userinfo->get();
    $email = $user->email;
    $first_name = $user->givenName;
    $last_name = $user->familyName;
    $name =  $user->name;
    $gender = $user->gender;
    $profile_picture = $user->picture;
    $id = $user->id; //used
    $hd = $user->hd;
    $password =  password_hash($id, PASSWORD_DEFAULT); // take google id as password(after encrypted)
    $username = "$first_name, $last_name"; //the reason use format [$first name, $last name] instead of $name, is to avoid repeated username in users table


    // your action here
    echo $username;

}
```

### `button.php`

Create a login button to header to `login.php`

PHP

```php
    // if google login
    if (isset($_POST['googleLogin'])) {
        header("location: login.php");
    }
```

HTML

```html
<button name="googleLogin" class="login-with-google-btn">
  Sign in with Google
</button>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://technical-gitbook.kosontechnology.com/php/third-party-login/google-apis-client-library.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
