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

ailove-dev/vk-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ailove-dev/vk-bundle
    

    Ensure ailove-dev/vk-php-sdk and ailove-dev/abstract-social-bundle are also installed (handled automatically via require).

  2. Enable the Bundle Add to config/bundles.php:

    return [
        // ...
        AiloveDev\VKBundle\VKBundle::class => ['all' => true],
    ];
    
  3. Configure FOSUserBundle Ensure FOS\UserBundle is installed and configured. Update config/packages/security.yaml to include the chain provider:

    security:
        providers:
            chain_provider:
                chain:
                    providers: [fos_userbundle, vk_provider]
            fos_userbundle:
                id: fos_user.user_provider.username_email
            vk_provider:
                id: vk.user.provider
    
  4. Configure VKBundle Add to config/packages/vk.yaml (create if missing):

    vk:
        app_id: '%env(VK_APP_ID)%'          # Your VK app ID
        secret: '%env(VK_SECRET)%'          # Your VK app secret
        redirect_uri: '%env(VK_REDIRECT_URI)%'  # e.g., 'https://your-app.com/connect/vk/check'
        scope: ['email', 'offline']         # Requested permissions
    
  5. First Use Case: Login Button Add a route in config/routes.yaml:

    vk_login:
        path: /connect/vk/check
        controller: AiloveDev\VKBundle\Controller\VKController::checkCallback
    

    Create a login button in your template:

    <a href="{{ path('vk_login') }}">Login with VK</a>
    

Implementation Patterns

Workflow: OAuth Flow

  1. Initiate Login Redirect users to VK’s OAuth endpoint via the bundle’s built-in route (/connect/vk/check). The bundle handles the initial redirect to VK’s authorization page.

  2. Callback Handling VK redirects back to your redirect_uri with a code. The VKController::checkCallback processes this code to fetch user data:

    // Inside your controller or service
    $vkUser = $this->get('vk.user.provider')->connect();
    
  3. User Registration/Association The bundle extends FOSUserBundle’s user provider. If the VK user doesn’t exist locally, create a new user:

    $user = new User();
    $user->setUsername($vkData['email']);
    $user->setEmail($vkData['email']);
    $user->setVkId($vkData['id']); // Custom field to track VK ID
    $user->setPassword(''); // FOSUserBundle handles password-less login
    $userManager->updateUser($user);
    
  4. Post-Login Logic Use Symfony’s security events to handle post-login actions:

    # config/packages/security.yaml
    security:
        firewalls:
            main:
                form_login:
                    check_path: vk_login_check
                remember_me:
                    secret: '%kernel.secret%'
                logout:
                    path: fos_user_security_logout
    

Integration Tips

  • Custom User Fields Extend your User entity to include VK-specific fields (e.g., vkId, firstName, lastName):

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $vkId;
    
  • Token Refresh Use the offline scope to handle token expiration. Store the access_token and refresh_token in the user session or database:

    $vkService = $this->get('vk.api');
    $vkService->setAccessToken($refreshToken); // Refresh token logic
    
  • Error Handling Wrap VK API calls in try-catch blocks to handle rate limits or invalid tokens:

    try {
        $userData = $vkService->api('users.get', ['user_ids' => $vkId]);
    } catch (\AiloveDev\VKBundle\Exception\VKException $e) {
        $this->addFlash('error', 'Failed to fetch VK data: ' . $e->getMessage());
        return $this->redirectToRoute('homepage');
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Dependencies The bundle relies on dev-master branches for ailove-dev/vk-php-sdk and abstract-social-bundle. Pin versions explicitly in composer.json to avoid breaking changes:

    "require": {
        "ailove-dev/vk-php-sdk": "dev-master",
        "ailove-dev/abstract-social-bundle": "dev-master"
    }
    
  2. Missing Redirect URI Configuration VK’s OAuth requires an exact match for the redirect_uri. Test locally with http://localhost/connect/vk/check and update .env:

    VK_REDIRECT_URI=http://localhost/connect/vk/check
    
  3. FOSUserBundle Conflicts Ensure fos_userbundle is not configured to use email as the primary login field if you’re using VK’s email scope. Override the provider in security.yaml:

    fos_userbundle:
        id: fos_user.user_provider.username  # Use username instead of email
    
  4. Token Storage The bundle doesn’t persist tokens by default. Manually save access_token and refresh_token to the user entity or session:

    $user->setVkAccessToken($accessToken);
    $user->setVkRefreshToken($refreshToken);
    $userManager->updateUser($user);
    

Debugging

  • Enable VK Debugging Add display=1 to the VK API URL to see raw responses:

    $vkService->api('users.get', ['user_ids' => $vkId, 'display' => 1]);
    
  • Check VK App Settings Ensure your VK app’s Valid Redirect URIs include all possible routes (e.g., https://your-app.com/connect/vk/check, http://localhost/connect/vk/check).

  • Log VK Responses Extend the VKApi service to log responses:

    $vkService = $this->get('vk.api');
    $vkService->setLogger($this->get('logger'));
    

Extension Points

  1. Custom User Provider Override the default vk.user.provider to add logic (e.g., role assignment):

    services:
        app.vk_user_provider:
            class: App\Security\VKUserProvider
            arguments: ['@fos_user.user_manager', '@vk.api']
            tags: ['security.user_provider']
    
  2. Add Custom VK Fields Extend the VKUser class to fetch additional data (e.g., city, bdate):

    // In your service
    $vkData = $vkService->api('users.get', [
        'user_ids' => $vkId,
        'fields' => 'city,bdate,photo_max'
    ]);
    
  3. Webhook Integration Use VK’s API to set up webhooks for real-time updates (e.g., user profile changes). Example:

    $vkService->api('account.registerDevice', [
        'user_id' => $vkId,
        'settings' => json_encode(['event_id' => 'new_message'}),
        'access_token' => $accessToken
    ]);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui