Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Google Api Bundle Laravel Package

double-star-systems/google-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. 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).

  2. Credentials Setup

    • Download your credentials.json from the Google Cloud Console.
    • Place it in config/google_api_bundle/credentials.json (or configure a custom path below).
  3. 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',
    ],
    
  4. 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();
        }
    }
    

Implementation Patterns

Dependency Injection

  • 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']);
    

Workflows

  1. 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()`.
    
  2. Service Account Flow For server-to-server interactions (e.g., Gmail API):

    $client->setAuthConfig($credentialsPath);
    $client->setSubject('user@example.com'); // Impersonate a user
    
  3. Token Management Persist tokens to Laravel’s storage:

    $client->setAccessToken($tokenData);
    $tokenData = $client->getAccessToken(); // Save to DB/storage
    

Integration Tips

  • 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.


Gotchas and Tips

Pitfalls

  1. Credentials Paths

    • Hardcoded paths (e.g., 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')),
      
  2. Token Persistence

    • The bundle expects token_file to be writable. In Laravel, use storage_path():
      token_file: "%kernel.project_dir%/storage/framework/google_tokens.json"
      
    • Fix: Ensure the directory exists and is writable:
      Storage::disk('local')->makeDirectory('framework', 0755, true);
      
  3. Scopes Misconfiguration

    • Missing or incorrect scopes will cause Google_Auth_Exception. Validate scopes against Google’s API docs.
  4. Service Account vs. OAuth

    • Confusing the two flows can lead to Google_Auth_AssertionCredentials failing. Use:
      • OAuth: User consent (e.g., Drive UI).
      • Service Account: Server-to-server (e.g., automated backups).
  5. CORS/Redirect URIs

    • For OAuth, ensure your credentials.json includes a valid redirect_uri matching your Laravel app’s callback URL (e.g., http://your-app.test/google/callback).

Debugging

  • Enable Debugging:
    $client->setDeveloperKey('YOUR_DEBUG_KEY'); // For API key-based services
    $client->setApplicationName('Debug Mode');
    
  • Log Token Errors:
    try {
        $client->fetchAccessTokenWithAssertion();
    } catch (Exception $e) {
        Log::error('Google Auth Error: ' . $e->getMessage());
    }
    

Extension Points

  1. 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;
    });
    
  2. Event Listeners Listen for token refreshes:

    event(new GoogleTokenRefreshed($client->getAccessToken()));
    
  3. 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}"),
            ];
        }
    }
    

Performance Tips

  • Batch Requests: Use Google_Service_Drive->files->listFiles() with pageSize and pageToken for pagination.
  • Lazy Loading: Load only required fields:
    $optParams = ['fields' => 'files(id, name, createdTime)'];
    $results = $service->files->listFiles($optParams);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky