Odnoklassniki API integration

The request format for the OK API and the authorization method depend on the context:

Client-side API calls

To call the OK API on behalf of the user, use VK Bridge in the client app:

  1. 1.
    Get the user access token using the VKWebAppGetAuthToken event.
  2. 2.
    To make a request to the OK API, use the VKWebAppCallAPIMethod event.

Requesting an access token

To get a user access token on OK, use the VKWebAppGetAuthToken event with the append_local=true parameter. The access token will be returned in the local_access_token field:

JavaScript
bridge.send('VKWebAppGetAuthToken', { app_id: 1234567, scope: 'friends', append_local: true }) .then( (data) => { if (data.local_access_token) { // OK user access token received } }) .catch( (error) => { // Error console.log(error); });

Making a request

Using VKWebAppCallAPIMethod, you can send requests to the OK API from the client side of your app. To do this, add the use_local=true parameter and pass the OK user access token in the access_token parameter:

JavaScript
bridge.send('VKWebAppCallAPIMethod', { use_local: true method: 'users.getInfo', params: { uids: 123456789, fields: "first_name,last_name" access_token: 'ok_user_access_token' }}) .then((data) => { if (data.response) { // API method executed } }) .catch((error) => { // Error console.log(error); });

Server-side API calls

To call the OK API on behalf of the app:

  1. 1.
    In the app control panel, get the public and secret keys.
  2. 2.
    Calculate the signature based on the request parameters and the secret key.

Request syntax

To call the OK API, use GET or POST HTTP requests. Any OK API method can be called in one of two equivalent ways by specifying:

  • The method name in the method parameter:

    https://api.ok.ru/fb.do?method=<method_name>&application_key=<public_key>&format=json&params1=value1&params2=value2&sig=<request_signature>
  • The method group and method name in the URL path:

    https://api.ok.ru/api/<method_group>/<method_name>?application_key=<public_key>&format=json&params1=value1&params2=value2&sig=<request_signature>

Common parameters

Parameters required to make a request:

Parameter
Description
application_key
App public key from the control panel.    • Game settings    • Mini app settings
application_secret_key
App secret key from the control panel.    • Game settings    • Mini app settings
sig
Request signature. The signature must be generated from the app secret key and the method parameters.    • Calculating the request signature
format
Response format. Always use json.

Calculating the request signature

To call a method on behalf of the app, calculate the request signature — the value of the sig parameter. The signature is calculated using the public and secret keys from the app control panel, as well as all request parameters.

Important! If you change any parameter in the request, you must recalculate sig.

Example: calculating the request signature for the users.getInfo method with the following parameters:

  • uids=123456789
  • fields=first_name,last_name

To calculate the request signature:

  1. 1.

    Sort the names of all request parameters alphabetically:

    application_key=<public_key> fields=first_name,last_name format=json method=users.getInfo uids=123456789
  2. 2.

    Build a string by writing key=value pairs in alphabetical order, without separators.

    application_key=<public_key>fields=first_name,last_nameformat=jsonmethod=users.getInfouids=123456789
  3. 3.

    Append the secret key application_secret_key to the end of the string:

    application_key=<public_key>fields=first_name,last_nameformat=jsonmethod=users.getInfouids=123456789<secret_key>
  4. 4.

    To get the request signature value sig, calculate the MD5 hash of the string from step 3 and write the result as a 32-character hexadecimal value. Pass the resulting value in the sig parameter:

    https://api.ok.ru/fb.do?method=users.getInfo&application_key=<public_key>&format=json&uids=123456789&fields=first_name,last_name&sig=<request_signature>

Examples

The examples below show how to calculate the request signature and call the users.getInfo method with the following parameters:

JSON
{ uids: '123456789', fields: 'first_name,last_name' }

Calling a method in JavaScript (Node.js)

JavaScript
const crypto = require('node:crypto'); const OK_API_URL = 'https://api.ok.ru/fb.do'; const APP_CONFIG = { applicationKey: process.env.OK_APPLICATION_KEY, applicationSecretKey: process.env.OK_APPLICATION_SECRET_KEY }; /** * Creates a signature for an OK API request. * * 1. Sorts parameters by name. * 2. Concatenates them into a key=value string. * 3. Appends the app secret key to the string. * 4. Calculates MD5. */ function generateSignature(params, secretKey) { const paramString = Object.keys(params) .sort() .map(key => `${key}=${params[key]}`) .join(''); return crypto .createHash('md5') .update(paramString + secretKey) .digest('hex'); } async function callAPI(method, customParams = {}) { const params = { ...customParams, application_key: APP_CONFIG.applicationKey, method }; params.sig = generateSignature( params, APP_CONFIG.applicationSecretKey ); const response = await fetch(OK_API_URL, { method: 'POST', body: new URLSearchParams(params) }); if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } const data = await response.json(); if (data.error_code) { throw new Error( `OK API error #${data.error_code}: ${data.error_msg}` ); } return data; } const params = { uids: '123456789', fields: 'first_name,last_name' } callAPI('users.getInfo', params) .then(data => console.log(data)) .catch(error => console.error(error.message));

Calling a method in Go

Go
package main import ( "crypto/md5" "encoding/hex" "fmt" "io" "net/http" "net/url" "os" "sort" "strings" ) const okAPIURL = "https://api.ok.ru/fb.do" var appConfig = struct { ApplicationKey string ApplicationSecretKey string }{ ApplicationKey: os.Getenv("OK_APPLICATION_KEY"), ApplicationSecretKey: os.Getenv("OK_APPLICATION_SECRET_KEY"), } // generateSignature creates a signature for an OK API request. // // 1. Sorts parameters by name. // 2. Concatenates them into a key=value string. // 3. Appends the app secret key to the string. // 4. Calculates MD5. func generateSignature(params map[string]string, secretKey string) string { keys := make([]string, 0, len(params)) for key := range params { keys = append(keys, key) } sort.Strings(keys) var builder strings.Builder for _, key := range keys { builder.WriteString(key) builder.WriteByte('=') builder.WriteString(params[key]) } builder.WriteString(secretKey) hash := md5.Sum([]byte(builder.String())) return hex.EncodeToString(hash[:]) } func callAPI(method string, customParams map[string]string) ([]byte, error) { params := make(map[string]string, len(customParams)+3) for key, value := range customParams { params[key] = value } params["application_key"] = appConfig.ApplicationKey params["method"] = method params["sig"] = generateSignature( params, appConfig.ApplicationSecretKey, ) form := url.Values{} for key, value := range params { form.Set(key, value) } response, err := http.PostForm(okAPIURL, form) if err != nil { return nil, fmt.Errorf("failed to call OK API: %w", err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { return nil, fmt.Errorf("failed to read OK API response: %w", err) } if response.StatusCode < 200 || response.StatusCode >= 300 { return nil, fmt.Errorf( "OK API returned HTTP %d: %s", response.StatusCode, body, ) } return body, nil } func main() { params := map[string]string{ "uids": "123456789", "fields": "first_name,last_name", } data, err := callAPI("users.getInfo", params) if err != nil { fmt.Println(err) return } fmt.Println(string(data)) }

Related materials