Christopher Ansbaugh
Christopher Ansbaugh

Reputation: 133

Google_Service_OAuth2 is 'Undefined type' in PHP

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.

Upvotes: 4

Views: 4059

Answers (1)

Michael Peng
Michael Peng

Reputation: 926

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);

Upvotes: 5

Related Questions