Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google_Service_OAuth2 is 'Undefined type' in PHP

Tags:

php

oauth-2.0

I'm trying to login with Google Sign-in but it's showing the 'Google_Service_OAuth2' as an undefined type.

I found this stack post: Google_Service_Oauth2 is undefined but there were no responses on it.

I installed the apiclient with composer and after research I've found that each of the files are in the correct locations (such as the src folder). Additionally, other libraries I've installed using composer are working properly.

Using command composer require google/apiclient composer installed version 2.12. I've tried installing v2.0 which is the version that most of the guides and posts I've found are using.

I've already run composer dump-autoload and restarted my machine just in case.

Here's my code:

use Google\Client;

$client = new Google_Client();

$clientID = 'MY CLIENT ID';
$clientSecret = 'MY CLIENT SECRET';
$redirectUri = 'http://localhost/dhi-portal/users/login';


$client->addScope('email');
$client->addScope('profile');

session_start();



if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

    if (!isset($token['error'])) {
        $client->setAccessToken($token['accessToken']);

        $_SESSION['accessToken'] = $token['accessToken'];

        $googleService = new Google_Service_OAuth2($client);
                    
    }
}

I haven't continued further from here because it's showing the undefined type.

Any guidance would be greatly appreciated.

like image 780
Christopher Ansbaugh Avatar asked Oct 19 '25 04:10

Christopher Ansbaugh


1 Answers

I had this same issue when I updated from google/apiclient version 2.9.x => 2.12.x. The problem is they changed the classes to use namespaces instead.

**Before**
$client = new Google_Client();
$service = new Google_Service_Books($client);


**After**
$client = new Google\Client();
$service = new Google\Service\Books($client);

Source: https://github.com/googleapis/google-api-php-client/blob/main/UPGRADING.md

So in your case, you need to rewrite your code like so if you wish to use 2.12.x:

$client = new Google\Client();
...
$googleService = new Google\Service\Oauth2($client);
like image 66
Michael Peng Avatar answered Oct 21 '25 19:10

Michael Peng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!