### Getting Started with VK API Source: https://dev.vk.com/ru/api/getting-started This section covers the initial steps for using the VK API, including registering an application, obtaining access tokens, and making your first API request. ```APIDOC ## Getting Started with VK API This guide will walk you through the essential steps to start using the VK API. ### Step 1. Register Your Application To make API requests to VK, you must include an access token. VK supports several types of access tokens. You need to register your application or website with VK. The registration page depends on your application type: * **Standalone application or website:** https://id.vk.com/business/go * **Mini-application or game:** https://vk.com/apps?act=manage **Types of Applications:** * **Mini-application or game:** These applications run within the VK user interface and use the user's information without requiring explicit authorization. * **Standalone application:** Any external application that uses the VK API and operates outside the VK interface. * **Website:** A website that uses the VK API or integrates VK widgets. ### Step 2. Obtain an Access Token After registering your application, you will be taken to the application settings page where you can find your access token. The term 'token' is used interchangeably with 'access key' in VK ID documentation. **Other Ways to Obtain Tokens:** * For standalone applications and websites using the older VK OAuth authorization system, refer to the 'Access Keys' section. * For mini-applications and games, you can use the access token provided by VK during the application's startup in the launch parameters. See the 'Mini-applications - Launch Parameters' and 'Games - Launch Parameters' sections for details. * Games and mini-applications can also request an access token using the `VKWebAppGetAuthToken` event from the VK Bridge library. ### Step 3. Make a Request Once you have obtained an access token, include it in the `access_token` query parameter or the `Authorization` header. **Example with `Authorization` header:** ```http POST https://api.vk.ru/method/status.get?user_id=743784474&v=5.131 HTTP/1.1 Authorization: Bearer vk1.a.8mo8TRf0jm67Nla3W3fFbe9qKhMNNMqg21DQLgaPUj... ``` **Example with `access_token` query parameter:** ``` https://api.vk.ru/method/status.get?user_id=743784474&v=5.131&access_token=vk1.a.8mo8TRf0jm67Nla3W3fFbe9qKhMNNMqg21DQLgaPUj... ``` ### Related Materials * Request Format * VK ID Tokens * Access Keys ``` -------------------------------- ### VK API Client Info Object Example (JSON) Source: https://dev.vk.com/ru/api/bots/getting-started An example of the `client_info` object received in the VK API's `message_new` event. This object details the client's capabilities, such as supported button actions, keyboard types, and language ID. ```json { "client_info": { "button_actions": [ "text", "vkpay", "open_app", "location", "open_link", "callback" ], "keyboard": true, "inline_keyboard": true, "carousel": false, "lang_id": 0 } } ``` -------------------------------- ### Install Community Widget Source: https://dev.vk.com/ru/api/community-apps-widgets/getting-started To install a widget, users first need to add the application to their community. This is typically done using the VK Bridge `VKWebAppAddToCommunity` event. After the app is added, the widget preview can be shown using `VKWebAppShowCommunityWidgetPreviewBox`. ```APIDOC ## Install Community Widget ### Description Instructions for installing a widget in a VK community. ### Method N/A (Uses VK Bridge Events) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Step 1: Add application to community VKBridge.send('VKWebAppAddToCommunity'); // Step 2: Show widget preview box VKBridge.send('VKWebAppShowCommunityWidgetPreviewBox'); ``` ### Response #### Success Response (200) N/A (Events do not return direct success responses in this context) #### Response Example N/A ``` -------------------------------- ### Widget Code Example with API Call Source: https://dev.vk.com/ru/api/community-apps-widgets/getting-started Within the widget `code`, you can call a limited set of VK API methods. This example demonstrates fetching user information using `users.get`. The API version defaults to 5.100. ```javascript return { 'widget': { 'title': 'User Info Widget', 'content': { 'type': 'text', 'text': API.users.get({"user_ids": Args.uid})[0].first_name + ' ' + API.users.get({"user_ids": Args.uid})[0].last_name } } }; ``` -------------------------------- ### VK API Path Parameter Example Source: https://dev.vk.com/ru/api/api-requests Shows how to specify the API method name as part of the URL path. This example uses 'status.get' as the method. ```http https://api.vk.ru/method/status.get? ``` -------------------------------- ### VK API Request Syntax Example (POST) Source: https://dev.vk.com/ru/api/api-requests Demonstrates how to make a POST request to a VK API method, including the URL structure, query parameters, and headers. This example shows calling the 'users.get' method to retrieve user details. ```http POST https://api.vk.ru/method/users.get?user_ids=743784474&fields=bdate&access_token=533bacf01e11f55b536a565b57531ac114461ae8736d6506a3&v=5.199 HTTP/1.1 ``` -------------------------------- ### Example Incoming Event Data (JSON) Source: https://dev.vk.com/ru/api/callback/getting-started An example of a JSON object representing a 'group_join' event. This illustrates the actual data fields and their typical values, including the event type, ID, API version, object details (user ID and join type), and group ID. ```json { "type": "group_join", "event_id": 12345, "v": "5.131", "object": { "user_id": 1, "join_type": "approved" }, "group_id": 1 } ``` -------------------------------- ### Start Command Payload (JSON) Source: https://dev.vk.com/ru/api/bots/development/keyboard This JSON snippet shows the structure of the `payload` sent when a user clicks the 'Start' button in a community chat. It typically contains a command, such as `start`, and can be extended with additional parameters if needed, facilitating the initial interaction with the bot. ```json { "command": "start" } ``` -------------------------------- ### VK API Response Example (JSON) Source: https://dev.vk.com/ru/api/api-requests Provides a sample JSON response for a VK API method call. This example shows the expected output format for the 'users.get' method when requesting user information. ```json { "response": [ { "id": 743784474, "first_name": "Персик", "last_name": "Рыжий", "bdate": "21.12.2000" } ] } ``` -------------------------------- ### Install Community Widget using VK Bridge Source: https://dev.vk.com/ru/api/community-apps-widgets/getting-started This snippet demonstrates the sequence of VK Bridge events required to install a widget in a community. First, the application must be added to the community using `VKWebAppAddToCommunity`, followed by displaying the widget preview using `VKWebAppShowCommunityWidgetPreviewBox`. ```javascript VKBridge.send('VKWebAppAddToCommunity'); VKBridge.send('VKWebAppShowCommunityWidgetPreviewBox'); ``` -------------------------------- ### PHP Example: Handling Message New Event Source: https://dev.vk.com/ru/api/callback/getting-started A PHP script demonstrating how to process incoming notifications, specifically handling the 'message_new' event and responding to users. ```APIDOC ## Example Usage (PHP) ### Description This PHP script illustrates how to handle notifications from the VKontakte Callback API. It specifically demonstrates processing a new message event and sending a reply back to the sender. ### PHP Script ```php type) { // Handle confirmation request for server address verification case 'confirmation': echo $confirmation_token; break; // Handle new message event case 'message_new': // Get the sender's user ID $user_id = $data->object->message->from_id; // Use users.get to retrieve sender's information $user_info_url = "https://api.vk.ru/method/users.get?user_ids={$user_id}&access_token={$token}&v=5.103"; $user_info = json_decode(file_get_contents($user_info_url)); // Extract the sender's first name $user_name = $user_info->response[0]->first_name; // Prepare parameters for sending a reply message using messages.send $request_params = [ 'message' => "Hello, {$user_name}!", 'peer_id' => $user_id, 'access_token' => $token, 'v' => '5.103', 'random_id' => '0' // A unique ID for the message to avoid duplicates ]; // Build the query string for the messages.send API method $get_params = http_build_query($request_params); // Send the reply message file_get_contents('https://api.vk.ru/method/messages.send?' . $get_params); // Respond with 'ok' to the Callback API server to confirm successful processing echo('ok'); break; } ?> ``` ### SDK Support VKontakte provides SDKs to facilitate interaction with the Callback API: * Java SDK * PHP SDK ``` -------------------------------- ### Connecting Callback API Source: https://dev.vk.com/ru/api/callback/getting-started Instructions on how to connect your server to the Callback API through the community settings and API methods. ```APIDOC ## Connecting Callback API ### Via Community Settings 1. Navigate to your community settings on vk.com. 2. Go to **Management** and then **Additional Settings → API Access**. 3. Open the **Callback API** tab. 4. Specify and confirm the server URL where event notifications will be sent. You can connect up to 10 servers, each with a different set of events and API version. 5. Upon confirmation, VK will send a `confirmation` type notification to your server. Your server must return a specific string provided by VK to confirm the connection. This confirmation string can be obtained using the `groups.getCallbackConfirmationCode` method or viewed in community settings. ### Via API Methods - `groups.addCallbackServer`: Adds a Callback API server to the community. - `groups.deleteCallbackServer`: Deletes a Callback API server. - `groups.editCallbackServer`: Edits Callback API server data. - `groups.getCallbackConfirmationCode`: Retrieves the confirmation code for connecting a Callback API server. - `groups.getCallbackServers`: Retrieves a list of connected servers in the community. - `groups.getCallbackSettings`: Retrieves event settings for a Callback API server. - `groups.setCallbackSettings`: Sets event settings for a Callback API server. ``` -------------------------------- ### Construct vk.me Link with Parameters Source: https://dev.vk.com/ru/api/community-messages/getting-started Creates short URLs using vk.me to redirect users to a specified dialog. Links can include `ref` and `ref_source` parameters that are returned in the message object for events like `message_new`. This is useful for tracking link effectiveness and associating users with external application sessions. ```URL vk.me/{group_name}?ref={ref}&ref_source={ref_source} ``` ```URL vk.com/write-{group_id}?ref={ref}&ref_source={ref_source} ``` -------------------------------- ### Open API Initialization Source: https://dev.vk.com/ru/api/open-api/getting-started Initializes the Open API with your application ID. Supports both synchronous and asynchronous initialization. ```APIDOC ## Open API Initialization ### Description Initializes the Open API with your application ID. Supports both synchronous and asynchronous initialization. ### Method `VK.init(params)` ### Parameters #### Parameters - **apiId** (integer) - Required - The identifier of your VK application. - **status** (boolean) - Optional - If `true`, automatically updates session data and status using `VK.Auth.getLoginStatus`. - **onlyWidgets** (boolean) - Optional - If `true`, initializes Open API only for widget integration. ### Synchronous Initialization Example ```html ``` ### Asynchronous Initialization Example ```html
``` ``` -------------------------------- ### VK API Wall Post Response Example (JSON) Source: https://dev.vk.com/ru/api/upload/wall-photo This is an example of the JSON response received after successfully posting a photo to a VK wall using the `wall.post` method. It contains the ID of the newly created post. ```json { "response":{ "post_id":17 } } ``` -------------------------------- ### Bots Long Poll API Example Event: Group Join Source: https://dev.vk.com/ru/api/bots-long-poll/getting-started An example of a `group_join` event object as received from the Bots Long Poll API. It details the user ID and the type of join. ```json { "type": "group_join", "event_id": "c68dfb983247fea8ac98ea0ea59717df71d8064f", "v": "5.131", "object": { "user_id": 1, "join_type": "approved" }, "group_id": 1 } ``` -------------------------------- ### Post Content for Donut Subscribers (API Example) Source: https://dev.vk.com/ru/api/donut/getting-started This example shows how to use the `wall.post` method to publish a post that is initially visible only to 'donut' subscribers. The `donut_paid_duration` parameter can be used to set a time after which the post becomes visible to all community members. ```HTTP https://api.vk.ru/method/wall.post?owner_id=-1&message=This is a special post for donut subscribers!&access_token=YOUR_ACCESS_TOKEN&v=5.131&donut_paid_duration=3600 ``` -------------------------------- ### Modify Donut Paid Duration for a Wall Post (API Example) Source: https://dev.vk.com/ru/api/donut/getting-started This example demonstrates how to use the `wall.edit` method to change the `donut_paid_duration` parameter for an existing wall post. This allows you to adjust when a post, initially meant for subscribers, becomes publicly available. ```HTTP https://api.vk.ru/method/wall.edit?owner_id=-1&post_id=123&access_token=YOUR_ACCESS_TOKEN&v=5.131&donut_paid_duration=7200 ``` -------------------------------- ### Synchronous Initialization of VK Open API Source: https://dev.vk.com/ru/api/open-api/getting-started This method initializes the VK Open API synchronously by including the API script in the head and calling VK.init before the closing body tag. It requires your application ID. ```html ``` ```javascript VK.init({ apiId: ВАШ_APP_ID }); ``` -------------------------------- ### Widget Code Structure Example Source: https://dev.vk.com/ru/api/community-apps-widgets/getting-started The `code` parameter for updating a widget should return a JSON object describing the widget. This example shows a basic structure. The `widget` object's content varies based on the widget type. To hide a widget, return `false`. ```javascript return { 'widget': { 'title': 'Example Widget', 'more_info': 'This is a sample widget code.' // Widget-specific content based on 'type' } }; // To hide the widget: // return false; ``` -------------------------------- ### Creating a Community Access Token Source: https://dev.vk.com/ru/api/access-token/community-token/in-community-settings Instructions on how to generate an access token for a VKontakte community through the community's settings. This token is used to make API requests on behalf of the community. ```APIDOC ## Creating a Community Access Token Community access tokens are used to make requests to the VKontakte API on behalf of a community. One way to obtain such a token is to create it in the community's settings. ### Requirements Only community administrators can create and view access tokens. ### Steps 1. Open vk.com and navigate to the community where you are an administrator. 2. In the right-hand menu, select **Manage** and then **Additional → API Interaction**. 3. On the **Access Tokens** tab, you can view existing tokens or create new ones. - [Go to community management](link_to_community_management) - [Open the "Access Tokens" tab](link_to_access_tokens_tab) 4. Click **Create Token**. 5. In the dialog window, select the data scopes the token will have access to, and click **Create**. 6. Confirm the action in the VKontakte mobile application. You will see the created token on the **Access Tokens** tab. ### Token Usage Use this token to send requests to the VKontakte API from the server-side of your application. ### Related Materials * Community Access Token ``` -------------------------------- ### Check if User is a Donut Subscriber (API Example) Source: https://dev.vk.com/ru/api/donut/getting-started This example demonstrates how to use the `donut.isDon` method to check if a user is subscribed to paid content within a VK community. It requires the community ID and a valid access token. The API version should also be specified. ```HTTP https://api.vk.ru/method/donut.isDon?owner_id=-1&access_token=42&v=5.131 ``` -------------------------------- ### Asynchronous Initialization of VK Open API Source: https://dev.vk.com/ru/api/open-api/getting-started This method initializes the VK Open API asynchronously, allowing the platform to initialize in parallel with your JavaScript code. It requires a specific container div and dynamically loads the API script. It also requires your application ID. ```html
``` -------------------------------- ### File Upload Overview Source: https://dev.vk.com/ru/api/upload/overview General process for uploading any file to VK, involving obtaining an upload URL, transferring files, and saving information. ```APIDOC ## File Upload Process Overview ### Description This outlines the general steps required to upload any file type via the VK API. It includes obtaining an upload URL, sending the file data, and confirming the upload. ### Method N/A (This is a conceptual overview) ### Endpoint N/A (This is a conceptual overview) ### Parameters N/A ### Request Example N/A ### Response N/A ## Note on Saving File Information To save information about the uploaded file, remove the escaping character (`\`) from the `photo`, `photo_list` parameters. ## File Type Specific Uploads Details of the upload process may vary based on the file type. Refer to the left-hand menu for specific instructions on uploading: * Photos to an album * Photos to a wall * User or community cover photos * Photos to private messages * Cover photos for chats * Photos for products * Photos for product collections * Audio files to profile music * Video recordings to a profile * Documents * Community covers * Audio messages * Stories to profiles ``` -------------------------------- ### Example Carousel Template Object Source: https://dev.vk.com/ru/api/bots/development/messages A complete example of the 'template' object for sending a carousel message. It includes the 'type' as 'carousel' and an 'elements' array containing multiple carousel items. Each item demonstrates different configurations, including 'photo_id', 'action', and 'buttons' with text labels. ```JSON { "type": "carousel", "elements": [{ "photo_id": "-109837093_457242811", "action": { "type": "open_photo" }, "buttons": [{ "action": { "type": "text", "label": "Текст кнопки 🌚", "payload": "{}" } }] }, { "photo_id": "-109837093_457242811", "action": { "type": "open_photo" }, "buttons": [{ "action": { "type": "text", "label": "Текст кнопки 2", "payload": "{}" } }] }, { "photo_id": "-109837093_457242811", "action": { "type": "open_photo" }, "buttons": [{ "action": { "type": "text", "label": "Текст кнопки 3", "payload": "{}" } }] } ]} ```