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

cekurte/google-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the bundle via Composer:

    composer require cekurte/google-api-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Cekurte\GoogleApiBundle\CekurteGoogleApiBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default configuration:

    php bin/console cekurte:google-api:install
    

    Update config/packages/cekurte_google_api.yaml with your Google API credentials (e.g., OAuth 2.0 client ID/secret, service account key).

  3. First Use Case Use the bundle to interact with a Google API (e.g., Google Sheets):

    use Cekurte\GoogleApiBundle\Service\GoogleApiService;
    
    class MyController extends AbstractController
    {
        public function __construct(private GoogleApiService $googleApiService) {}
    
        public function index()
        {
            $client = $this->googleApiService->getClient('sheets', 'v4');
            $service = new Google_Service_Sheets($client);
            $spreadsheet = $service->spreadsheets->get('spreadsheetId');
            return $this->json($spreadsheet);
        }
    }
    

Where to Look First

  • Documentation: Start with Resources/doc/index.md for setup and API usage.
  • Configuration: Check config/packages/cekurte_google_api.yaml for bundle settings.
  • Service Container: Use GoogleApiService to instantiate Google API clients.

Implementation Patterns

Usage Patterns

  1. Service Initialization The bundle provides a centralized way to create Google API clients:

    // Get a client for a specific API (e.g., Sheets, Drive, Calendar)
    $client = $this->googleApiService->getClient('sheets', 'v4');
    $service = new Google_Service_Sheets($client);
    
  2. Authentication Workflows

    • OAuth 2.0: Configure OAuth credentials in config/packages/cekurte_google_api.yaml and use the bundle to handle user authentication flows.
      cekurte_google_api:
          auth:
              oauth:
                  client_id: '%env(GOOGLE_OAUTH_CLIENT_ID)%'
                  client_secret: '%env(GOOGLE_OAUTH_CLIENT_SECRET)%'
                  redirect_uri: '%env(GOOGLE_OAUTH_REDIRECT_URI)%'
      
    • Service Accounts: For server-to-server interactions, use a service account JSON key:
      cekurte_google_api:
          auth:
              service_account:
                  key_file: '%kernel.project_dir%/config/google-service-account.json'
      
  3. API Calls Use the generated Google API service classes (e.g., Google_Service_Sheets) to interact with endpoints:

    $result = $service->spreadsheets->get('spreadsheetId');
    $batchUpdate = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
    $batchUpdate->setRequests([/* ... */]);
    $updatedSpreadsheet = $service->spreadsheets->batchUpdate('spreadsheetId', $batchUpdate);
    
  4. Dependency Injection Inject GoogleApiService into controllers, services, or commands to reuse client initialization logic.

Workflows

  1. User Authentication Flow Redirect users to Google for OAuth authorization:

    $authUrl = $this->googleApiService->getAuthUrl('sheets', 'https://example.com/callback');
    return $this->redirect($authUrl);
    

    Handle the callback to exchange the authorization code for tokens:

    $token = $this->googleApiService->handleAuthCallback('sheets', $code);
    
  2. Batch Operations Use the bundle to handle token refreshes and batch API calls efficiently:

    $client = $this->googleApiService->getClient('sheets', 'v4');
    $client->setUseBatch(true);
    
  3. Error Handling Wrap API calls in try-catch blocks to handle Google API exceptions:

    try {
        $result = $service->spreadsheets->get('spreadsheetId');
    } catch (Google_Service_Exception $e) {
        // Handle API-specific errors (e.g., 404 for non-existent resources)
        $this->addFlash('error', $e->getMessage());
    } catch (Google_Auth_Exception $e) {
        // Handle authentication errors
        $this->addFlash('error', 'Authentication failed');
    }
    

Integration Tips

  1. Environment Variables Store sensitive credentials (e.g., OAuth client secrets, service account keys) in .env:

    GOOGLE_OAUTH_CLIENT_ID=your_client_id
    GOOGLE_OAUTH_CLIENT_SECRET=your_client_secret
    GOOGLE_SERVICE_ACCOUNT_KEY=%kernel.project_dir%/config/google-service-account.json
    
  2. Caching Clients Reuse clients for performance (the bundle manages client lifecycle):

    // Reuse the same client for multiple calls
    $client = $this->googleApiService->getClient('sheets', 'v4');
    $service->spreadsheets->get('spreadsheetId1');
    $service->spreadsheets->get('spreadsheetId2');
    
  3. Custom API Services Extend the bundle to support custom Google APIs not covered by default:

    # config/packages/cekurte_google_api.yaml
    cekurte_google_api:
        apis:
            custom_api:
                version: 'v1'
                class: Google_Service_CustomApi
    

Gotchas and Tips

Pitfalls

  1. Deprecated APIs The bundle may not support the latest Google API versions. Verify compatibility with the Google API PHP Client library.

  2. Service Account Scopes Ensure your service account key has the correct scopes for the API you’re using. For example, for Google Sheets:

    cekurte_google_api:
        auth:
            service_account:
                scopes: ['https://www.googleapis.com/auth/spreadsheets']
    
  3. Token Expiry OAuth tokens expire. Handle token refreshes gracefully:

    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    }
    
  4. Locale/Encoding Issues Google APIs may return data in UTF-8 or other encodings. Normalize responses:

    $response = mb_convert_encoding($response, 'UTF-8', 'auto');
    
  5. Bundle Maturity The bundle has low activity (0 stars, no dependents). Test thoroughly in a staging environment before production use.

Debugging

  1. Enable Debugging Enable Google API client logging to debug issues:

    $client->setDeveloperKey('your_api_key');
    $client->setApplicationName('MyApp/1.0');
    $client->setDebug(true);
    $client->setAccessType('offline');
    
  2. Check HTTP Requests Use tools like Postman or browser dev tools to inspect raw API requests/responses.

  3. Symfony Profiler Use Symfony’s profiler to inspect the GoogleApiService calls and debug performance bottlenecks.

Config Quirks

  1. Default API Configuration The bundle assumes default API configurations (e.g., Sheets API uses v4). Override in config/packages/cekurte_google_api.yaml:

    cekurte_google_api:
        apis:
            sheets:
                version: 'v4'
                class: Google_Service_Sheets
    
  2. Auth Provider Switching The bundle supports both OAuth and service accounts. Ensure your config matches the auth method:

    # OAuth example
    cekurte_google_api:
        auth:
            oauth:
                enabled: true
                service_account: false
    
    # Service account example
    cekurte_google_api:
        auth:
            oauth:
                enabled: false
            service_account:
                enabled: true
    

Extension Points

  1. Custom Client Factories Extend the bundle to support custom client initialization logic:

    // src/Service/CustomGoogleApiService.php
    use Cekurte\GoogleApiBundle\Service\GoogleApiService;
    
    class CustomGoogleApiService extends GoogleApiService
    {
        public function getCustomClient()
        {
            $client = $this->createClient('custom_api', 'v1');
            // Customize client here
            return $client;
        }
    }
    
  2. Event Listeners Listen to bundle events (e.g., google_api.client.created) to intercept client creation:

    // src/EventListener/GoogleApiListener.php
    use
    
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.
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
spatie/mailcoach-vapor