### Install VK ID SDK via pnpm
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/web/install
This code snippet illustrates the installation of the VK ID SDK for Web using pnpm, a performant package manager. This method is ideal for projects with a code bundler and requires NodeJS version 16.10 or higher.
```bash
pnpm add @vkid/sdk
```
--------------------------------
### Install VK ID SDK via npm
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/web/install
This code snippet shows how to install the VK ID SDK for Web using npm, a popular package manager. This method is suitable for projects that use a code bundler. Ensure you have NodeJS version 16.10 or higher installed.
```bash
npm i @vkid/sdk
```
--------------------------------
### Configure AuthConfiguration with Scopes (Swift)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
This example demonstrates how to specify required access scopes when creating an `AuthConfiguration`. Scopes define the permissions your application needs. They can be provided as an array of strings or using the `Scope` type, either as a string or an array of strings.
```swift
let authConfiguration = AuthConfiguration(
// ...
scope: ["phone", "email"]
)
let authConfiguration = AuthConfiguration(
// ...
scope: Scope("phone email")
)
let authConfiguration = AuthConfiguration(
// ...
scope: Scope(["phone", "email"])
)
```
--------------------------------
### Install VK ID SDK via yarn
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/web/install
This code snippet demonstrates how to install the VK ID SDK for Web using yarn, another common package manager. This approach is recommended for projects utilizing a code bundler and requires NodeJS version 16.10 or higher.
```bash
yarn add @vkid/sdk
```
--------------------------------
### Install VK ID SDK using CDN script
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/web/install
This HTML script tag allows you to install the VK ID SDK for Web using a Content Delivery Network (CDN). This method is suitable for projects that do not use a code bundler. Replace '<3.0.0' with the desired specific version of the SDK. The SDK will be available globally via the `window.VKIDSDK` object.
```html
```
--------------------------------
### VK ID Authorization Configuration
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
Details on configuring authorization flows and PKCE parameters for VK ID integration.
```APIDOC
## VK ID Authorization Configuration
### Description
This section details the configuration of `AuthConfiguration` for VK ID, including authorization schemes and the generation of PKCE parameters.
### Method
N/A (Configuration)
### Endpoint
N/A (Configuration)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
None
#### Response Example
None
## PKCE Parameters Generation
### Description
Details on generating `PKCESecrets` for secure authorization code exchange.
### Method
N/A (Configuration)
### Endpoint
N/A (Configuration)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```swift
// Example for frontend code exchange
let codeVerifier = someCodeVerifierGenerator()
let codeChallenge = someBase64Encoder(
someS256Encoder(codeVerifier)
)
let pkceSecrets = PKCESecrets(
codeVerifier: codeVerifier,
codeChallenge: codeChallenge,
codeChallengeMethod: .S256,
state: UUID().uuidString
)
// Example for backend code exchange
let codeChallenge = // Received from your backend codeChallenge.
let pkceSecrets = PKCESecrets(
codeChallenge: codeChallenge,
codeChallengeMethod: .S256,
state: UUID().uuidString
)
```
### Response
#### Success Response (200)
None
#### Response Example
None
## Configuring Frontend Code Exchange Authorization
### Description
Instructions on setting up `AuthConfiguration` for the frontend code exchange authorization flow.
### Method
N/A (Configuration)
### Endpoint
N/A (Configuration)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```swift
// PKCE generated by SDK
let authConfiguration = AuthConfiguration(
flow: .publicClientFlow()
)
// PKCE generated by you
let authConfiguration = AuthConfiguration(
flow: .publicClientFlow(
pkce: pkceSecrets
)
)
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Get User Info Response Example
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/auth-without-sdk/auth-without-sdk-ios
This is an example of the response when retrieving user information. It includes details such as user ID, name, contact information, avatar, and verification status.
```json
{
"user": {
"user_id": "1234567890",
"first_name": "Ivan",
"last_name": "Ivanov",
"phone": "79991234567",
"avatar": "https://pp.userapi.com/60tZWMo4SmwcploUVl9XEt8ufnTTvDUmQ6Bj1g/mmv1pcj63C4.png",
"email": "ivan_i123@vk.ru",
"sex": 2,
"verified": false,
"birthday": "01.01.2000"
}
}
```
--------------------------------
### Get User Info Request Example
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/auth-without-sdk/auth-without-sdk-ios
This example demonstrates how to retrieve detailed user information. It requires an Authorization header with the access token and a JSON body containing the client ID.
```shell
curl --location 'https://id.vk.ru/oauth2/user_info' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer ****' \
--data '{
"client_id":"7915193"
}'
```
--------------------------------
### Передача конфигурации в виджет OAuthListWidget VK ID SDK
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
Пример инициализации `OAuthListWidget` с передачей объекта `authConfiguration`. Результат авторизации обрабатывается в замыкании, связанном с виджетом.
```swift
let oAuthListWidget = OAuthListWidget(
// ...
authConfiguration: authConfiguration
) { authResult in
// Обработка результата авторизации.
}
```
--------------------------------
### User Info Response Example
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/oauth/oauth-mail/index
This is an example of a successful HTTP 200 OK response when retrieving user information. It contains various user profile details such as name, nickname, email, and more.
```json
{
"sub": "...",
"name": "Алексей Иванов",
"given_name": "Алексей",
"family_name": "Иванов",
"nickname": "alex",
"picture": "https://...",
"gender": "male",
"birthdate": "2006-01-02",
"locale": "ru_RU",
"email": "alex@ivanov.ru",
"email_verified": true
}
```
--------------------------------
### Configure AuthConfiguration for Frontend Flow (Swift)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
Configures the `AuthConfiguration` for a frontend authorization flow using VK ID SDK. Demonstrates creating the configuration with the `.publicClientFlow` and optionally providing pre-generated PKCE secrets.
```swift
// В данном случае pkce сгенерированы SDK.
let authConfiguration = AuthConfiguration(
flow: .publicClientFlow()
)
// В данном случае pkce сгенерированы вами.
let authConfiguration = AuthConfiguration(
flow: .publicClientFlow(
pkce: pkceSecrets
)
)
```
--------------------------------
### Передача конфигурации в метод authorize() VK ID SDK
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
Пример передачи объекта `authConfiguration` в метод `authorize()` для инициализации процесса авторизации. Обработка результата авторизации происходит в замыкании.
```swift
VKID.shared.authorize(
with: authConfiguration,
// ...
) { authResult in
// Обработка результата авторизации.
}
```
--------------------------------
### Access Token Response Example
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/oauth/oauth-mail/index
This is an example of a successful HTTP 200 OK response when obtaining or refreshing an access token. It includes the expiration time, the access token itself, and a refresh token.
```json
{
"expires_in":3600,
"access_token":"****",
"refresh_token":"****"
}
```
--------------------------------
### Request Community Access Token (HTTP)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/oauth/oauth-vkontakte/authcode-flow-community
This example demonstrates the HTTP GET request required to obtain a community access token. It includes all necessary parameters: client_id, client_secret, redirect_uri, and code. The URL is directed to the VK OAuth access_token endpoint.
```HTTP
GET https://oauth.vk.com/access_token?client_id=1&client_secret=H2Pk8htyFD8024mZaPHm&redirect_uri=http://mysite.ru&code=7a6fa4dff77a228eeda56603b8f53806c883f011c40b72630bb50df056f6479e52a
```
--------------------------------
### Передача конфигурации в шторку авторизации OneTapBottomSheet VK ID SDK
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
Пример инициализации `OneTapBottomSheet` с передачей объекта `authConfiguration`. Замыкание используется для обработки результата авторизации после отображения шторки.
```swift
let oneTapBottomSheet = OneTapBottomSheet(
// ...
authConfiguration: authConfiguration
) { authResult in
// Обработка результата авторизации.
}
```
--------------------------------
### Import VK ID SDK Modules for Web
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/web/setup
Import specific modules or all modules from the VK ID SDK for web integration. This allows for the use of features like OneTap, FloatingOneTap, OAuthList, or manual button implementation. Ensure the SDK is installed via npm or included via CDN.
```javascript
import { Config, OneTap } from '@vkid/sdk';
```
```javascript
import * as VKID from '@vkid/sdk';
```
--------------------------------
### Migrate SDK Initialization (Kotlin)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/migration/android/migration-android
Remove the old `SuperappKit.init(config)` call and replace it with `VKID.init(this)` within your `Application.onCreate()` method. This initializes the VK ID SDK for use throughout your application.
```kotlin
// Remove
val config = ...
SuperappKit.init(config)
// Add in Application.onCreate
class App : Application {
override fun onCreate() {
super.onCreate()
VKID.init(this)
}
}
```
--------------------------------
### Configure AuthConfiguration for Confidential Client Flow (Swift)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
This snippet illustrates how to create an `AuthConfiguration` object for the confidential client flow. It involves setting the `flow` parameter to `.confidentialClientFlow` and providing an instance that conforms to `AuthCodeHandler` (like `self` in the example) to the `codeExchanger` parameter, along with any necessary `pkce` parameters.
```swift
let authConfiguration = AuthConfiguration(
flow: .confidentialClientFlow(
codeExchanger: self,
pkce: pkceSecrets
)
)
```
--------------------------------
### PKCE (Proof Key for Code Exchange) Flow
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/web/setup
Implement PKCE for enhanced security during the authorization process. This section details how to use `codeVerifier` and `codeChallenge`.
```APIDOC
## PKCE (Proof Key for Code Exchange) Flow
### Description
PKCE enhances the security of authorization flows by introducing a dynamic secret (`codeVerifier`) and its transformation (`codeChallenge`). This section explains how to integrate PKCE with the VK ID SDK.
### Usage Scenarios
**1. Providing `codeVerifier`:**
- The VK ID SDK transforms the provided `codeVerifier` into a `codeChallenge` using the specified `code_challenge_method`.
- The `codeChallenge` is then used in the authorization request to `https://id.vk.ru/authorize`.
- This method is versatile and supports both client-side and server-side code-to-token exchange.
**2. Providing `codeChallenge`:**
- The VK ID SDK uses the provided `codeChallenge` directly in the authorization request to `https://id.vk.ru/authorize`.
- This method is *only* compatible with server-side code-to-token exchange.
- If your application does not use a backend, you cannot use this method as the `codeVerifier` will not be available for the token exchange.
**3. No `codeVerifier` or `codeChallenge` provided:**
- The VK ID SDK automatically generates a `codeVerifier` and transforms it into a `codeChallenge` using the `code_challenge_method`.
- The `codeChallenge` is used in the authorization request to `https://id.vk.ru/authorize`.
- This method is *only* compatible with client-side code-to-token exchange.
- If your application uses a backend, you will not be able to retrieve the generated `codeVerifier` from the VK ID SDK to use in your backend's code-to-token exchange request.
```
--------------------------------
### Handle Authorization Result with Backend Code Exchange (Swift)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
This example shows how to handle the result of VK ID authorization when using a backend code exchange flow. It implements the `VKIDObserver` protocol to receive `AuthResult`. The code specifically catches `AuthError.authCodeExchangedOnYourBackend` to confirm the successful completion of the confidential flow, distinguishing it from other success or error cases.
```swift
extension AuthViewController: VKIDObserver {
func vkid(_ vkid: VKID, didCompleteAuthWith result: AuthResult, in oAuth: OAuthProvider) {
do {
let session = try result.get()
print("Auth succeeded with\n(session)")
self.showAlert(message: session.debugDescription)
} catch AuthError.cancelled {
print("Auth cancelled by user")
} catch AuthError.authCodeExchangedOnYourBackend {
print("Conf flow ended")
self.showAlert(message: "Успешное завершение Confidential flow")
} catch {
print("Auth failed with error: (error)")
self.showAlert(message: "Ошибка авторизации")
}
}
}
```
--------------------------------
### Configure VK ID SDK for Web Authorization
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/web/setup
Configure the VK ID SDK by initializing it with essential parameters such as the application ID (client_id), redirect URL, and PKCE parameters like scope, codeVerifier, codeChallenge, and state. This setup is crucial for initiating the authorization process.
```javascript
VKID.Config.init({
app: client_id, // Идентификатор приложения.
redirectUrl: redirect_url, // Адрес для перехода после авторизации.
state: '<случайно сгенерированный state>', // Произвольная строка состояния приложения.
codeVerifier: '<ваш сгенерированный code_verifier>', // Параметр в виде случайной строки. Обеспечивает защиту передаваемых данных.
scope: 'email phone', // Список прав доступа, которые нужны приложению.
});
```
--------------------------------
### Get Masked User Info Request Example
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/auth-without-sdk/auth-without-sdk-ios
This example shows how to retrieve masked user information using an ID token. It requires the client ID and the ID token in the request body.
```shell
curl --location 'https://id.vk.ru/oauth2/public_info?client_id=51923592' \
--header 'Content-Type: application/json' \
--data '{
"id_token": "****"
}'
```
--------------------------------
### Configure One Tap Button with Custom Appearance and Layout (Swift)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/elements/onetap-button/onetap-ios
This Swift example illustrates initializing a OneTapButton with specific visual properties. It allows customization of the button's style, theme (using system color scheme), layout (size and corner radius), and presenter for the authorization UI. It also includes a closure for handling the authorization result.
```swift
let oneTap = OneTapButton(
appearance: .init(
style: .primary(),
theme: .matchingColorScheme(.system)
),
layout: .regular(
height: .large(.h56),
cornerRadius: 28
),
presenter: .newUIWindow
) { authResult in
// Обработка результата авторизации.
}
```
--------------------------------
### Get User Info using Access Token with VK ID SDK
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/work-with-user-info/user-info
Retrieves user information using an Access Token. The returned data depends on the scopes requested during application setup and authorization. To get unmasked phone and email, ensure these scopes are enabled and included in the `scope` parameter.
```javascript
VKID.Auth.userInfo(access_token);
```
--------------------------------
### Install VK ID SDK for iOS using CocoaPods
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/ios/install
Integrate the VK ID SDK into your iOS project using CocoaPods. After adding the pod to your Podfile, run 'pod install --repo-update' to fetch and link the SDK. This is an alternative dependency management approach.
```ruby
pod 'VKID', '~> 2.3'
```
```bash
pod install --repo-update
```
--------------------------------
### Get User Info using Access Token
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/work-with-user-info/user-info
Retrieve user information using an Access Token. The data returned depends on the scopes requested during authorization and app setup.
```APIDOC
## Get User Info using Access Token
### Description
Retrieve user profile information using a valid Access Token. The fields returned are determined by the scopes configured for the application and requested during the authorization flow.
### Method
GET
### Endpoint
- SDK: `VKID.Auth.userInfo(access_token)`
- API: `/oauth2/user_info`
- VK API: `/users.get`
### Parameters
#### SDK Method: `userInfo`
- **access_token** (string) - Required - The Access Token obtained after authorization.
#### API Endpoint: `/oauth2/user_info`
- **access_token** (string) - Required - The Access Token obtained after authorization.
- **scope** (string) - Optional - Specifies the requested scopes (e.g., `phone email`).
### Request Example (SDK)
```javascript
VKID.Auth.userInfo(accessToken);
```
### Request Example (API)
```
GET https://id.vk.ru/oauth2/user_info?access_token=
```
### Response
#### Success Response (200)
- **id** (string) - User ID.
- **first_name** (string) - User's first name.
- **last_name** (string) - User's last name.
- **photo_url** (string) - URL to the user's profile photo.
- **gender** (string) - User's gender.
- **birth_date** (string) - User's date of birth.
- **email** (string) - User's email address (if requested and granted).
- **phone** (string) - User's phone number (if requested and granted).
#### Response Example (`/oauth2/user_info`)
```json
{
"id": "123456789",
"first_name": "Иван",
"last_name": "Петров",
"photo_url": "https://example.com/photo.jpg",
"gender": "male",
"birth_date": "1990-01-01"
}
```
#### Note on `users.get` API
The VK API `users.get` method returns information directly from the user's profile, which may not be verified. For verified data, use the `/oauth2/user_info` endpoint or SDK methods.
```
--------------------------------
### Configuring Community Subscription Window (XML)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/group-subscription/group-subscription-android
This example shows how to configure the community subscription window using XML attributes and properties. It includes setting the group ID, styling, and managing the Snackbar host and access token provider. The `show()`, `hide()`, and `setCallbacks()` methods are also available for programmatic control.
```xml
```
--------------------------------
### Handle Authorization Code Callback
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/oauth/oauth-ok/server
After user authorization, the user is redirected to this URI. The authorization code ('code') and the 'state' parameter (if provided) are appended as GET parameters. The 'code' is valid for 2 minutes.
```URL
{redirect_uri}?code={code}&state={state}
```
--------------------------------
### Передача конфигурации в кнопку OneTapButton VK ID SDK
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
Пример инициализации `OneTapButton` с передачей объекта `authConfiguration`. Результат авторизации обрабатывается в замыкании, переданном при создании кнопки.
```swift
let oneTapButton = OneTapButton(
// ...
authConfiguration: authConfiguration
) { authResult in
// Обработка результата авторизации.
}
```
--------------------------------
### Creating and Rendering Community Subscription Window
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/group-subscription/group-subscription-web
This section provides guidance on how to create an instance of the community subscription window and render it within your application, specifying parameters like community ID, access token, and visual theme.
```APIDOC
## Creating and Rendering Community Subscription Window
### Description
This endpoint allows you to programmatically create and display a community subscription window to users. You need to provide the community ID and an access token with the necessary permissions. You can also customize the appearance and language of the window.
### Method
POST (Implicitly, via SDK method call)
### Endpoint
N/A (SDK method)
### Parameters
#### Request Body (for `render` method)
- **groupId** (Int) - Required - The ID of the community to subscribe users to. This can be found in the community's detailed information.
- **accessToken** (String) - Required - An access token that includes the 'groups' scope, granting permission to manage community subscriptions.
- **scheme** (Enum VKID.Scheme or String) - Optional - The color scheme for the window. Use `VKID.Scheme.LIGHT` (default) or `VKID.Scheme.DARK`.
- **lang** (Enum VKID.Languages or Number) - Optional - The localization for the window. Use values from `VKID.Languages` (default is `VKID.Languages.RUS`).
### Request Example
```javascript
import * as VKID from '@vkid/sdk';
// Create an instance of the community subscription window.
const communitySubscription = new VKID.CommunitySubscription();
// Render the subscription window for a specific community, using a provided access token, light theme, and Russian language.
communitySubscription.render({
groupId: GROUP_ID,
accessToken: ACCESS_TOKEN,
scheme: VKID.Scheme.LIGHT,
lang: VKID.Languages.RUS
});
```
### Response
#### Success Response (200)
The community subscription window is rendered on the user's interface.
#### Response Example
N/A
```
--------------------------------
### Set Custom Log Engine for VK ID SDK
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/start-integration/android/install
This example demonstrates how to set a custom log engine for the VK ID SDK. You can implement your own `LogEngine` to handle logs as needed, overriding the default behavior.
```kotlin
VKID.logEngine = object: LogEngine {
override fun log(logLevel: LogEngine.LogLevel, tag: String, message: String, throwable: Throwable?) {
//...
}
}
```
--------------------------------
### Configure Automatic OneTapBottomSheet Display in Swift
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/elements/onetap-drawer/floating-onetap-ios
This example illustrates how to configure the OneTapBottomSheet for automatic display using the `autoShow` method. Before enabling this, ensure that `autoShowConfiguration` is properly set up. This method is useful for seamlessly presenting the authorization sheet when needed.
```swift
oneTapSheet.autoShow(factory: vkid)
```
--------------------------------
### Migrate Manifest Placeholders (Kotlin DSL)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/migration/android/migration-android
Update your `build.gradle` file to use `addManifestPlaceholders` with the new VK ID specific keys like `VKIDRedirectHost`, `VKIDRedirectScheme`, `VKIDClientID`, and `VKIDClientSecret`. This configures the necessary parameters for VK ID authentication within the AndroidManifest.xml.
```kotlin
android.defaultConfig.manifestPlaceholders = [
'VkExternalAuthRedirectScheme' : 'vk' + 'your_app_id',
'VkExternalAuthRedirectHost' : 'vk.ru',
]
// to
android {
defaultConfig {
addManifestPlaceholders(mapOf(
"VKIDRedirectHost" to "vk.ru" // Usually vk.ru.
"VKIDRedirectScheme" to "vk1233445" // Strictly in the format vk{App ID}.
"VKIDClientID" to clientId // com_vk_sdk_AppId.
"VKIDClientSecret" to clientSecret // vk_client_secret.
))
}
}
```
--------------------------------
### Generate PKCE Secrets for Backend Authorization (Swift)
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/setting-up-auth/setup-ios
Generates PKCE parameters for backend authorization flows where the code challenge is obtained from a backend service. This focuses on providing the pre-generated code challenge, the challenge method, and a state identifier.
```swift
let codeChallenge = // Полученный от вашего бэкенда codeChallenge.
let pkceSecrets = PKCESecrets(
codeChallenge: codeChallenge,
codeChallengeMethod: .S256,
state: UUID().uuidString
)
```
--------------------------------
### Migrate Dependencies in build.gradle
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/migration/android/migration-android
Replace existing VK SDK dependencies with the appropriate VK ID SDK dependencies in your app's build.gradle file. Choose the dependency that matches your authorization approach (e.g., without UI, One Tap with Compose, or One Tap with XML).
```gradle
dependencies {
implementation "com.vk:oauth-vk:${sdkVersion}"
implementation "com.vk:vksdk-pub:${sdkVersion}"
}
// to
dependencies {
// If using authorization without UI, specify this dependency.
implementation("com.vk.id:vkid:${sdkVersion}")
// If using One Tap on Compose, specify this dependency.
implementation("com.vk.id:onetap-compose:${sdkVersion}")
// If using One Tap on XML, specify this dependency.
implementation("com.vk.id:onetap-xml:${sdkVersion}")
}
```
--------------------------------
### VK ID Authorization Button Integration
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/elements/custom-button/custom-button-web
This section details how to integrate the VK ID authorization button into your website. It includes code examples for adding a click handler to the button that initiates the authorization process using the VK ID SDK.
```APIDOC
## POST /websites/id_vk_about_business_go_ru_vkid
### Description
This endpoint describes the process of integrating the VK ID authorization button into your website. It involves obtaining the authorization button element and attaching a click event handler to it, which triggers the `Auth.login()` method from the VK ID SDK.
### Method
POST
### Endpoint
/websites/id_vk_about_business_go_ru_vkid
### Parameters
#### Query Parameters
- **scheme** (Enum VKID.Scheme or String) - Optional - Specifies the color scheme for the VK ID interface. Default is `VKID.Scheme.LIGHT`. Use `VKID.Scheme.DARK` for a dark theme.
- **lang** (Enum VKID.Languages or number) - Optional - Sets the localization for the VK ID interface. Default is `VKID.Languages.RUS`. Use other enum values or numbers for different languages.
### Request Example
```javascript
// Example for SDK installed via console
import * as VKID from '@vkid/sdk';
const handleClick = () => {
VKID.Auth.login()
}
const button = document.getElementById('VKIDSDKAuthButton');
if (button) {
button.onclick = handleClick;
}
// Example for SDK installed via script and CDN
const VKID = window.VKIDSDK;
const handleClick = () => {
VKID.Auth.login()
}
const button = document.getElementById('VKIDSDKAuthButton');
if (button) {
button.onclick = handleClick;
}
```
### Response
#### Success Response (200)
This endpoint does not return a direct response body. The success is indicated by the initiation of the VK ID login flow.
#### Response Example
N/A
```
--------------------------------
### Get Fresh Access Token in VK ID iOS
Source: https://id.vk.com/about/business/go/docs/ru/vkid/latest/vk-id/connection/migration/ios/oauth-2
This Swift code demonstrates how to obtain a fresh Access Token for a VK ID user session. The `getFreshAccessToken` method is called on the `currentAuthorizedSession`. An optional `forceRefresh` parameter can be used to explicitly trigger a token refresh.
```swift
vkid.currentAuthorizedSession?.getFreshAccessToken { result in
// Обработка результата получения 'AccessToken'.
}
vkid.currentAuthorizedSession?.getFreshAccessToken(forceRefresh: true) { result in
// Обработка результата получения 'AccessToken'.
}
```