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 Custom Laravel Package

kunstmaan/google-api-custom

Laravel/PHP wrapper for Google APIs with custom configuration support. Helps integrate Google services (e.g., analytics or other endpoints) using a simplified client setup, credential handling, and service initialization geared toward app-specific needs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Package:

    composer require kunstmaan/google-api-custom
    
  2. Publish the Configuration:

    php artisan vendor:publish --provider="Kunstmaan\GoogleApiCustom\GoogleApiCustomServiceProvider"
    

    This creates config/google-api-custom.php. Configure your Google API credentials (e.g., service account JSON key) and default scopes:

    return [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'key_file' => base_path('path/to/credentials.json'),
        'scopes' => [
            'https://www.googleapis.com/auth/drive',
        ],
    ];
    
  3. Register the Service Provider (if not auto-discovered): Add to config/app.php under providers:

    Kunstmaan\GoogleApiCustom\GoogleApiCustomServiceProvider::class,
    
  4. First API Call (Google Drive Example): Use the facade or dependency injection:

    // Option 1: Facade (if registered)
    $files = \Google::service('Drive')->files()->listFiles();
    
    // Option 2: Dependency Injection (recommended)
    use Kunstmaan\GoogleApiCustom\GoogleClient;
    
    class MyController {
        public function __construct(private GoogleClient $googleClient) {}
    
        public function index() {
            $drive = $this->googleClient->service('Drive');
            $files = $drive->files->listFiles();
            return response()->json($files);
        }
    }
    
  5. Verify Credentials: Test with a simple API call (e.g., list files) and check for auth errors. Use Laravel Tinker to debug:

    php artisan tinker
    >>> $drive = app(Kunstmaan\GoogleApiCustom\GoogleClient::class)->service('Drive');
    >>> $drive->files->listFiles();
    

Implementation Patterns

Core Workflows

1. Service Initialization

  • Pattern: Initialize the Google client once per request (singleton) and reuse across controllers/services.
  • Example:
    // In a service class
    public function __construct(private GoogleClient $googleClient) {}
    
    public function syncDriveFiles() {
        $drive = $this->googleClient->service('Drive');
        // Use $drive->files->* methods
    }
    

2. Environment-Specific Configs

  • Override configs per environment (e.g., config/google-api-custom.php):
    'scopes' => env('APP_ENV') === 'local'
        ? ['https://www.googleapis.com/auth/drive.readonly']
        : ['https://www.googleapis.com/auth/drive'],
    
  • Use .env for sensitive data:
    GOOGLE_CLIENT_ID=your_client_id
    GOOGLE_CLIENT_SECRET=your_secret
    GOOGLE_KEY_FILE=/path/to/credentials.json
    

3. API-Specific Services

  • Create dedicated service classes for each Google API (e.g., Drive, Calendar) to encapsulate logic:
    class GoogleDriveService {
        public function __construct(private GoogleClient $client) {}
    
        public function listFiles(string $query = '') {
            return $this->client->service('Drive')->files->listFiles([
                'q' => $query,
                'fields' => 'files(id, name, mimeType)',
            ]);
        }
    }
    

4. Dependency Injection

  • Prefer constructor injection over facades for testability:
    // Testable with mocks
    $service = new GoogleDriveService($mockGoogleClient);
    

5. Error Handling

  • Wrap API calls in try-catch blocks to handle Google-specific exceptions:
    try {
        $response = $this->googleClient->service('Drive')->files->get('fileId');
    } catch (\Google_Service_Exception $e) {
        Log::error('Google API error: ' . $e->getMessage());
        throw new \RuntimeException('Failed to fetch file', 0, $e);
    }
    

Integration Tips

1. Laravel Facades

  • Register a facade for convenience (add to config/app.php):
    'aliases' => [
        'Google' => Kunstmaan\GoogleApiCustom\Facades\Google::class,
    ],
    
  • Usage:
    $files = \Google::service('Drive')->files->listFiles();
    

