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

Vk Laravel Package

baks-dev/vk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require baks-dev/vk
    php artisan vendor:publish --provider="BaksDev\Vk\VkServiceProvider" --tag="config"
    
    • Publishes the default config file to config/vk.php.
  2. Configuration:

    • Edit config/vk.php with your VK API credentials (client ID, client secret, redirect URI, etc.).
    • Set default API version (e.g., v5.131).
  3. First Use Case: Fetch basic user info via the CLI or a controller:

    use BaksDev\Vk\VkClient;
    
    $client = app(VkClient::class);
    $user = $client->api()->users()->get(['user_ids' => '123456789']);
    dd($user);
    

Key Files to Review

  • config/vk.php: Default configuration.
  • src/VkClient.php: Core client class.
  • src/Exceptions/: Custom exceptions (e.g., VkApiException).
  • tests/VkTestCase.php: Test patterns for integration.

Implementation Patterns

Workflows

  1. Authentication:

    • Use OAuth2 for user authorization:
      $authUrl = $client->oauth()->getAuthUrl(['scope' => 'wall,photos']);
      // Redirect user to $authUrl, then handle callback:
      $accessToken = $client->oauth()->handleCallback($request);
      $client->setAccessToken($accessToken);
      
    • Store tokens in the database or session (e.g., via Laravel’s HasApiTokens trait if provided).
  2. API Calls:

    • Method Chaining:
      $client->api()
            ->users()
            ->get(['fields' => 'city,country'], ['user_id' => auth()->id());
      
    • Batch Requests:
      $batch = $client->batch();
      $batch->add('users.get', ['user_ids' => '1,2,3']);
      $batch->add('photos.get', ['owner_id' => '1', 'album_id' => 'profile']);
      $results = $batch->execute();
      
  3. Webhooks:

    • Configure webhooks via the VkWebhook facade:
      $webhook = app(VkWebhook::class);
      $webhook->subscribe(['type' => 'message_new'], route('vk.webhook'));
      
  4. Uploads:

    • Handle file uploads (e.g., photos, docs):
      $photo = $client->upload()->photos()->save('path/to/image.jpg', [
          'album_id' => 'profile',
          'group_id' => 123456789,
      ]);
      

Integration Tips

  • Laravel Services: Bind the client to the container in AppServiceProvider:
    $this->app->singleton(VkClient::class, function () {
        return new VkClient(config('vk'));
    });
    
  • Middleware: Create middleware to attach the VkClient to requests:
    public function handle(Request $request, Closure $next) {
        $request->merge(['vk' => app(VkClient::class)]);
        return $next($request);
    }
    
  • Events: Listen for VK events (e.g., Vk\Events\AuthSuccess) if the package emits them.

Gotchas and Tips

Pitfalls

  1. Rate Limits:

    • VK enforces strict rate limits (e.g., 3 API calls/sec by default). Cache responses aggressively:
      $user = Cache::remember("vk_user_{$userId}", now()->addMinutes(5), function () use ($client, $userId) {
          return $client->api()->users()->get(['user_ids' => $userId]);
      });
      
    • Use the VkRateLimiter middleware if provided.
  2. Token Expiry:

    • Refresh tokens silently fail if not handled. Implement a retry mechanism:
      try {
          $response = $client->api()->users()->get(...);
      } catch (\BaksDev\Vk\Exceptions\TokenExpiredException $e) {
          $client->oauth()->refreshToken($refreshToken);
          return $this->handle($request);
      }
      
  3. Locale/Encoding:

    • VK returns data in UTF-8, but some legacy systems may misinterpret it. Ensure your Laravel app uses:
      'default_locale' => 'en_US.UTF-8',
      
      in app/config/app.php.
  4. Deprecated Methods:

    • The package may wrap deprecated VK API methods. Check the VK API changelog and update calls if needed.

Debugging

  • Enable Logging: Add to config/vk.php:

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

    Logs will appear in storage/logs/vk.log.

  • HTTP Client Inspection: Use Laravel’s tap to inspect raw responses:

    $response = $client->api()->users()->get(...)->tap(function ($response) {
        \Log::debug('Raw VK response:', $response->getData());
    });
    

Extension Points

  1. Custom API Methods: Extend the client to add missing methods:

    namespace App\Services\Vk;
    
    use BaksDev\Vk\VkClient;
    
    class ExtendedVkClient extends VkClient {
        public function customMethod(array $params) {
            return $this->callApi('custom.method', $params);
        }
    }
    
  2. Response Transformers: Override response handling in a service:

    $client->setResponseTransformer(function ($response) {
        return collect($response['response'])->map(fn ($item) => [
            'id' => $item['id'],
            'formatted_name' => "{$item['first_name']} {$item['last_name']}",
        ]);
    });
    
  3. Testing: Mock the client in tests:

    $mockClient = Mockery::mock(VkClient::class);
    $mockClient->shouldReceive('api')->andReturnSelf();
    $mockClient->shouldReceive('users->get')->andReturn(['response' => [...]]);
    $this->app->instance(VkClient::class, $mockClient);
    

Config Quirks

  • Environment Variables: Use .env for sensitive data:
    VK_CLIENT_ID=your_id
    VK_CLIENT_SECRET=your_secret
    VK_REDIRECT_URI=http://your-app.com/vk/callback
    
  • API Version: Always pin the VK API version in config/vk.php to avoid breaking changes:
    'api_version' => '5.131', // Use the latest stable version
    
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.
monarobase/country-list
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity