Skip to content

Latest commit

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

VK ID (OAuth 2.1 + PKCE)

Latest Stable VersionTotal DownloadsLatest Unstable VersionLicensePHP Version Require

На Русском

composer require movemoveapp/vkid

Register an application

Create a new VK ID application at id.vk.ru. Make sure you specify the correct redirect URI (must match exactly with the one in your config).

Installation & Basic Usage

Please see the Base Installation Guide first, then follow the VK ID-specific instructions below.

Add configuration to config/services.php

'vkid' => [
'client_id' => env('VKID_CLIENT_ID'),
'client_secret' => env('VKID_CLIENT_SECRET'),
'redirect' => env('VKID_REDIRECT_URI'),
// --- Extended configuration ---'scopes' => env('VKID_SCOPES', ['email']), // default: ['email'], supports ['email','phone']'pkce_ttl' => env('VKID_PKCE_TTL', 10), // minutes to store code_verifier'cache_store' => env('VKID_CACHE_STORE', 'redis'), // cache store for PKCE verifier'cache_prefix' => env('VKID_CACHE_PREFIX', 'socialite:vkid:pkce:'),
'api_version' => env('VKID_API_VERSION', '5.199'), // VK API version
],

Add provider event listener

Laravel 11+

Since Laravel 11 removed EventServiceProvider, use the Event facade in your AppServiceProvider@boot:

useIlluminate\Support\Facades\Event;
useSocialiteProviders\Manager\SocialiteWasCalled;
useMoveMoveApp\VKID\VKIDExtendSocialite;
publicfunctionboot(): void
{
Event::listen(SocialiteWasCalled::class, [VKIDExtendSocialite::class, 'handle']);
}
Laravel 10 or below Add the listener in your `app/Providers/EventServiceProvider.php`. See the [Base Installation Guide](https://socialiteproviders.com/usage/) for detailed instructions.
protected$listen = [
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
MoveMoveApp\VKID\VKIDExtendSocialite::class.'@handle',
],
];

Usage

You can now use the driver as usual with Socialite:

return Socialite::driver('vkid')->redirect();

For extended scopes (e.g. apps with Business Account permission):

return Socialite::driver('vkid')
->scopes(['email', 'phone'])
->redirect();

Handling the callback:

try {
$vkUser = Socialite::driver('vkid')->user();
// Typical fields:// $vkUser->getId(), getNickname(), getName(), getEmail(), getAvatar()// Optional phone (if scope=phone and app has permission):// $vkUser->user['phone'] ?? null// Your app logic:$localUser = User::firstOrCreate(
['email' => $vkUser->getEmail() ?? "vk_{$vkUser->getId()}@example.local"],
['name' => $vkUser->getName()]
);
Auth::login($localUser);
returnredirect()->intended('/');
} catch (\Laravel\Socialite\Two\InvalidStateException$e) {
// Thrown when PKCE verifier expired (user waited too long)returnredirect()->route('login')->with('auth_error', 'Authorization expired. Please try again.');
} catch (\RuntimeException$e) {
// Thrown when cache store is unavailable/misconfiguredreport($e);
returnredirect()->route('login')->with('auth_error', 'Temporary VK ID authorization error.');
} catch (\Throwable$e) {
report($e);
returnredirect()->route('login')->with('auth_error', 'Unexpected VK ID login error.');
}

Returned User fields

FieldDescription
idVK user ID
nicknamescreen_name (if present)
nameFirst + last name
emailfrom id_token (if scope=email)
avatarURL to 200px profile photo
phonefrom id_token (if scope=phone and granted)

Exception Reference

ExceptionCauseRecommended handling
Laravel\Socialite\Two\InvalidStateException- state or PKCE verifier missing or expired- user waited longer than pkce_ttl minutes before pressing “Allow”Ask user to restart login. Show message like “Authorization expired. Please try again.”
RuntimeException("VKID PKCE cache failure")Cache store misconfigured or unavailable (e.g., Redis down)Log and retry later. Typically a server-side infra issue.
RuntimeException("VKID PKCE cache failure: unable to persist code_verifier")Misconfigured cache_store or permission issue writing PKCE stateEnsure correct cache driver in config/cache.php
Any other exceptionNetworking or unexpected JSON formatGeneric fallback “VK ID login failed”

All exceptions extend base \Throwable and can be caught globally in your app’s Handler.

Extended Configuration Options

KeyTypeDefaultDescription
`client_idstringVK App ID
`client_secretstringVK App secret
`redirectstringFull callback URL (must match app settings)
`scopesarray['email']Default OAuth scopes
`pkce_ttlint10Time in minutes to store PKCE verifier
`cache_storestring'redis'Cache store for PKCE (see config/cache.php)
`cache_prefixstring'socialite:vkid:pkce:'Prefix for PKCE keys
`api_versionstring'5.199'VK API version for users.get

Example .env

VKID_CLIENT_ID=1234567VKID_CLIENT_SECRET=secretkeyVKID_REDIRECT_URI=https://your-app.com/auth/vkid/callbackVKID_SCOPES="['email','phone']"VKID_PKCE_TTL=10VKID_CACHE_STORE=redisVKID_CACHE_PREFIX=socialite:vkid:pkce:VKID_API_VERSION=5.199

Example User Flow Diagram

Client → https://id.vk.ru/authorize?response_type=code&state=XYZ...
↳ Redirects user back to /auth/vkid/callback?code=...&state=XYZ
Provider → Exchanges code for tokens (with code_verifier)
↳ Fetches user profile via api.vk.com/method/users.get
App → Creates/logs in user, handles avatar/email/phone sync

Reference

About

VK ID OAuth 2.1 (id.vk.ru) Socialite provider with PKCE (cache-based, stateless-friendly).

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages