0

I am building a plugin in wordpress and there I need to user Google API. I did a test with a quickstart.php with the code from here and works, the connection is ok.

Now I structure all the files and the code from quickstart.php is pleaced inside a class, but there I get the error from the title.

<?php
/**
 * @package NrcCalmnestGoogleApi
 */
namespace Inc\Api\Google;

use Google_Client;
use Google_Service_Directory;

class GoogleApi
{
    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    public function getClient()
    {
        $client = new Google_Client();
        $client->setApplicationName('G Suite Directory API PHP Quickstart');
        $client->setScopes(Google_Service_Directory::ADMIN_DIRECTORY_USER);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
    
        // Load previously authorized token from a file, if it exists.
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        $tokenPath = 'token.json';
        if (file_exists($tokenPath)) {
            $accessToken = json_decode(file_get_contents($tokenPath), true);
            $client->setAccessToken($accessToken);
        }
    
        // If there is no previous token or it's expired.
        if ($client->isAccessTokenExpired()) {
            // Refresh the token if possible, else fetch a new one.
            if ($client->getRefreshToken()) {
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            } else {
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();
                printf("Open the following link in your browser:\n%s\n", $authUrl);
                print 'Enter verification code: ';
                $authCode = trim(fgets(STDIN));
    
                // Exchange authorization code for an access token.
                $accessToken = $client->fetchAccessTokenWithAuthCode(urldecode($authCode));
                $client->setAccessToken($accessToken);
    
                // Check to see if there was an error.
                if (array_key_exists('error', $accessToken)) {
                    throw new Exception(join(', ', $accessToken));
                }
            }
            // Save the token to a file.
            if (!file_exists(dirname($tokenPath))) {
                mkdir(dirname($tokenPath), 0700, true);
            }
            file_put_contents($tokenPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }

    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    public function someTest()
    {
        // Get the API client and construct the service object.
        $client = $this->getClient();
        $service = new Google_Service_Directory($client);
        
        // Print the first 10 users in the domain.
        $optParams = array(
          'customer' => 'my_customer',
          'maxResults' => 10,
          'orderBy' => 'email',
        );
        $results = $service->users->listUsers($optParams);
        
        if (count($results->getUsers()) == 0) {
          print "No users found.\n";
        } else {
          print "Users:\n";
          foreach ($results->getUsers() as $user) {
            printf("%s (%s)\n", $user->getPrimaryEmail(),
                $user->getName()->getFullName());
          }
        }
    
    }
    
}

// Get the API client and construct the service object.
$client = new GoogleApi;
$client = $client->someTest();

Fatal error: Uncaught Error: Class 'Google_Client' not found in ...\plugins\nrc-calmnest-google-api\inc\Api\Google\GoogleApi.php:29 Stack trace: #0 ...\plugins\nrc-calmnest-google-api\inc\Api\Google\GoogleApi.php(85): Inc\Api\Google\GoogleApi->getClient() #1 ...\plugins\nrc-calmnest-google-api\inc\Api\Google\GoogleApi.php(112): Inc\Api\Google\GoogleApi->someTest() #2 {main} thrown in ...\plugins\nrc-calmnest-google-api\inc\Api\Google\GoogleApi.php on line 29

What I tried:

here are some suggestions about autoload fine, or composer.json and to use composer install or composer dump-autoload, but nothing changes.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Beusebiu
  • 1,433
  • 4
  • 23
  • 68
  • It looks like that other post were using an old version of the client (and was posted 4 years ago). Have you checked [the readme file](https://github.com/googleapis/google-api-php-client) for googles api client? They have pretty well explained examples about autoloading and usage. – M. Eriksson Apr 22 '21 at 07:01
  • I didn't check this one. From what I see there is v. 2.7 and there are some stuff about composer.json. I can do an upgrade, to check it. – Beusebiu Apr 22 '21 at 07:05
  • Same output.. as a solution I remove all USE/NAMESPACE and I added the path for autoload and worked. require '../../../vendor/autoload.php'; – Beusebiu Apr 22 '21 at 08:10
  • I assume you have installed the library in your environment? – Iamblichus Apr 22 '21 at 11:00

0 Answers0