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).
Enable the Bundle
Add to config/bundles.php:
return [
// ...
AiloveDev\VKBundle\VKBundle::class => ['all' => true],
];
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
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
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>
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.
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();
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);
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
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');
}
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"
}
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
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
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);
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'));
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']
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'
]);
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
]);
How can I help you explore Laravel packages today?