The VK PHP SDK can be installed using Composer by running the following command:
composer require vkcom/vk-php-sdk
Create VKApiClient object using the following code:
$vk = new VKApiClient();
Also you can initialize VKApiClient with different API version and different language like this:
$vk = new VKApiClient('5.73');
$vk = new VKApiClient('5.73', VKLanguage::ENGLISH);
The library provides the authorization flows for user based on OAuth 2.0 protocol implementation in vk.com API. Please read the full
documentation before you start.
OAuth 2.0 Authorization Code Flow allows calling methods from the server side.
This flow includes two steps — obtaining an authorization code and exchanging the code for an access token. Primarily you should obtain the "code" (
manual user access and
manual community access) by redirecting the user to the authorization page using the following method:
Create
VKOAuth object first:
$oauth = new VKOAuth();
$oauth = new VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';;
$display = VKOAuthDisplay::PAGE;
$scope = array(VKOAuthUserScope::WALL, VKOAuthUserScope::GROUPS);
$state = 'secret_state_code';
$browser_url = $oauth->getAuthorizeUrl(VKOAuthResponseType::CODE, $client_id, $redirect_uri, $display, $scope, $state);
$oauth = new VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';;
$display = VKOAuthDisplay::PAGE;
$scope = array(VKOAuthGroupScope::MESSAGES);
$state = 'secret_state_code';
$groups_ids = array(1, 2);
$browser_url = $oauth->getAuthorizeUrl(VKOAuthResponseType::CODE, $client_id, $redirect_uri, $display, $scope, $state, $groups_ids);
User access key and
community access key uses different values inside scope array
After successful authorization user's browser will be redirected to the specified
redirect_uri. Meanwhile the code will be sent as a GET parameter to the specified address:
https://example.com?code=CODE
Then use this method to get the access token:
$oauth = new VKOAuth();
$client_id = 1234567;
$client_secret = 'SDAScasd'
$redirect_uri = 'https://example.com/vk';;
$code = 'CODE';
$response = $oauth->getAccessToken($client_id, $client_secret, $redirect_uri, $code);
$access_token = $response['access_token'];
The
redirect_uri should be the URL that was used to get a code at the first step.
In difference with authorization code flow this flow gives you temporary access key.
Read more about
user access key and
community access key.
First step to get access using Implicit flow is creating VKOauth object:
$oauth = new VKOAuth();
$oauth = new VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';;
$display = VKOAuthDisplay::PAGE;
$scope = array(VKOAuthUserScope::WALL, VKOAuthUserScope::GROUPS);
$state = 'secret_state_code';
$revoke_auth = true;
$browser_url = $oauth->getAuthorizeUrl(VKOAuthResponseType::TOKEN, $client_id, $redirect_uri, $display, $scope, $state, null, $revoke_auth);
If you want to make user getting access anyway, set
revoke_auth as true.
$oauth = new VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';;
$display = VKOAuthDisplay::PAGE;
$scope = array(VKOAuthGroupScope::MESSAGES);
$state = 'secret_state_code';
$groups_ids = array(1, 2);
$browser_url = $oauth->getAuthorizeUrl(VKOAuthResponseType::TOKEN, $client_id, $redirect_uri, $display, $scope, $state, $groups_ids);
Arguments are similar with authorization code flow
After successful authorization user's browser will be redirected to the specified redirect_uri. Meanwhile the access token will be sent as a GET parameter to the specified address:
For
user access key will be:
https://example.com#access_token=533bacf01e11f55b536a565b57531ad114461ae8736d6506a3&expires_in=86400&user_id=8492&state=123456
And for
community access key:
https://example.com#access_token_XXXXXX=533bacf01e11f55b536a565b57531ad114461ae8736d6506a3&expires_in=86400
access_token is your new access token.
expires_in is lifetime of access token in seconds.
user_id is user identifier.
state is string from authorize method.
access_token_
XXXXXX is community access token where XXXXXX is community identifier.
You can find the full list of VK API methods
here.
Example of calling method
users.get:
$vk = new VKApiClient();
$response = $vk->users()->get($access_token, array(
'user_ids' => array(1, 210700286),
'fields' => $array('city', 'photo'),
));
Please read the
full manual before the start.
Call
photos.getMessagesUploadServer to receive an upload address:
$vk = new VKApiClient();
$address = $vk->photos()->getMessagesUploadServer('{access_token}');
Then use
upload() method to send files to the
upload_url address received in the previous step:
$vk = new VKApiClient();
$photo = $vk->request()->upload($address['upload_url'], 'photo', 'photo.jpg');
You will get a JSON object with
server,
photo,
hash fields. To save a photo call
photos.saveMessagesPhoto with these three parameters:
$vk = new VKApiClient();
$response_save_photo = $vk->photos()->saveMessagesPhoto($access_token, array(
'server' => $photo['server'],
'photo' => $photo['photo'],
'hash' => $photo['hash'],
));
Please read the
full manual before the start.
Call
video.save to get a video upload server address:
$vk = new VKApiClient();
$address = $vk->video()->save($access_token, array(
'name' => 'My video',
));
Send a file to
upload_url received previously calling
upload() method:
$vk = new VKApiClient();
$video = $vk->request()->upload($address['upload_url'], 'video_file', 'video.mp4');
Videos are processed for some time after uploading.
Enable Callback API Long Poll for your group and specify which events should be tracked by calling the following API method:
$vk = new VKApiClient();
$vk->groups()->setLongPollSettings($access_token, array(
'group_id' => 159895463,
'enabled' => 1,
'message_new' => 1,
'wall_post_new' => 1,
));
Override methods from VKCallbackApiHandler class for handling events:
class CallbackApiMyHandler extends VKCallbackApiHandler {
public function messageNew($object) {
echo 'New message: ' . $object['body'];
}
public function wallPostNew($object) {
echo 'New wall post: ' . $object['text'];
}
}
To start listening to LongPoll events, create an instance of your CallbackApiMyHandler class, instance of VKCallbackApiLongPollExecutor class and call method listen():
$vk = new VKApiClient();
$access_token = 'asdj4iht2i4ntokqngoiqn3ripogqr';
$group_id = 159895463;
$wait = 25;
$handler = new CallbackApiMyHandler();
$executor = new VKCallbackApiLongPollExecutor($vk, $access_token, $group_id, $handler, $wait);
$executor->listen();
Parameter
wait is the waiting period.
While calling function
listen() you can also specify the number of the event from which you want to receive data. The default value is the number of the last event.
Example:
$vk = new VKApiClient();
$access_token = 'asdj4iht2i4ntokqngoiqn3ripogqr';
$group_id = 159895463;
$timestamp = 12;
$wait = 25;
$executor = new VKCallbackApiLongPollExecutor($vk, $access_token, $group_id, $handler, $wait);
$executor->listen($timestamp);
CallbackApi handler will wait until VK send notification about event when it happened you may handle this event. More information
here.
You should to configure Callback API inside your community settings.
First step will be approve your domain. VK sends you request to your server with event type
confirmation and you should to send back confirmation string. In other types of event you should to send back ok string.
Look at this example:
use VK\CallbackApi\Server\VKCallbackApiServerHandler;
class ServerHandler extends VKCallbackApiServerHandler {
const SECRET = 'ab12aba';
const GROUP_ID = 123999;
const CONFIRMATION_TOKEN = 'e67anm1';
function confirmation(int $group_id, ?string $secret) {
if ($secret === static::MY_SECRET && $group_id === static::GROUP_ID) {
echo static::CONFIRMATION_TOKEN;
}
}
public function messageNew(int $group_id, ?string $secret, array $object) {
echo 'ok';
}
}
$handler = new ServerHandler();
$data = json_decode(file_get_contents('php://input'));
$handler->parse($data);
To handle events you should to override methods from VKCallbackApiServerHandler class like this.
confirmation event handler contains 2 arguments: group id, and secret key. You must to override confirmation method.