2. Middleware for Auth

  • Create middleware to validate Google auth tokens (e.g., for webhooks):
    namespace App\Http\Middleware;
    
    use Closure;
    use Kunstmaan\GoogleApiCustom\GoogleClient;
    
    class ValidateGoogleAuth {
        public function __construct(private GoogleClient $googleClient) {}
    
        public function handle($request, Closure $next) {
            $token = $request->bearerToken();
            if (!$this->googleClient->verifyIdToken($token)) {
                abort(401, 'Invalid Google token');
            }
            return $next($request);
        }
    }
    

3. Caching Responses

  • Cache frequent API responses (e.g., user data) using Laravel’s cache:
    $cacheKey = 'google_drive_files';
    $files = Cache::remember($cacheKey, now()->addHours(1), function () {
        return $this->googleClient->service('Drive')->files->listFiles();
    });
    

4. Testing

  • Mock the GoogleClient in tests:
    use Kunstmaan\GoogleApiCustom\GoogleClient;
    use Mockery;
    
    $mockClient = Mockery::mock(GoogleClient::class);
    $mockClient->shouldReceive('service')
        ->with('Drive')
        ->andReturn($mockDriveService);
    
    $service = new GoogleDriveService($mockClient);
    

5. Artisan Commands

  • Use the package in Artisan commands for CLI-driven tasks (e.g., syncing data):
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Kunstmaan\GoogleApiCustom\GoogleClient;
    
    class SyncGoogleDrive extends Command {
        protected $googleClient;
    
        public function __construct(GoogleClient $googleClient) {
            parent::__construct();
            $this->googleClient = $googleClient;
        }
    
        public function handle() {
            $files = $this->googleClient->service('Drive')->files->listFiles();
            // Process files...
        }
    }
    

6. Event Listeners

  • Trigger events after API operations (e.g., GoogleDriveSynced):
    event(new GoogleDriveSynced($files));
    

Gotchas and Tips

Pitfalls

  1. Credential Leaks:

    • Gotcha: Hardcoding credentials in config files or version control.
    • Fix: Use Laravel’s .env and never commit credentials.json to Git. Add it to .gitignore:
      credentials.json
      
    • Tip: Use environment variables for paths:
      'key_file' => env('GOOGLE_KEY_FILE_PATH'),
      
  2. Scope Mismatches:

    • Gotcha: Missing or incorrect OAuth scopes causing 403 Forbidden errors.
    • Fix: Double-check scopes in config/google-api-custom.php and Google Cloud Console. Example for Drive:
      'scopes' => [
          'https://www.googleapis.com/auth/drive',
          'https://www.googleapis.com/auth/drive.readonly',
      ],
      
  3. PHP Version Conflicts:

    • Gotcha: PHP 8.x deprecation warnings (e.g., array_merge signatures) despite fixes in the package.
    • Fix: Pin PHP version in composer.json:
      "config": {
          "platform": {
              "php": "8.2"
          }
      }
      
    • Tip: Test with php -l or phpstan to catch deprecations early.
  4. Rate Limiting:

    • Gotcha: Unhandled rate limits (e.g., 429 Too Many Requests) crashing your app.
    • Fix: Implement exponential backoff in a middleware or service:
      use GuzzleHttp\Exception\RequestException;
      use Symfony\Component\HttpKernel\Exception\HttpException;
      
      try {
          $response = $this->googleClient->service('Drive')->files->listFiles();
      } catch (RequestException $e) {
          if ($e->getCode() === 429) {
              sleep(2); // Retry after delay
              return $this->handle();
          }
          throw new HttpException(500, 'Google API error');
      }
      
  5. Service Account vs. OAuth:

    • Gotcha: Confusing service account credentials with OAuth client IDs.
    • Fix: Use service accounts for server-to-server apps (e.g., Drive syncs) and OAuth for user logins.
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.
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views