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

Vkontakte Laravel Package

socialiteproviders/vkontakte

Laravel Socialite provider for VKontakte (vk.ru). Install via Composer, add vkontakte credentials to config/services.php, register the SocialiteWasCalled listener, then authenticate with Socialite::driver('vkontakte'). Returns id, nickname, name, email, avatar.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require socialiteproviders/vkontakte
    

    Ensure socialiteproviders/vkontakte is listed in config/auth.php under providers (if using Laravel's auth scaffolding).

  2. Service Provider Registration: Add to config/app.php under providers:

    SocialiteProviders\Manager\ServiceProvider::class,
    SocialiteProviders\VKontakte\VKontakteExtendSocialite::class,
    
  3. First Use Case: Configure the provider in config/services.php:

    'vkontakte' => [
        'client_id' => env('VKONTAKE_CLIENT_ID'),
        'client_secret' => env('VKONTAKE_CLIENT_SECRET'),
        'redirect' => env('VKONTAKE_REDIRECT_URI', 'http://your-app.test/auth/vkontakte/callback'),
    ],
    

    Add routes in routes/web.php:

    Route::get('/auth/vkontakte', [AuthController::class, 'redirectToVKontakte'])->name('auth.vkontakte');
    Route::get('/auth/vkontakte/callback', [AuthController::class, 'handleVKontakteCallback']);
    
  4. Basic Controller Usage:

    use Laravel\Socialite\Facades\Socialite;
    
    public function redirectToVKontakte()
    {
        return Socialite::driver('vkontakte')->redirect();
    }
    
    public function handleVKontakteCallback()
    {
        $user = Socialite::driver('vkontakte')->user();
        // Handle user data (e.g., create/update in DB)
    }
    

Implementation Patterns

Workflows

  1. User Authentication Flow:

    • Redirect to VKontakte for OAuth:
      return Socialite::driver('vkontakte')->scopes(['email'])->redirect();
      
    • Handle callback with user data:
      $vkontakteUser = Socialite::driver('vkontakte')->user();
      $email = $vkontakteUser->email; // If requested in scopes
      $name = $vkontakteUser->name;
      $avatar = $vkontakteUser->avatar_original;
      
  2. Data Mapping: Use the map() method to transform raw data into your user model:

    $user = Socialite::driver('vkontakte')->user()->map([
        'nickname' => 'vkontakte_id',
        'name' => function($user) {
            return $user->name ?? $user->first_name . ' ' . $user->last_name;
        },
    ]);
    
  3. Scopes and Permissions: Request additional permissions (e.g., email, offline):

    Socialite::driver('vkontakte')->scopes(['email', 'offline'])->redirect();
    

    Note: VKontakte requires email scope to access email addresses.

  4. State Management: Use Laravel's built-in CSRF protection or add custom state:

    Socialite::driver('vkontakte')->state('custom_state')->redirect();
    

Integration Tips

  • Laravel Auth Scaffolding: Extend AuthController to handle VKontakte login:

    public function handleProviderCallback($provider)
    {
        try {
            $user = Socialite::driver($provider)->user();
            // Logic to find/create user
            Auth::login($user, true);
            return redirect('/home');
        } catch (\Exception $e) {
            return redirect('/login')->with('error', $e->getMessage());
        }
    }
    
  • User Model Binding: Bind the provider user to your model:

    $vkontakteUser->token; // Access token for API calls
    $vkontakteUser->user['id']; // VKontakte user ID
    
  • API Calls: Use the access token to call VKontakte API:

    $client = new \GuzzleHttp\Client();
    $response = $client->get('https://api.vk.com/method/users.get', [
        'query' => [
            'user_ids' => $vkontakteUser->id,
            'access_token' => $vkontakteUser->token,
            'v' => '5.131',
        ],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Scopes Limitation:

    • VKontakte requires explicit scopes (e.g., email). Without email, the user()->email will return null.
    • Scopes must be requested during the initial redirect; you cannot request them later.
  2. Token Expiry:

    • Access tokens expire (typically 24 hours for non-offline scopes). Use the offline scope to get a long-lived token:
      Socialite::driver('vkontakte')->scopes(['offline'])->redirect();
      
    • Store the refresh token ($vkontakteUser->refreshToken) to renew access tokens.
  3. User Data Inconsistency:

    • VKontakte may return incomplete user data (e.g., null for email or name). Handle missing fields gracefully:
      $email = $vkontakteUser->email ?? 'user@example.com'; // Fallback
      
  4. Redirect URI Mismatch:

    • Ensure the redirect URI in config/services.php matches the callback route exactly (including http vs https).
  5. API Version (v):

    • VKontakte API methods require a v parameter (e.g., v=5.131). The package handles this internally, but ensure you’re using the latest stable version.

Debugging

  • Enable Socialite Debugging: Add to config/socialite.php:

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

    This logs OAuth errors and responses.

  • Check VKontakte Developer Console: Verify your app’s client_id and client_secret are correct in VKontakte Developer.

  • Token Validation: If tokens fail silently, validate them manually:

    $response = $client->get('https://oauth.vk.com/access_token_info', [
        'query' => [
            'access_token' => $vkontakteUser->token,
            'v' => '5.131',
        ],
    ]);
    

Extension Points

  1. Custom User Fields: Extend the User model to include VKontakte-specific fields:

    public function vkontakte()
    {
        return $this->morphOne(VKontakteAccount::class, 'accountable');
    }
    
  2. Custom Provider Logic: Override the provider’s behavior by extending VKontakteExtendSocialite:

    namespace App\Providers;
    
    use SocialiteProviders\VKontakte\VKontakteExtendSocialite as BaseProvider;
    
    class VKontakteExtendSocialite extends BaseProvider
    {
        protected function getUserByToken($token)
        {
            // Custom logic (e.g., cache user data)
        }
    }
    

    Register the provider in AppServiceProvider:

    Socialite::extend('vkontakte', function ($app) {
        return $app->make(\App\Providers\VKontakteExtendSocialite::class);
    });
    
  3. Webhooks: Use VKontakte’s webhooks to listen for user events (e.g., profile updates). Store the secret in .env and verify signatures:

    $secret = env('VKONTAKE_WEBHOOK_SECRET');
    $signature = $_SERVER['HTTP_X_VK_WEBHOOK_SIGNATURE'];
    $payload = file_get_contents('php://input');
    if (!hash_equals($signature, hash_hmac('sha256', $payload, $secret))) {
        abort(403);
    }
    
  4. Rate Limiting: VKontakte API has rate limits (e.g., 3 calls/second). Implement queued jobs for API calls:

    dispatch(new FetchVKontakteUserData($vkontakteUser->token))->delay(now()->addSeconds(1));
    
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.
terminal42/code-quality-tools
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