How OAuth 2.0 Authorization Code Flow works
masterThe Authorization Code Flow is used for server-side applications. It is a two-step process:
- Obtain an authorization code: Redirect the user to the VK authorization page using
VKOAuth::getAuthorizeUrl()withVKOAuthResponseType::CODE. - Exchange the code for an access token: Once the user is redirected back to your
redirect_uriwith acodeparameter, useVKOAuth::getAccessToken()to retrieve the token.
Use VKOAuthUserScope for user access and VKOAuthGroupScope for community access.
// 1. Get the authorization URL
$oauth = new \VK\OAuth\VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';
$display = \VK\OAuth\VKOAuthDisplay::PAGE;
$scope = [\VK\OAuth\Scopes\VKOAuthUserScope::WALL, \VK\OAuth\Scopes\VKOAuthUserScope::GROUPS];
$state = 'secret_state_code';
$browser_url = $oauth->getAuthorizeUrl(\VK\OAuth\VKOAuthResponseType::CODE, $client_id, $redirect_uri, $display, $scope, $state);
// 2. Exchange code for token (after redirect)
$response = $oauth->getAccessToken($client_id, $client_secret, $redirect_uri, $code);
$access_token = $response['access_token'];