double-star-systems/google-api-bundle
Installation
Run composer require double-star-systems/google-api-bundle in your Laravel project (note: this bundle is technically Symfony-focused, but can be adapted via Symfony Bridge or standalone usage).
Credentials Setup
credentials.json from the Google Cloud Console.config/google_api_bundle/credentials.json (or configure a custom path below).Basic Configuration
Add minimal config to config/services.php (Laravel) or config/packages/google_api.yaml (Symfony):
'google_api' => [
'scopes' => ['https://www.googleapis.com/auth/drive'], // Required
'credentials_file' => config('services.google_api.credentials_file', base_path('config/google_api_bundle/credentials.json')),
'token_file' => storage_path('framework/google_tokens.json'), // Laravel storage path
'application_name' => 'Your Laravel App',
],
First Use Case
Inject the Google\Client service into a controller or service:
use Google\Client;
class GoogleDriveController extends Controller {
public function listFiles(Client $client) {
$service = new Google_Service_Drive($client);
$results = $service->files->listFiles();
return $results->getFiles();
}
}
Service Binding: Register the bundle’s service in Laravel’s container (if not auto-discovered):
$this->app->bind('google.client', function ($app) {
return new Google\Client([
'credentials' => $app['config']['services.google_api.credentials_file'],
'scopes' => $app['config']['services.google_api.scopes'],
'auth' => new Google_Auth_AssertionCredentials(
$app['config']['services.google_api.service_account_email'],
['https://www.googleapis.com/auth/drive']
),
]);
});
Service Scopes: Dynamically set scopes per request:
$client = app('google.client');
$client->setScopes(['https://www.googleapis.com/auth/calendar.readonly']);
OAuth Flow For user-based auth (e.g., Drive API):
$client->setAuthConfig($credentialsPath);
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$authUrl = $client->createAuthUrl();
// Redirect user to $authUrl, then handle callback with `$client->authenticate()`.
Service Account Flow For server-to-server interactions (e.g., Gmail API):
$client->setAuthConfig($credentialsPath);
$client->setSubject('user@example.com'); // Impersonate a user
Token Management Persist tokens to Laravel’s storage:
$client->setAccessToken($tokenData);
$tokenData = $client->getAccessToken(); // Save to DB/storage
Laravel Caching: Cache API responses with Laravel’s cache:
$cacheKey = 'google_drive_files';
$files = cache()->remember($cacheKey, now()->addHours(1), function () use ($service) {
return $service->files->listFiles()->getFiles();
});
Queue Jobs: Offload long-running API calls to queues:
Dispatch(new SyncGoogleData($client))->onQueue('google');
API Rate Limiting: Use Laravel’s throttle middleware for endpoints consuming Google APIs.
Credentials Paths
config/google_api_bundle/) may fail in shared hosting. Use config() or environment variables:
'credentials_file' => env('GOOGLE_CREDENTIALS_PATH', base_path('config/google_api_bundle/credentials.json')),
Token Persistence
token_file to be writable. In Laravel, use storage_path():
token_file: "%kernel.project_dir%/storage/framework/google_tokens.json"
Storage::disk('local')->makeDirectory('framework', 0755, true);
Scopes Misconfiguration
Google_Auth_Exception. Validate scopes against Google’s API docs.Service Account vs. OAuth
Google_Auth_AssertionCredentials failing. Use:
CORS/Redirect URIs
credentials.json includes a valid redirect_uri matching your Laravel app’s callback URL (e.g., http://your-app.test/google/callback).$client->setDeveloperKey('YOUR_DEBUG_KEY'); // For API key-based services
$client->setApplicationName('Debug Mode');
try {
$client->fetchAccessTokenWithAssertion();
} catch (Exception $e) {
Log::error('Google Auth Error: ' . $e->getMessage());
}
Custom Services Extend the bundle’s service to add Laravel-specific logic:
$this->app->extend('google.client', function ($client, $app) {
$client->setUseObjects(true); // Enable object serialization
return $client;
});
Event Listeners Listen for token refreshes:
event(new GoogleTokenRefreshed($client->getAccessToken()));
API Response Wrapping Create a Laravel resource for Google API responses:
class GoogleDriveFileResource extends JsonResource {
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'url' => url("/storage/{$this->id}"),
];
}
}
Google_Service_Drive->files->listFiles() with pageSize and pageToken for pagination.$optParams = ['fields' => 'files(id, name, createdTime)'];
$results = $service->files->listFiles($optParams);
How can I help you explore Laravel packages today?