google/apiclient
Official Google APIs Client Library for PHP. Access services like Gmail, Drive, and YouTube from your server. Supports PHP 8+. In maintenance mode (critical fixes/security only). Install via Composer: google/apiclient.
Installation:
composer require google/apiclient
Pin google/apiclient-services to a specific version for production stability:
"require": {
"google/apiclient": "^2.15.0",
"google/apiclient-services": "^2.15.0"
}
Basic Setup:
require __DIR__.'/vendor/autoload.php';
$client = new Google\Client();
$client->setApplicationName('MyApp');
$client->setDeveloperKey('YOUR_API_KEY'); // For API keys
First API Call (e.g., Books API):
$service = new Google\Service\Books($client);
$results = $service->volumes->listVolumes('PHP', ['filter' => 'free-ebooks']);
$client = new Google\Client();
$client->setAuthConfig(__DIR__.'/client_secret.json');
$client->addScope(Google\Service\Drive::DRIVE);
$client->setRedirectUri('https://your-app.com/oauth2callback');
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token);
}
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client = new Google\Client();
$client->useApplicationDefaultCredentials();
$client->setSubject('user@example.com'); // Impersonate a user
$client->addScope(Google\Service\Drive::DRIVE);
$drive = new Google\Service\Drive($client);
$files = $drive->files->listFiles();
$batch = new Google\BatchRequest($client);
$batch->add($drive->files->get('FILE_ID'));
$batch->add($drive->files->get('ANOTHER_FILE_ID'));
$responses = $batch->execute();
// Upload
$file = new Google\Service\Drive\DriveFile([
'name' => 'test.txt',
'parents' => ['ROOT_FOLDER_ID']
]);
$content = fopen('test.txt', 'r');
$service->files->create($file, [
'uploadType' => 'media',
'mediaBody' => $content
]);
// Download
$file = $service->files->get('FILE_ID');
$content = $file->getDownloadMedia();
file_put_contents('downloaded.txt', $content);
.env and use Laravel’s config() helper:
$client = new Google\Client();
$client->setAuthConfig(config('services.google.client_secret'));
Google\Task\Composer::cleanup in composer.json to trim unused services:
"scripts": {
"post-install-cmd": "Google\\Task\\Composer::cleanup"
},
"extra": {
"google/apiclient-services": ["Drive", "YouTube"]
}
$cache = new \Cache\Adapter\Filesystem\FilesystemCachePool(
new \League\Flysystem\Filesystem(
new \League\Flysystem\Adapter\Local(__DIR__.'/cache')
)
);
$client->setCache($cache);
Service Account Limitations:
403: Access Denied. Solution: Ensure scopes are correct and the service account has proper IAM roles.Token Expiry:
setTokenCallback to log new tokens:
$client->setTokenCallback(function ($token) {
file_put_contents('token.json', json_encode($token));
});
Quota Exhaustion:
429 Too Many Requests with exponential backoff:
$client->setHttpClient(new \GuzzleHttp\Client([
'delay' => 1000, // 1 second delay
'timeout' => 30
]));
CORS Issues:
Deprecated APIs:
plus, analytics) are deprecated. Use alternatives like people or analyticsadmin.$client->setDeveloperKey('YOUR_KEY');
$client->setUseBatch(true);
$client->setApplicationName('DebugApp');
$client->setAuthConfig('client_secret.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$client->setDebug(true); // Logs to STDOUT
google/apiclient.invalid_grant: Refresh token expired. Re-authenticate the user.insufficient_permission: Missing scope or IAM role. Verify addScope() and service account permissions.Custom HTTP Client: Override the default Guzzle client for retries or middleware:
$client->setHttpClient(new \GuzzleHttp\Client([
'handler' => \GuzzleHttp\HandlerStack::create([
new \GuzzleHttp\Middleware::retry(new \GuzzleHttp\RetryMiddleware())
])
]));
Token Management:
Extend Google_Auth_AssertionCredentials for custom token fetching:
class CustomCredentials extends Google_Auth_AssertionCredentials {
public function getAssertion() { /* ... */ }
}
$client->setAuth(new CustomCredentials(...));
Service-Specific Extensions: Use traits or decorators to wrap API services:
class DriveServiceDecorator {
protected $service;
public function __construct(Google\Service\Drive $service) {
$this->service = $service;
}
public function uploadFile($filePath, $folderId) {
// Custom logic
$this->service->files->create(...);
}
}
Event Listeners: Attach callbacks to the client for pre/post-request hooks:
$client->addIOHandler(new class implements \Google\IO\IOHandlerInterface {
public function handle($request, $next) {
// Pre-request logic
$response = $next($request);
// Post-request logic
return $response;
}
});
setUseBatch(true):
Enables batch requests but may fail if individual requests exceed size limits (~30MB).setAccessType('offline'):
Required for refresh tokens but may trigger additional OAuth prompts.setApprovalPrompt('force'):
Bypasses cached consent (useful for testing). Avoid in production.How can I help you explore Laravel packages today?