VK PHP SDK

repository·master·Indexed 42 days ago

https://github.com/vkcom/vk-php-sdk

A PHP library for interacting with the VK API, featuring OAuth 2.0 authorization flows (Authorization Code and Implicit), structured access to API methods via VKApiClient, and support for Long Poll and Callback API server handlers. It provides specialized classes for account management, profile updates, push notification control, and community app widgets.

Tokens
13.2K
Snippets
40
Records
71
Agent score
52%

What's inside VK PHP SDK

  1. How OAuth 2.0 Authorization Code Flow works

    master

    The Authorization Code Flow is used for server-side applications. It is a two-step process:

    1. Obtain an authorization code: Redirect the user to the VK authorization page using VKOAuth::getAuthorizeUrl() with VKOAuthResponseType::CODE.
    2. Exchange the code for an access token: Once the user is redirected back to your redirect_uri with a code parameter, use VKOAuth::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'];
  2. How Implicit Flow works

    master

    The Implicit Flow provides a temporary access key directly in the URL fragment after authorization. This is typically used for client-side applications.

    Use VKOAuth::getAuthorizeUrl() with VKOAuthResponseType::TOKEN. The access token will be returned in the URL fragment (e.g., #access_token=...) at your redirect_uri.

    $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];
    $state = 'secret_state_code';
    $revoke_auth = true;
    
    $browser_url = $oauth->getAuthorizeUrl(\VK\OAuth\VKOAuthResponseType::TOKEN, $client_id, $redirect_uri, $display, $scope, $state, null, $revoke_auth);
  3. Initialize the VKApiClient

    master

    Create an instance of VKApiClient to interact with the VK API. You can specify a custom API version and language during initialization.

    Default initialization uses the library's default version and language.

    // Default initialization
    $vk = new \VK\Client\VKApiClient();
    
    // Initialize with specific API version
    $vk = new VKApiClient('5.199');
    
    // Initialize with specific API version and language
    $vk = new VKApiClient('5.199', \VK\Client\Enums\VKLanguage::ENGLISH);
  4. Implement Long Poll for Group updates

    master

    Long Poll allows your application to listen for real-time events from a VK group.

    1. Enable Long Poll: Use groups()->setLongPollSettings() to enable the service and select event types (e.g., message_new, wall_post_new).
    2. Create a Handler: Extend VK\CallbackApi\VKCallbackApiHandler and override methods corresponding to the events you want to track (e.g., messageNew($object)).
    3. Execute the Listener: Use VK\CallbackApi\LongPoll\VKCallbackApiLongPollExecutor to start the listening loop.
    // 1. Setup settings
    $vk->groups()->setLongPollSettings($access_token, [
      'group_id'      => 159895463,
      'enabled'       => 1,
      'message_new'   => 1,
      'wall_post_new' => 1,
    ]);
    
    // 2. Define Handler
    class CallbackApiMyHandler extends VK\CallbackApi\VKCallbackApiHandler {
        public function messageNew($object) {
            echo 'New message: ' . $object['body'];
        }
        
        public function wallPostNew($object) {
            echo 'New wall post: ' . $object['text'];
        }
    }
    
    // 3. Listen
    $handler = new CallbackApiMyHandler();
    $executor = new \VK\CallbackApi\VKCallbackApiLongPollExecutor($vk, $access_token, $group_id, $handler, 25);
    $executor->listen();
  5. Implement Callback API Server Handler

    master

    The Callback API notifies your server via HTTP requests when events occur. To handle these:

    1. Extend the Handler: Extend VK\CallbackApi\Server\VKCallbackApiServerHandler.
    2. Handle Confirmation: You MUST override the confirmation(int $group_id, ?string $secret) method. When VK sends a confirmation event, verify the $secret matches your configured secret and echo the CONFIRMATION_TOKEN provided in your community settings.
    3. Handle Other Events: For other events (like messageNew), return the string 'ok'.
    4. Parse Requests: Use $handler->parse(json_decode(file_get_contents('php://input'))) to process incoming data.
    class ServerHandler extends \VK\CallbackApi\Server\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);
  6. Upload photos to a Private Message

    master

    To upload a photo to a private message, follow these three steps:

    1. Get an upload server address: Call photos()->getMessagesUploadServer($access_token).
    2. Upload the file: Use the upload() method from the request object to send the file to the upload_url received in step 1.
    3. Save the photo: Use photos()->saveMessagesPhoto($access_token, [...]) with the server, photo, and hash fields returned from the upload step.
    $vk = new \VK\Client\VKApiClient();
    
    // 1. Get upload server
    $address = $vk->photos()->getMessagesUploadServer($access_token);
    
    // 2. Upload file
    $photo = $vk->getRequest()->upload($address['upload_url'], 'photo', 'photo.jpg');
    
    // 3. Save photo
    $response_save_photo = $vk->photos()->saveMessagesPhoto($access_token, [
        'server' => $photo['server'],
        'photo'  => $photo['photo'],
        'hash'   => $photo['hash'],
    ]);
  7. Upload video files

    master

    To upload a video file:

    1. Get a video upload server: Call video()->save($access_token, ['name' => '...']).
    2. Upload the file: Use the upload() method from the request object to send the file to the upload_url received in step 1.
    $vk = new \VK\Client\VKApiClient();
    
    // 1. Get upload server
    $address = $vk->video()->save($access_token, [
        'name' => 'My video',
    ]);
    
    // 2. Upload file
    $video = $vk->getRequest()->upload($address['upload_url'], 'video_file', 'video.mp4');
  8. Upload photo or video stories

    master

    To upload stories, you must first obtain an upload server URL and then save the results:

    1. Get Upload Server:
      • Use getPhotoUploadServer(string $access_token, array $params = []) for photos.
      • Use getVideoUploadServer(string $access_token, array $params = []) for videos.
      • Common params: group_id (integer), add_to_news (boolean), user_ids (array of integers), and link_url (string).
    2. Save Story:
      • Use save(string $access_token, array $params = []) with the results from the upload step. Required params: upload_results (array of strings) or upload_results_json (string).
  9. Make API requests using VKApiClient

    master

    Access VK API methods through the VKApiClient instance. Methods are grouped by resource (e.g., users(), photos(), video()).

    Example of calling users.get:

    $vk = new \VK\Client\VKApiClient();
    $response = $vk->users()->get($access_token, [
        'user_ids'  => [1, 210700286],
        'fields'    => ['city', 'photo'],
    ]);
  10. Manage application balance and transactions

    master

    Use the following methods to monitor application finances:

    • getAppBalance(string $access_token): Returns the application's payment balance in hundredths of a vote.
    • getTransactionsHistory(string $access_token, array $params): Shows history of vote transactions between users and the application.
      • Params: type, uid_from, uid_to, date_from, date_to, limit.
  11. Retrieve and manage tags

    master

    Methods for managing favorites tags:

    • getTags(string $access_token): Retrieves the list of user tags.
    • editTag(string $access_token, array $params = []): Edits an existing tag. Requires id and name in $params.
    • removeTag(string $access_token, array $params = []): Removes a tag by id.
    • reorderTags(string $access_token, array $params = []): Reorders tags. Requires ids (array of integers) in $params.
    • setTags(string $access_token, array $params = []): Assigns tags to an item. Requires item_type (FaveSetTagsItemType), item_owner_id, item_id, and tag_ids (array of integers). Can also take link_id or link_url for links.