The translation was generated automatically and may contain mistakes

PHP SDK

Project page on Github: https://github.com/VKCOM/vk-php-sdk .

PHP SDK is a PHP library for interacting with the VKontakte API, including authorization OAuth 2.1 and call API methods.

This library is based on JSON Schematics API VKontakte. The API version 5.199 is used.

Requirements

PHP 7.1 or newer.

Connection in the Annex

To install the PHP SDK, use the Composer command:

PHP
composer require vkcom/vk-php-sdk

Initialization

Create an object VKApiClient With code:

PHP
$vk = new VKApiClient();

You can also initialize.. VKApiClient with another version of the API or another language, for example:

'''php $vk = new VKApiClient('5.199'); $vk = new VKApiClient('5.199', VKLanguage::ENGLISH);

## Авторизация SDK предоставляет возможность авторизации на основе протокола `OAuth 2.1`. Пожалуйста, ознакомьтесь с полной [документацией](api/access-token/getting-started) перед началом работы. ### Authorization Code Flow `OAuth 2.1` Authorization Code Flow позволяет обращаться к методам API в серверной части вашего приложения. Эта схема состоит из дву?1?… шагов — получение `code` и обмен `code` на ключ доступа. ?1?’ первую очередь вы должны получить `code` для пользователя или сообщества: * [Инструкция для авторизации пользователя](https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/api-description#Zapros-koda-podtverzhdeniya-i-rabota-s-formoj-razresheniya-dostupov-polzovatelya) * [Инструкция для авторизации сообщества](https://id.vk.com/about/business/go/docs/ru/vkid/latest/oauth/oauth-vkontakte/authcode-flow-community) Чтобы перенаправить пользователя на страницу авторизации, используйте следующий код: #### Для ключа доступа пользователя ```php use VK\OAuth\User\DTO\AuthorizeUrlParams; use VK\OAuth\User\DTO\TokensParams; use VK\OAuth\User\User; require 'vendor/autoload.php'; $clientId = 1234567; $clientSecret = 'secret'; $redirectUri = 'https://domain.tld'; $state = 'abc'; // @see https://datatracker.ietf.org/doc/html/rfc7636#section-4.1 $verifier = 'very_very_very_very_very_very_big_random_string'; $auth = new User(); $authParams = (new AuthorizeUrlParams( $clientId, $verifier, $redirectUri, $state, ))->setScope(Scopes::EMAIL, Scopes::PHONE); $authUrl = $auth->getAuthorizeUrl($authParams);

The Community Access Key

'''php use VK\OAuth\Group\Display; use VK\OAuth\Group\DTO\AccessTokenParams; use VK\OAuth\Group\DTO\AuthorizeUrlParams; use VK\OAuth\Group\Group; use VK\OAuth\ResponseType;

require 'vendor/autoload.php';

$clientId = 1234567; $clientSecret = 'secret'; $redirectUri = 'https://domain.tld'; $state = 'abc';

$auth = new Group();

$authParams = new AuthorizeUrlParams( ResponseType::CODE, $clientId, $redirectUri, Display::PAGE, $state, );

$authUrl = $auth->getAuthorizeUrl($authParams);

