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

dktw/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 is a Symfony bundle, but can be adapted for Laravel via Laravel Symfony Bridge or manually).

  2. Credentials Setup

    • Generate a credentials.json file from the Google Cloud Console.
    • Place it in config/google_api_bundle/credentials.json (or configure a custom path in config/google_api.php).
  3. Basic Configuration Add minimal config in config/google_api.php:

    return [
        'scopes' => ['https://www.googleapis.com/auth/drive'], // Replace with your required scopes
        'credentials_file' => env('GOOGLE_CREDENTIALS_PATH', base_path('config/google_api_bundle/credentials.json')),
        'token_file' => storage_path('app/google_tokens.json'), // Persist tokens here
        'application_name' => 'Your Laravel App',
    ];
    
  4. First Use Case Inject the Google_Client service into a controller or service:

    use Google\Client;
    
    class ExampleController extends Controller
    {
        public function __construct(private Client $googleClient) {}
    
        public function index()
        {
            $service = new Google\Service\Drive($this->googleClient);
            $files = $service->files->listFiles();
            return response()->json($files);
        }
    }
    

Implementation Patterns

Dependency Injection

  • Service Binding: Register the bundle’s service in Laravel’s container (if not using Symfony Bridge):

    $this->app->bind('google.client', function ($app) {
        return new Google\Client([
            'credentials' => $app['config']['google_api.credentials_file'],
            'scopes' => $app['config']['google_api.scopes'],
            'auth_key_file' => $app['config']['google_api.credentials_file'],
            'access_type' => 'offline',
            'approval_prompt' => 'force',
        ]);
    });
    
  • Lazy Initialization: Use app('google.client') to defer client initialization until first use (avoids early auth prompts).

Workflows

  1. Auth Flow

    • Handle OAuth 2.0 manually or use middleware to pre-authenticate:
      $this->googleClient->setAccessToken($token);
      $this->googleClient->setAuthConfig($config);
      
  2. Service Integration

    • Instantiate Google services dynamically:
      $serviceName = request('service', 'drive');
      $serviceClass = "Google\\Service\\$serviceName";
      $service = new $serviceClass($this->googleClient);
      
  3. Token Persistence

    • Save/load tokens to/from token_file:
      $this->googleClient->setAccessToken(file_get_contents(storage_path('google_tokens.json')));
      
  4. Batch Operations

    • Use Google\Batch for parallel API calls:
      $batch = new Google\Batch($this->googleClient);
      $batch->add($service->files->create(...));
      

Integration Tips

  • Laravel Events: Trigger events on auth success/failure:
    $this->googleClient->setAuthConfig($config);
    event(new GoogleAuthSuccess($this->googleClient->getAccessToken()));
    
  • Caching: Cache API responses with Laravel’s cache:
    return Cache::remember("google_{$endpoint}", now()->addHours(1), function () use ($service) {
        return $service->files->listFiles()->getFiles();
    });
    
  • Queue Jobs: Offload long-running API calls to queues:
    GoogleApiJob::dispatch($this->googleClient, 'drive', 'files.list')->onQueue('google');
    

Gotchas and Tips

Pitfalls

  1. Credentials Path

    • Hardcoding paths (e.g., config/google_api_bundle/) may fail in shared hosting. Use env() or Laravel’s config_path():
      'credentials_file' => env('GOOGLE_CREDENTIALS_PATH', config_path('google_api_bundle/credentials.json')),
      
  2. Token File Permissions

    • Ensure token_file is writable by the web server:
      chmod 644 storage/app/google_tokens.json
      
  3. Scopes Misconfiguration

    • Missing or incorrect scopes will cause Google_Auth_Exception. Validate scopes against Google’s API docs.
  4. Service Descriptor Caching

    • Clear Laravel’s config cache after changing google_api.php:
      php artisan config:clear
      
  5. Deprecated Methods

    • The bundle wraps google-api-php-client v1.x. Upgrade to v2.x if using newer APIs (adjust service classes accordingly).

Debugging

  • Enable Debugging Add to config/google_api.php:

    'debug' => env('APP_DEBUG', false),
    

    This enables verbose logging for OAuth flows.

  • Token Errors If tokens expire silently, log the token_file contents:

    file_put_contents(storage_path('logs/google_token_debug.log'), file_get_contents($tokenFile), FILE_APPEND);
    
  • CORS Issues Ensure your Google Cloud project’s APIs & Services > Credentials allows your Laravel app’s domain.

Extension Points

  1. Custom Auth Providers Extend the client with custom auth logic (e.g., JWT):

    $this->googleClient->setAuthConfig([
        'client_id' => 'custom',
        'client_secret' => 'custom',
        'auth_provider_x509_cert_url' => 'https://example.com/jwt.pem',
    ]);
    
  2. Middleware for Auth Create middleware to auto-refresh tokens:

    public function handle($request, Closure $next)
    {
        if ($this->googleClient->isAccessTokenExpired()) {
            $this->googleClient->fetchAccessTokenWithRefreshToken($this->googleClient->getRefreshToken());
        }
        return $next($request);
    }
    
  3. Dynamic Scopes Load scopes from a database or user roles:

    $scopes = Scope::where('user_id', auth()->id())->pluck('scope')->toArray();
    $this->googleClient->setScopes($scopes);
    
  4. Testing Mock the client in tests:

    $mockClient = Mockery::mock(Client::class);
    $mockClient->shouldReceive('getAccessToken')->andReturn(['access_token' => 'mock_token']);
    $this->app->instance(Client::class, $mockClient);
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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