Ключ доступа пользователя и ключ доступа сообщества используют разные значения в массиве [`scope`](api/privacy#Права%20доступа). После успешной авторизации браузер перенаправит пользователя на указанный `redirect_uri`. `code`, `device_id` и `state` будут переданы на указанный вами адрес: > https://example.com?code=CODE&device_id=DEVICE_ID&state=STATE Затем используйте этот метод для получения ключа доступа пользователя: ```php use VK\OAuth\User\DTO\TokensParams; use VK\OAuth\User\User; require 'vendor/autoload.php'; $redirectUri = 'https://domain.tld'; $state = 'abc'; // @see https://datatracker.ietf.org/doc/html/rfc7636#section-4.1 $verifier = 'very_very_very_very_very_very_big_random_string'; $auth = new User(); $query = parse_url($url, PHP_URL_QUERY); if (empty($query)) { echo "err empty query in url\n"; exit(1); } parse_str($query, $q); if (empty($q'code')) { echo "err not found parameter code in url\n"; exit(1); } if (empty($q'device_id')) { echo "err not found parameter device_id in url\n"; exit(1); } if (empty($q'state')) { echo "err not found parameter state in url\n"; exit(1); } if ($q'state' !== $state) { echo "err invalid state value in url, expect {$state}: {$q'state'}\n"; exit(1); } $tokenParams = new TokensParams($clientId, $verifier, $redirectUri, $q'code', $q'device_id'); $tokens = $auth->getTokens($tokenParams);

redirect_uri , state and verifier It should be the same as the ones used in the first step.

Or use the method to get the community access key:

PHP
use VK\OAuth\Group\DTO\AccessTokenParams; use VK\OAuth\Group\Group; require 'vendor/autoload.php'; $clientId = 1234567; $clientSecret = 'secret'; $redirectUri = 'https://domain.tld'; $state = 'abc'; $auth = new Group(); $query = parse_url($url, PHP_URL_QUERY); if (empty($query)) { echo "err empty query in url\n"; exit(1); } parse_str($query, $q); if (empty($q'code')) { echo "err not found parameter code in url\n"; exit(1); } if ($q'state' !== $state) { echo "err invalid state value in url, expect {$state}: {$q'state'}\n"; exit(1); } $tokenParams = new AccessTokenParams($clientId, $clientSecret, $redirectUri, $q'code'); $tokens = $auth->getAccessToken($tokenParams);

redirect_uri and state It should be the same as the ones used in the first step.

Implicit flow

Unlike Authorization Code Flow, this scheme allows you to get an access key with a limited validity period.

More about getting the community access key — in the article Implicit Flow to get community access token .

Since June 25, 2024, the method of obtaining a user access key (access token) has changed. More details in section VK ID Authorization Service .

The Community Access Key

PHP
require_once "vendor/autoload.php"; use VK\OAuth\Group\Display; use VK\OAuth\Group\DTO\AuthorizeUrlParams; use VK\OAuth\Group\Group; use VK\OAuth\Group\Scopes; use VK\OAuth\ResponseType; $client_id = 1234567; $redirect_uri = 'https://example.com/vk'; $display = Display::PAGE; $scopes = [Scopes::MESSAGES]; $state = 'secret_state_code'; $groups_ids = [1, 2]; $auth = new Group(); $authParams = new AuthorizeUrlParams( ResponseType::TOKEN, $client_id, $redirect_uri, $display, $state, ); $authParams->setScopes($scopes); $authParams->setGroupIds($groups_ids); $browser_url = $auth->getAuthorizeUrl($authParams);

After successful authorization, the browser redirects the user to the specified redirect_uri . The access key will be passed as a fragment to the address you specified:

For the community access key:

https://example.com#access_token_XXXXXX=533bacf01e11f55b536a565b57531ad114461ae8736d6506a3&expires_in=86400&state=secret_state_code
  • •
    expires_in The duration of the access key in seconds.
  • •
    state the line passed in the authorization request.
  • •
    access_token_XXXXXX A community access key where XXXXXX is the community ID.

API Requests

List of all API methods .

Example of request

Example method call users.get :

'''php $vk = new VKApiClient(); $response = $vk->users()->get($access_token, array( 'user_ids' => array(1, 210700286), 'fields' => array('city', 'photo'), ));

### Загрузка фото в личное сообщение Пожалуйста, прочитайте полное руководство перед началом работы. ?1?’ызовите [`photos.getMessagesUploadServer`](method/photos.getMessagesUploadServer), чтобы получить адрес для загрузки файла: ```php $vk = new VKApiClient(); $address = $vk->photos()->getMessagesUploadServer('{access_token}');

Then use the method upload() to send files to the received upload_url : '''php $vk = new VKApiClient(); $photo = $vk->getRequest()->upload($address['upload_url'], 'photo', 'photo.jpg');

?1?’ ответе вы получите JSON-объект с полями `server`, `photo`, `hash`. Чтобы сохранить фотографию, вызовите метод [`photos.saveMessagesPhoto`](method/photos.saveMessagesPhoto) с этими тремя параметрами: ```php $vk = new VKApiClient(); $response_save_photo = $vk->photos()->saveMessagesPhoto($access_token, array( 'server' => $photo['server'], 'photo' => $photo['photo'], 'hash' => $photo['hash'], ));

Downloading the video

Please read the full guide before starting work.

Call the method video.save to get the address to download the file:

PHP
$vk = new VKApiClient(); $address = $vk->video()->save($access_token, array( 'name' => 'My video', ));

Then use the method upload() to send the file to the received upload_url :

PHP
$vk = new VKApiClient(); $video = $vk->getRequest()->upload($address['upload_url'], 'video_file', 'video.mp4');

Some time after uploading the video is in the process of processing.

Developments in Communities

Long Poll

Enable the Bots Long Poll API in your community and specify events to be tracked using this method:

'''php $vk = new VKApiClient(); $vk->groups()->setLongPollSettings($access_token, array( 'group_id' => 159895463, 'enabled' => 1, 'message_new' => 1, 'wall_post_new' => 1, ));

Переопределите методы из `VKCallbackApiHandler`, чтобы отслеживать события: ```php class CallbackApiMyHandler extends VKCallbackApiHandler { public function messageNew($group_id, $secret, $object) { echo 'New message: ' . $object['message']['text']; } public function wallPostNew($object) { echo 'New wall post: ' . $object['text']; } }

To start tracking events in Long Poll, create a class instance CallbackApiMyHandler , class VKCallbackApiLongPollExecutor and call the method listen() :

'''php $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();

Параметр `wait` соответствует периоду« ожидания» запроса. ?1?’ вызове функции `listen()` вы также можете задать номер события, начиная с которого нужно получать обновления. Значение по умолчанию — номер последнего события. Пример: ```php $vk = new VKApiClient(); $access_token = 'asdj4iht2i4ntokqngoiqn3ripogqr'; $group_id = 159895463; $ts = 12; $wait = 25; $executor = new VKCallbackApiLongPollExecutor($vk, $access_token, $group_id, $handler, $wait); $executor->listen($ts);

Callback API

You can find more information about the Callback API here.. page .

You need to configure the Callback API in the Management → In addition → Working with APIs your group or public page.

First of all, you need to confirm the server address. VKontakte sends a request to your server with the event type confirmation in response to which it is necessary to return the control line (confirmation code). For all other types of notifications, your server should respond with a string "ok" .

Пример:

PHP
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::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, override methods from the class VKCallbackApiServerHandler .

Event handler confirmation contains two arguments: a community ID and a private key. You need to redefine it.