Skip to content

Login with VKontakte🔗

Login with VKontakte

Login with VKontakte - allows people to quickly create an account and enter your application from various platforms. This feature is available on iOS, Android, web apps, PC apps, and devices like Smart TV and IoT. Logging in through VKontakte allows you to solve two problems: perform authentication and request permissions to access people's data. Logging in through VKontakte can be used simply for authorization, and for authorization and requesting permissions. With the “Log in through VKontakte” people can quickly and easily create an account in your application without setting a password. This simple and convenient method allows you to increase conversion. Having created an account on one platform, a person can then log in to your application on any other platforms - just one touch or click. A verified email address will allow you to reach that person and engage them again.

Important

Note that this submodule depends on the native sdk VKontakte, and is fully compatible with it. That is, if you are currently working with native sdk, that is when you switch to MRGS, we automatically raise the saved session

Android sdk-fingerprint is incorrect

1) Make sure you remove all ":" from SHA1 according to documentation.
2) You are using the new apk signing mechanism in GooglePlay, you should take SHA1 for your project fromGooglePlay Console.

VK authorization

VK authorization requires Android 5.0+ (Api level 21+).

Setup🔗

Obtaining keys and nessesary data🔗

Before begin, Set up a developer account on the VKontakte website, add a new application. After registering the application, you will receive a unique identifier for your application (VKontakte AppID).

To create an application, open the "Management" page in the left menu, then click "Create Application" - you will be taken to the page https://vk.com/editapp?act=create. Select the type of application - Standalone application. After confirming the action, you will be taken to a page with information about the application. Click the “Settings” tab in the menu on the left. You will see the "Application ID" field, in which a number will be indicated, for example, 5490057. This number is the application identifier, also known as VKontakte App ID, it will be required in future work.

Important

At this step, you only need to get VKontakte App ID and configure the application on the VKontakte website. How to use it in the project is described below.

Setting up project🔗

In order for the authorization to work correctly, you need to add some changes to the project:

Unity

For iOS, you need to add the following data to the Info.plist application:

  1. Add a new URL-scheme to open other applications from your application
  2. Add a new URL-scheme to open your application from outside vk<VKontakte_APP_ID>

You need to add a new application opening scheme so that the browser can return the user back to your application. The URL scheme should be a string of the form ** vk <VKontakte_APP_ID> **, where VKontakte_APP_ID is your VKontakte application identifier obtained in the previous step (for example, if VKontakte_APP_ID is 7425813, then the added scheme should look like: vk7425813 ) Details on adding URL schemes in the generated project are described in this article, but Unity has a simpler method for adding data to the application plist described below.

A scheme for opening other applications is needed to check for the availability of the official VKontakte application. You must add the vkauthorize schema to LSApplicationQueriesSchemes. Details on adding URL schemes in the generated project are described in this article, but Unity has a simpler method for adding data to the application plist, described below.

Add this code to Unity post build process:

[PostProcessBuild]
public static void PostProcessBuild(BuildTarget target, string path)
{
    string plistPath = path + "/Info.plist";
    PlistDocument plist = new PlistDocument();
    plist.ReadFromString(File.ReadAllText(plistPath));
    PlistElementDict rootDict = plist.root;

    PlistElementArray schemesToOpen = rootDict.CreateArray("LSApplicationQueriesSchemes");
    schemesToOpen.AddString("vkauthorize");

    // Adding URL-scheme
    PlistElementArray appSchemes = rootDict.CreateArray("CFBundleURLTypes");
    PlistElementDict appSchemesDict = appSchemes.AddDict();
    appSchemesDict.SetString("CFBundleURLName", "");
    PlistElementArray appSchemesArray = appSchemesDict.CreateArray("CFBundleURLSchemes");                
    appSchemesArray.AddString("vk<VKontakte_APP_ID>"); // Where VKontakte_APP_ID - is your Vkontakte application id you have got on the previous step

    File.WriteAllText(plistPath, plist.WriteToString());
}

Or change the existing property adding code in the application's Info.plist, if you have one.

Android:

Unfortunately, the VK SDK for Android does not allow you to specify the AppID (application identifier) as a parameter when initializing the SDK. The only way is to add a special integer identifier com_vk_sdk_AppId (the name is important) to the application resources. To do this, you can, for example, create an empty Android library (aar-file), in the resources of which add this identifier (by placing it in the res/values/integers.xml file of your library)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="com_vk_sdk_AppId">YOUR_APP_ID</integer>
</resources>
iOS

You need to add the following data to the Info.plist of your application:

  1. Add a new URL-scheme to open other applications from your application
  2. Add a new URL-scheme to open your application from outside vk<VKontakte_APP_ID>

You need to add a new application opening scheme so that the browser can return the user back to your application. The URL scheme should be a string of the form ** vk <VKontakte_APP_ID> **, where VKontakte_APP_ID is your VKontakte application identifier obtained in the previous step (for example, if VKontakte_APP_ID is 7425813, then the added scheme should look like: vk7425813 ) Details about adding URL schemes in the generated project are written in this article, but the description of the addition is also given below.

A scheme for opening other applications is needed to check for the availability of the official VKontakte application. You must add the vkauthorize schema to LSApplicationQueriesSchemes. Details on adding URL schemes in the generated project are written in this article, but the description of the addition is also given below.

Using UI:

To add schemes to LSApplicationQueriesSchemes (to open other applications) you need to:

  • Open Info.plist of the project
  • Add new field with name LSApplicationQueriesSchemes and type array
  • Add the necessary elements to the created array(vkauthorize)

To add URL-scehem (to have ability to open application from outsiede) you need to:

  • Open Info.plist
  • Add string «URL types»
  • Expand the first element ("Item0"), add the string "URL identifier" and add the value with the identifier of your application (for example, com.company.appname).
  • Add string to the first element ("item0") in "URL types" and name it "URL Schemes" and add a new element (desired URL scheme) to "URL Schemes"

As a result you will get such a structure:

Url schemes

Using XML:

Add data to the Info.plist:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>vkauthorize</string>
</array>

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>vk<VKontakte_APP_ID></string>
        </array>
    </dict>
</array>

Note: for URL schemes, if you already have such a structure in a plist with other schemes, then you can simply add one more element to the scheme array (CFBundleURLSchemes)

Android

In the project:

Unfortunately, the VK SDK for Android does not allow you to specify the AppID (application identifier) as a parameter when initializing the SDK. The only way is to add a special integer identifier com_vk_sdk_AppId (the name is important) to the application resources (for example, to the file res/values/integers.xml)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="com_vk_sdk_AppId">YOUR_APP_ID</integer>
</resources>

Add dependencies🔗

Add the MRGS SDK to the project:

Unity:

Adding to the project (general instruction)

Step 1. Add Sources

To add MRGS to a project via the Unity Package Manager (available from Unity 2018+) simply add a scopedRegistries section to the Packages/manifest.json file by adding the following entry:

{
    "dependencies": {
        ...
    },
    "scopedRegistries": [
            {
                "name": "MRGS",
                "url": "https://mrgs-nexus.my.games/repository/mrgs-uninty-plugins/",
                "scopes": [
                    "games.my.mrgs"
                ]
            }
    ]
}

Alternatively, you can click Edit -> Project Settings -> Package Manager -> '+' in scoped registry section, and fill in the fields according to the data above.

Step 2. Add dependency

  • Click Window -> Package Manager -> select 'Packages: MyRegistries' from dropdown list, select package MRGSAuthenticationVK from the list, then click "Install"
  • Import the module: using MRGS;
  • Download the latest version of the library. Unzip the archive.
  • (For unitypackage integration) In Unity, click Assets -> Import Package -> Custom Package, and select the games.my.mrgs.authenticationvk.unitypackage package from the downloaded archive.
  • (For tgz integration) In Unity, click Window -> Package Manager -> '+' -> Add package from tarball, and select the games.my.mrgs.authenticationvk-<version> package. tgz from the downloaded archive.
  • Import the module: using MRGS;

iOS:

Adding to the project (general instruction)

In iOS, when using manual integration, you need to add standard tools to the project VKSdk.framework and VKSdkResources.bundle, which are in the folder Dependencies/MRGSAuthenticationDependencies/VKontakte in the archive downloaded from the MRGS website. Instructions for adding 3d-party libraries to the project can be found on the Internet.

Step 1: Add dependencies

Via Package collection

  • In Xcode select File > Add Packages
  • Select "+" > "Add Swift Package Collection"
  • Insert URL: https://mrgs-nexus.my.games/repository/ios-sdks/MRGSPackageCollection.json
  • Select module MRGSAuthenticationVK from "MRGS Package Collection".
  • Or you can select "MRGS" package from "MRGS Package Collection" (contains all mrgs modules as products) and then select "MRGS/AuthenticationVK" product only.

Individual packages

  • In Xcode select File > Add Packages
  • In the search bar at the top right, paste the URL: https://mrgs-gitea.my.games/mrgs/mrgsauthenticationvk-ios-sdk.git
  • Add a module to your project
  • Or you can paste the url https://mrgs-gitea.my.games/mrgs/ios-sdks.git to include the "MRGS" package which contains all mrgs modules as products and then select only the product" MRGS/AuthenticationVK".

Step 2: Add support for ObjectiveC categories

  • Set the -ObjC flag in the "Other linker Flags" field in the project settings.
  • Import the module in code: @import MRGServiceKit; or @import MRGSAuthenticationVK; or #import <MRGSAuthenticationVK/MRGSAuthenticationVK.h>

Step 1. Add Sources

In your podfile, add sources to the top of the file:

source 'https://github.com/CocoaPods/Specs.git' # For main repo
source 'https://mrgs-gitea.my.games/mrgs/cocoapods-specs.git'  # For MRGS repo

Step 2: Add dependencies

Add the latest version of MRGSAuthenticationVK to target:

To add via subspecs:

target 'MyProject' do
    pod 'MRGS', '~> 5.0.0', :subspecs => ['AuthenticationVK']
end

To add via individual modules:

target 'MyProject' do
    pod 'MRGSAuthenticationVK', '~> 5.0.0'
end

To add all mrgs modules:

target 'MyProject' do
    pod 'MRGS/AllKits', '~> 5.0.0'
end

Step 3: Install dependencies

  • Run pod install (or pod install --repo-update if necessary)
  • Import the module in code: @import MRGServiceKit; or @import MRGSAuthenticationVK; or #import <MRGSAuthenticationVK/MRGSAuthenticationVK.h>

Step 1: Add dependencies

Add the dependency to your Cartfile:

binary "https://mrgs-nexus.my.games/repository/ios-sdks/MRGSAuthenticationVK/MRGSAuthenticationVK.json" ~> 5.0.0

Step 2: Install dependencies

  • Run carthage update --use-xcframeworks
  • Add downloaded frameworks to your project (make sure "do not embed" option is enabled)
  • Set the -ObjC flag in the "Other linker Flags" field in the project settings.
  • Import the module in code: @import MRGServiceKit; or @import MRGSAuthenticationVK; or #import <MRGSAuthenticationVK/MRGSAuthenticationVK.h>
  • Download the latest version of the library. Unzip the archive.
  • Add MRGSAuthenticationVK.xcframework from the downloaded archive to your project (Drag the libraries to the "Linked frameworks and Libraries" section) (Also contains MRGSAuthenticationVK.framework for compatibility - fat framework)

  • Set the -ObjC flag in the "Other linker Flags" field in the project settings.

  • Import the module in code: @import MRGSAuthenticationVK; or #import <MRGSAuthenticationVK/MRGSAuthenticationVK.h>
  • Also, you can add the MRGServiceKit.h and module.modulemap files from the archive to your project, or specify the path to them in the project settings in the Build Settings -> Header search paths section. Now, instead of importing each of our frameworks separately, you can only import one header file: @import MRGServiceKit;

Android:

Adding to the project

Add a dependency in build.gradle file:

dependencies {
    def mrgsVersion = "6.x.x"

    implementation "games.my.mrgs:authentication-vk:$mrgsVersion"
}

Copy the MRGSAuthentication.aar file into the libs directory of your project. Add the dependencies into the build.gradle file.

dependencies {
    //...
    implementation(name: 'MRGSAuthentication', ext:'aar')
    implementation(name: 'MRGSAuthenticationVK', ext:'aar')

    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'androidx.browser:browser:1.5.0'
    implementation "com.vk:android-sdk-core:3.4.1"
}

Configuring MRGS init params🔗

Pass received VKontakteAppID to MRGS SDK. To do this, when starting the MRGS SDK, add the appropriate setting in the parameters of the external SDK:

using MRGS;

public class MasterController : MonoBehaviour
{
    void Awake()
    {
        // Setting up mrgs params
        // ...

        var modulesParams = new List<MRGSExternalSDKSettings>
        modulesParams.Add(new MRGSVKontakteParams("<VKontakte_APP_ID>"))
        // Setting up external sdk params
        // ...

        MRGService.Instance.Initialize(serviceParams, sdkParams)
    }
}
@import MRGService;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Setting up mrgs params
    // ...
    //Setting up external sdk params

    MRGSVKontakteParams* VKontakteLoginParams = [[MRGSVKontakteParams alloc] initWithAppId:@"<VKontakte_APP_ID>"];

    NSArray *externalParams = @[ ..., VKontakteLoginParams];
    [MRGService startWithServiceParams:<params> externalSDKParams:externalParams delegate:nil];
}
import java.util.ArrayList;
import java.util.List;

import games.my.mrgs.MRGSModuleParams;
import games.my.mrgs.MRGService;
import games.my.mrgs.authentication.vk.MRGSVKAuthParams;

public class YourApplicationClass extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        // Setting MRGService
        final MRGServiceParams serviceParams = ...;
        // Setting External SDKs
        final List<MRGSModuleParams> moduleParams = new ArrayList<>();
        moduleParams.add(MRGSVKAuthParams.init());

        MRGService.service(context, serviceParams, moduleParams);
    }
}

Using MRGSAuthentication interface🔗

To work with Login with VKontakte, use the MRGSAuthenticationVKontakte class (MRGSVK on Android). Please note that this class implements main interface MRGSAuthentication, so it includes all the methods of this interface. The following describes the standard implementation of the MRGSAuthentication interface:

Delegate🔗

Before you start using the API, you must implement and set a delegate that accepts callbacks:

// Setting
// 'this' conforms to 'IMRGSAuthenticationDelegate' protocol
MRGSAuthenticationVKontakte.Instance.Delegate = this;

// Implementation
// The method that is called when the user has logged out of the social network remotely, or his session has ended.
public void OnAuthenticationProviderDidLogoutUser(MRGSAuthentication provider, MRGSAuthenticationUser user){
    Debug.Log("MRGSAuthentication<Unity> - OnAuthenticationProviderDidLogoutUser: " + user + "\nNetwork: " + provider.SocialId().ToString());
}
//Set
[MRGSAuthenticationVKontakte sharedInstance].delegate = self;

//Implementation
//The method that is called when the user remotely logs out of the social network, or his session ends.
- (void)authenticationProvider:(id<MRGSAuthentication>)provider didLogoutUser:(MRGSAuthenticationUser *)user{
    NSLog(@"User did logout: \n%@", user);
}

//The method that is called when the controller needs to be displayed to authorize the user.
- (void)shouldPresentAuthorizationController:(UIViewController *)viewController {
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    [rootVC presentViewController:viewController animated:YES completion:nil];
}
import androidx.annotation.NonNull;

import games.my.mrgs.authentication.MRGSAuthentication.OnExternalLogoutListener;
import games.my.mrgs.authentication.vk.MRGSVK;

// Set a listener
MRGSVK.getInstance().setOnExternalLogoutListener(new OnExternalLogoutListener() {
    @Override
    public void onUserLogout(@NonNull String socialId) {
        // Handel result.
    }
});

Status🔗

To check login status call:

bool isLoggedIn = MRGSAuthenticationVKontakte.Instance.IsLoggedIn();
BOOL isLoggedIn = [[MRGSAuthenticationVKontakte sharedInstance] isLoggedIn];
import games.my.mrgs.authentication.vk.MRGSVK;

final boolean isLoggedIn = MRGSVK.getInstance().isLoggedIn();

Login🔗

For regular login call one of the methods:

// If error occured, error object will be non-null
MRGSAuthenticationVKontakte.Instance.Login((MRGSError error) => {
    if (error == null) {
        // Auth success
    } 
});

// The response will include an object describing the user and the token, and an error object, if any.
MRGSAuthenticationVKontakte.Instance.Login((MRGSAuthenticationCredential credentials, MRGSError error) => {
    Debug.Log("MRGSAuthenticationVKontakte:\nCredentials: " + credentials + "\nError:\n" + error);
    if (error == null) {
        // Auth success
    }
});
// Only the object of the error will come in the answer, if it happened
[[MRGSAuthenticationVKontakte sharedInstance] login:^(NSError *error) {
    if (!error) {
        // Auth success
    }
}];

//The response will contain an object describing the user and the token, and the object of the error if it happened
[[MRGSAuthenticationVKontakte sharedInstance] loginWithCompletionHandler:^(MRGSAuthenticationCredential *credentials, NSError *error) {
    NSLog(@"Result - %@. Error - %@", credentials, error);
    if (!error) {
        // Auth success
    }
}];
import android.app.Activity;

import androidx.annotation.NonNull;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.MRGSCredentials;
import games.my.mrgs.authentication.MRGSLoginCallback;
import games.my.mrgs.authentication.vk.MRGSVK;

MRGSVK.getInstance().login(activity, new MRGSLoginCallback() {
    @Override
    public void onSuccess(@NonNull MRGSCredentials credentials) {
        // Handle result.
    }

    @Override
    public void onError(@NonNull MRGSError error) {
        // Handle error.
    }
});

Login with permissions🔗

You can also request additional data from user:

  • Email
  • Friends list
  • Post on user wall
  • Groups api (join, leave, check status)
  • Uploading user photos
  • Checking user status

Enum description (on Android - it's a string constants):

* Email - MRGSAuthenticationVKontakte.Scopes.Email
* Friends list - MRGSAuthenticationVKontakte.Scopes.Friends
* Post on user wall - MRGSAuthenticationVKontakte.Scopes.Wall
* Groups api (join, leave, check status) - MRGSAuthenticationVKontakte.Scopes.Groups
* Uploading user photos - MRGSAuthenticationVKontakte.Scopes.Photos
* Checking user status - MRGSAuthenticationVKontakte.Scopes.Status
* Email - kMRGSAuthenticationVKontakteScopeEmail
* Friends list - kMRGSAuthenticationVKontakteScopeFriends
* Post on user wall - kMRGSAuthenticationVKontakteScopeWall
* Groups api (join, leave, check status) - kMRGSAuthenticationVKontakteScopeGroups
* Uploading user photos - kMRGSAuthenticationVKontakteScopePhotos
* Checking user status - kMRGSAuthenticationVKontakteScopeStatus
* Email - "email"
* Friends list - "friends"
* Post on user wall - "wall"
* Groups api (join, leave, check status) - "groups"
* Uploading user photos - "photos"
* Checking user status - "status"

Call login method and pass array with permissions to request additional data

var scopes = new List<string>();
scopes.Add(MRGSAuthenticationVKontakte.Scopes.Email);
scopes.Add(MRGSAuthenticationVKontakte.Scopes.Friends);
scopes.Add(MRGSAuthenticationVKontakte.Scopes.Wall);
scopes.Add(MRGSAuthenticationVKontakte.Scopes.Groups);
scopes.Add(MRGSAuthenticationVKontakte.Scopes.Photos);
scopes.Add(MRGSAuthenticationVKontakte.Scopes.Status);

MRGSAuthenticationVKontakte.Instance.Login(scopes, (MRGSAuthenticationCredential credentials, MRGSError error) => {
    Debug.Log("MRGSAuthenticationVKontakte:\nCredentials: " + credentials + "\nError:\n" + error);
    if (error == null) {
        // Auth success
    }
});
NSArray* scopesToRequest = @[kMRGSAuthenticationVKontakteScopeEmail,kMRGSAuthenticationVKontakteScopeFriends,kMRGSAuthenticationVKontakteScopeWall,kMRGSAuthenticationVKontakteScopeGroups,kMRGSAuthenticationVKontakteScopePhotos,kMRGSAuthenticationVKontakteScopeStatus];
[[MRGSAuthenticationVKontakte sharedInstance] loginWithScopes:scopesToRequest completionHandler:^(MRGSAuthenticationCredential *credentials, NSError *error) {
    NSLog(@"Result - %@. Error - %@", credentials, error);
}];
import android.app.Activity;

import androidx.annotation.NonNull;

import java.util.Arrays;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.MRGSCredentials;
import games.my.mrgs.authentication.MRGSLoginCallback;
import games.my.mrgs.authentication.vk.MRGSVK;

final List<String> scopes = Arrays.asList("email", "friends", "groups", "wall", "photos", "status");
MRGSVK.getInstance().login(activity, scopes, new MRGSLoginCallback() {
    @Override
    public void onSuccess(@NonNull MRGSCredentials credentials) {
        // Handle result
    }

    @Override
    public void onError(@NonNull MRGSError error) {
        // Handle error.
    }
});

Important

Note that the user may not give some permissions (while for VKontakte you can not give only email). You can see the list of permissions received in the credentials.accessToken.authorizedScopes field.

Authentication status🔗

To get all the information about the current authorization status, user information, authorization status, use the methods:

// The information about the user, identifier, name, email, etc.
MRGSAuthenticationVKontakte.Instance.GetCurrentUser((MRGSAuthenticationUser user, MRGSError error) => {
    Debug.Log("MRGSAuthenticationVKontakte:\User: " + user + "\nError:\n" + error);
    if (error == null) {
        // Work with user data
    }
});

// Information about the token, lifetime, etc.
MRGSAuthenticationVKontakte.Instance.GetAccessToken((MRGSAuthenticationAccessToken token, MRGSError error) => {
    Debug.Log("MRGSAuthenticationVKontakte:\Token: " + token + "\nError:\n" + error);
    if (error == null) {
        // Work with token info
    }
    else if (error.Code == (int)MRGSAuthenticationErrorCode.ConnectionFailed)
    {
        // No network, try later     
    }
    else
    {
        // Logout user from app (MRGS will logout automatically in SDK)
    }
});
//An object is returned that combines information about the user (identifier, name, email, etc.) and about the token.
[[MRGSAuthenticationVKontakte sharedInstance] getCredentials:^(MRGSAuthenticationCredential *credentials, NSError *error) {
    NSLog(@"Result - %@. Error - %@", credentials, error);
    if(!error){
        // Credentials data work
    }
}];

//Information about the user, identifier, name, email, etc. is returned separately.
[[MRGSAuthenticationVKontakte sharedInstance] getCurrentUser:^(MRGSAuthenticationUser *user, NSError *error) {
    NSLog(@"User - %@. Error - %@", user, error);
    if(!error){
        // User data work
    }
}];

//Information about token and expiration date
[[MRGSAuthenticationVKontakte sharedInstance] getAccessToken:^(MRGSAuthenticationAccessToken *token, NSError *error) {
    if (!error) {
        NSLog(@"getAccessToken result - %@", token);
    } else {
        NSLog(@"getAccessToken error - %@", error);
    }
}];
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.MRGSAccessToken;
import games.my.mrgs.authentication.MRGSAuthentication;
import games.my.mrgs.authentication.MRGSUser;
import games.my.mrgs.utils.optional.BiConsumer;
import games.my.mrgs.authentication.vk.MRGSVK;

// Returns user's information.
MRGSVK.getInstance().getCurrentUser(new MRGSAuthentication.UserCallback() {
    @Override
    public void onSuccess(@NonNull final MRGSUser user) {
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

// Returns authentication's information.
MRGSVK.getInstance().getAccessToken(new BiConsumer<MRGSAccessToken, MRGSError>() {
    @Override
    public void accept(@Nullable MRGSAccessToken accessToken, @Nullable MRGSError error) {
        if (error != null) {
            Log.d("MRGSAuthentication", "AccessToken error: " + error.getErrorText());
        } else {
            Log.d("MRGSAuthentication", "AccessToken success: " + accessToken);
        }
    }
});

Logout🔗

In order to "log out" of a user’s account, use the method:

MRGSAuthenticationVKontakte.Instance.Logout();
[[MRGSAuthenticationVKontakte sharedInstance] logout];
import games.my.mrgs.authentication.vk.MRGSVK;

MRGSVK.getInstance().logout();

Additional features🔗

Please note that if you requested additional permissions from the user to access additional fields of his profile, we will request them automatically and the data will appear either in the corresponding fields of the object of the MRGSAuthenticationUser class, or in the optionalParams field of this object.

Using MRGSAuthenticationSocialNetwork interface🔗

The protocol for working with social networks is MRGSAuthenticationSocialNetwork. It allows you to receive the user's friends, his profile picture, make game requests and invitations to the game, and also open the "share" page.

Getting avatar🔗

In order to get a user avatar with a given identifier, use the method:

MRGSAuthenticationVKontakte.Instance.GetAvatar("required_user_id", MRGSAuthenticationPhotoSize.Small, (Texture2D avatar, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
    }
});
[[MRGSAuthenticationVKontakte sharedInstance] getAvatarForPlayerWithId: @"required_user_id" size:GKPhotoSizeSmall completionHandler:^(UIImage *image, NSError *error) {
    if(!error){
        // Operation completed successfully, work with data
    }
}];
import android.graphics.Bitmap;

import androidx.annotation.NonNull;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.MRGSAvatarCallback;
import games.my.mrgs.authentication.vk.MRGSVK;

// Call #getCurrentUser() to get current user.
final MRGSUser user = ...
// Get user's avatar.
MRGSVK.getInstance().getUserAvatar(user, new MRGSAvatarCallback() {
    @Override
    public void onSuccess(@NonNull Bitmap bitmap) {
        // Handle result.
    }

    @Override
    public void onError(@NonNull MRGSError error) {
        // Handle error.
    }
});

Getting friends list and information about user🔗

To get friends list of the current user please use method:

MRGSAuthenticationVKontakte.Instance.GetFriendsIds((List<string> ids, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
    }
});
[[MRGSAuthenticationVKontakte sharedInstance] getFriendsIds:^(NSArray *ids, NSError *error) {
    if(!error){
        // Operation completed successfully
    }
}];
import androidx.annotation.NonNull;

import java.util.List;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.MRGSSocial;
import games.my.mrgs.authentication.MRGSUser;
import games.my.mrgs.authentication.vk.MRGSVK;

MRGSVK.getInstance().getFriends(new MRGSSocial.FriendsCallback() {
    @Override
    public void onSuccess(@NonNull List<MRGSUser> users) {
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

Important

For this method to work, permission to the friends list is required. (permission must be set in method login).

In order to get an object with a user description with a given identifier, use the method:

MRGSAuthenticationVKontakte.Instance.GetUser("required_user_id",(MRGSAuthenticationUser user, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
    }
});
[[MRGSAuthenticationVKontakte sharedInstance] getUserWithId:@"required_user_id" completionHandler:^(MRGSAuthenticationUser *user, NSError *error) {
    if(!error){
        // Operation completed successfully
    }
}];
import androidx.annotation.NonNull;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.MRGSAuthentication;
import games.my.mrgs.authentication.MRGSUser;
import games.my.mrgs.authentication.vk.MRGSVK;

MRGSVK.getInstance().getUserWithId("userId", new MRGSAuthentication.UserCallback() {
    @Override
    public void onSuccess(@NonNull MRGSUser user) {
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

In order to get objects with user descriptions with given identifiers, use the method:

MRGSAuthenticationVKontakte.Instance.GetUsers(ids,(List<MRGSAuthenticationUser> users, MRGSError error) => { 
    if(error == null){
        // Operation completed sucessfully
    }
});
[[MRGSAuthenticationVKontakte sharedInstance] getUsersWithIds: @[@"required_user_id_1", @"required_user_id_2"] completionHandler:^(NSArray<MRGSAuthenticationUser*>* users, NSError *error) {
    if(!error){
        // Operation completed successfully
    }
}];
import androidx.annotation.NonNull;

import java.util.Arrays;
import java.util.List;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.MRGSSocial;
import games.my.mrgs.authentication.MRGSUser;
import games.my.mrgs.authentication.vk.MRGSVK;

MRGSVK.getInstance().getUsersWithId(Arrays.asList("user_id_1", "user_id_2"), new MRGSSocial.FriendsCallback() {
    @Override
    public void onSuccess(@NonNull List<MRGSUser> users) {
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

Creating post on user wall🔗

In order to open the dialog for creating a new post in the current user’s feed with the specified parameters, use the method:

var post = new MRGSAuthenticationPost();
post.Caption = "MRGS Framework - powerful tool for game development.";
post.Link = "http://mrgs.astrum.team";
post.Message = "Check out MRGS site!";
post.LocalImageURL = System.IO.Path.Combine(Application.dataPath.Replace("/Data", ""), "forest.jpg");

MRGSAuthenticationVKontakte.Instance.ShowPostOnWallDialog(post, (MRGSError error) => {
    if(error == null){
        // Operation completed successfully
    }
});
post.caption = @"MRGS Framework - powerful tool for game development.";
post.link = @"http://mrgs.astrum.team";
post.message = @"Check out MRGS site!";
post.image = [UIImage imageNamed:@"MRGSLogo"];

[[MRGSAuthenticationVKontakte sharedInstance] showPostOnWallDialog:post completionHandler:^(NSError *error) {
    if(!error){
        // Operation completed successfully
    }
}];
Opening a dialog is not supported in VK SDK 2.x, use the postOnWall method

Important

A dialog will open for creating a new post with the filled data specified in MRGSAuthenticationPost. For VKontakte, all fields are used in the MRGSAuthenticationPost object, i.e. caption,link, message and image.

Sending game invites and game requests🔗

To send invitations to the game and game requests (using them you can send "gifts" in some cases), as well as check incoming requests, the methods below are provided. The methods accept an MRGSAuthenticationInvite object, which indicates the invitation text, a list of users to be invited, and other request parameters (see the fields of the MRGSAuthenticationInvite class). The user will be shown a dialog for confirmation. In the response, if successful, an MRGSAuthenticationInvite object will be returned with filled in fields, such as request identifier, sent users.

//  Sending invite in game
var inviteIn = new MRGSAuthenticationInvite();
inviteIn.Message = @"Test invite message";
inviteIn.UserIdsToInvite = new List<string>() { "30907315" };

MRGSAuthenticationVKontakte.Instance.SendInvite(inviteIn, (MRGSAuthenticationInvite inviteOut, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
        Debug.Log("Sended invite - " + inviteOut);
    }
});

// Sanding game request
var inviteIn = new MRGSAuthenticationInvite();
inviteIn.Message = @"Test invite message";
inviteIn.UserIdsToInvite = new List<string>() { "30907315" }; 

MRGSAuthenticationVKontakte.Instance.SendGameRequest(inviteIn, (MRGSAuthenticationInvite inviteOut, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
        Debug.Log("Sended game request - " + inviteOut);
    }
});
// Sending invite in game
MRGSAuthenticationInvite *invite = [[MRGSAuthenticationInvite alloc] init];
invite.message = @"Test invite message";
invite.userIdsToInvite = @[@"30907315"];

[[MRGSAuthenticationVKontakte sharedInstance] sendInvite:invite completionHandler:^(MRGSAuthenticationInvite* inviteOut,NSError *error) {
    if(!error){
        // Operation completed sucessfully
        NSLog(@"Sended invite - %@", inviteOut);
    }
}];

// Sending game request
MRGSAuthenticationInvite *invite = [[MRGSAuthenticationInvite alloc] init];
invite.message = @"Test invite message";
invite.userIdsToInvite = @[@"30907315"];

[[MRGSAuthenticationVKontakte sharedInstance] sendGameRequest:invite completionHandler:^(MRGSAuthenticationInvite* inviteOut, NSError *error) {
    if(!error){
        // Operation completed sucessfully
        NSLog(@"Sended request - %@", inviteOut);
    }
}];
import androidx.annotation.NonNull;

import java.util.Collections;
import java.util.List;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.MRGSSocial;
import games.my.mrgs.authentication.vk.MRGSVK;

// Send invite request
MRGSVK.getInstance().sendGameRequest("Game Request",
        "Invite message", 
        true,
        Collections.singletonList(friend), 
        new MRGSSocial.GameRequestResultCallback() {
            @Override
            public void onSuccess(@NonNull List<String> users) {
                //users were invited in game
            }

            @Override
            public void onError(@NonNull MRGSError error) {
            }
        });

// Send game request
MRGSVK.getInstance().sendGameRequest("Game Request", 
        "Game request message", 
        false,
        Collections.singletonList(friend),
        new MRGSSocial.GameRequestResultCallback() {
            @Override
            public void onSuccess(@NonNull List<String> users) {
                //users were invited in game
            }

            @Override
            public void onError(@NonNull MRGSError error) {
            }
        });

Important

Sending invites and game requests is available only after reviewing the application on the VKontakte side. To test the work before the review, you can send requests and invitations only between administrators of the application.

Also, the method for receiving incoming game requests getGameRequests always returns an error, since VKontakte does not have such an API, but the method is left for compatibility with the MRGSAuthenticationSocialNetwork interface.

Additional features of VKontakte🔗

Also, MRGSAuthenticationVKontakte offers several additional features exclusively for working with VKontakte:

Posting posts without user approvement🔗

To publish a post without user confirmation on its wall, or the wall of another person, use the methods:

// Post on current user's wall
var post = new MRGSAuthenticationPost();
post.Caption = @"MRGS Framework - powerful tool for game development.";
post.Link = @"http://mrgs.astrum.team";
post.Message = @"Check out MRGS site!";
post.LocalImageURL = System.IO.Path.Combine(Application.dataPath.Replace("/Data", ""), "forest.jpg");

MRGSAuthenticationVKontakte.Instance.SendPostOnWall(post, (MRGSError error) => {
    if(error == null){
        // Operation completed successfully
    }
});

// Posting on another user's wall
var post = new MRGSAuthenticationPost();
post.Caption = @"MRGS Framework - powerful tool for game development.";
post.Link = @"http://mrgs.astrum.team";
post.Message = @"Check out MRGS site!";
post.LocalImageURL = System.IO.Path.Combine(Application.dataPath.Replace("/Data", ""), "forest.jpg");

MRGSAuthenticationVKontakte.Instance.SendPostOnWall(post, "dest_user_id", (MRGSError error) => {
    if(error == null){
        // Operation completed successfully
    }
});
// Post on current user's wall
MRGSAuthenticationPost *post = [[MRGSAuthenticationPost alloc] init];
post.caption = @"MRGS Framework - powerful tool for game development.";
post.link = @"http://mrgs.astrum.team";
post.message = @"Check out MRGS site!";
post.image = [UIImage imageNamed:@"MRGSLogo"];

[[MRGSAuthenticationVKontakte sharedInstance] sendPostOnWall:post completionHandler:^(NSError *error) {
    if(!error){
        // Operation completed successfully
    }
}];

// Post on user wall
MRGSAuthenticationPost *post = [[MRGSAuthenticationPost alloc] init];
post.caption = @"MRGS Framework - powerful tool for game development.";
post.link = @"http://mrgs.astrum.team";
post.message = @"Check out MRGS site!";
post.image = [UIImage imageNamed:@"MRGSLogo"];

[[MRGSAuthenticationVKontakte sharedInstance] sendPostOnWall:post toUserWithId:@"345031059" completionHandler:^(NSError *error) {
    if(!error){
        // Operation completed successfully
    }
}];
import androidx.annotation.NonNull;

import java.util.Arrays;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.vk.MRGSVK;
import games.my.mrgs.authentication.vk.MRGSVK.MRGSVKPostOnWall;

final MRGSVKPostOnWall post = new MRGSVKPostOnWall();
// You can set current vk user id or id or another vk user 
post.setUserId("userId to send");
post.setMessage("Text message");
post.setPhotoUris(Arrays.asList("file:///", "https://"));
// Publish only for friends
post.setFriendsOnly(onlyForFriends);

MRGSVK.getInstance().postOnWall(post, new MRGSVK.MRGSPostOnWallCallback() {
    @Override
    public void onSuccess(int postId) {
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

Important

Permission is required to publish posts (Wall), and if you want to attach photos, then permission to access photos (photos)

Extended methods getting user friends🔗

To get a list of friends who installed your application, a list of friends to whom you can send an invitation to install the application (that is, those who did not install it), and a list of friends to whom you can send a game request (that is, who installed the application, but the path to the API is different and not requires permission to access the list of friends), methods are provided:

// Get a list of friends who installed your application
MRGSAuthenticationVKontakte.Instance.GetInAppFriendsIds((List<string> ids, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
    }
});

// Getting a list of friends to whom you can send an invitation to install the application (that is, those who did not install it)
MRGSAuthenticationVKontakte.Instance.GetFriendsIdsAvailableForInvite((List<string> ids, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
    }
});

// Getting a list of friends to whom you can send a game request (that is, who installed the application)
MRGSAuthenticationVKontakte.Instance.GetFriendsIdsAvailableForGameRequest((List<string> ids, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
    }
});
// Get a list of friends who installed your application
[[MRGSAuthenticationVKontakte sharedInstance] getInAppFriendsIds:^(NSArray *ids, NSError *error) {
    if(!error){
        // Operation completed sucessfully
    }
}];

// Getting a list of friends to whom you can send an invitation to install the application (that is, those who did not install it)
[[MRGSAuthenticationVKontakte sharedInstance] getFriendsIdsAvailableForInvite:^(NSArray *ids, NSError *error) {
    if(!error){
        // Operation completed sucessfully
    }
}];

// Getting a list of friends to whom you can send a game request (that is, who installed the application)
[[MRGSAuthenticationVKontakte sharedInstance] getFriendsIdsAvailableForGameRequest:^(NSArray *ids, NSError *error) {
    if(!error){
        // Operation completed sucessfully
    }
}];
import androidx.annotation.NonNull;

import java.util.List;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.vk.MRGSVK;
import games.my.mrgs.authentication.vk.MRGSVK.MRGSUserIdsCallback;

// Getting a list of friends to whom you can send an invitation to install the application (that is, those who have not installed it)
MRGSVK.getInstance().getFriendsForInvite(new MRGSUserIdsCallback() {
    @Override
    public void onSuccess(@NonNull List<Integer> userIds) {
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

// Getting a list of friends to whom you can send a game request (that is, those who have installed the application)
MRGSVK.getInstance().getFriendsForGameRequest(new MRGSUserIdsCallback() {
    @Override
    public void onSuccess(@NonNull List<Integer> userIds) {
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

Important

The getInAppFriendsIds method requires permission to view friends (Friends). For the other two methods, this permission is not required.

Using groups API🔗

There are several methods to work with groups api:

// Join group
MRGSAuthenticationVKontakte.Instance.JoinGroup("29370987", (MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
    }
});

// Leave group
MRGSAuthenticationVKontakte.Instance.LeaveGroup("29370987", (MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
    }
});

// Checking if user member of a group
MRGSAuthenticationVKontakte.Instance.IsGroupMember("29370987", (bool isMember, MRGSError error) => {
    if(error == null){
        // Operation completed sucessfully
        if(isMember == true){
            // Group member
        }else{
            // Not group member
        }
    }
});
// Join group
[[MRGSAuthenticationVKontakte sharedInstance] joinGroup:@"29370987" completionHandler:^(NSError *error) {
    if(!error){
        // Operation completed sucessfully
    }
}];

// Leave group
[[MRGSAuthenticationVKontakte sharedInstance] leaveGroup:@"29370987" completionHandler:^(NSError *error) {
    if(!error){
        // Operation completed sucessfully
    }
}];

// Checking if user member of a group
[[MRGSAuthenticationVKontakte sharedInstance] isGroupMember:@"29370987" completionHandler:^(BOOL isMember, NSError *error) {
    if(!error){
        // Operation completed sucessfully
        if(isMember == true){
            // Group member
        }else{
            // Not group member
        }
    }
}];
import androidx.annotation.NonNull;

import games.my.mrgs.MRGSError;
import games.my.mrgs.authentication.vk.MRGSVK;
import games.my.mrgs.authentication.vk.MRGSVK.MRGSGroupCallback;

// Join the group
MRGSVK.getInstance().joinGroup("groupId", new MRGSGroupCallback() {
    @Override
    public void onSuccess(boolean status) {
        //success if status == true
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

// Leave the group
MRGSVK.getInstance().leaveGroup("groupId", new MRGSGroupCallback() {
    @Override
    public void onSuccess(boolean status) {
        //success if status == true
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

// Check if the user is the member of this group
MRGSVK.getInstance().isGroupMember("groupId", new MRGSGroupCallback() {
    @Override
    public void onSuccess(boolean status) {
        //success if status == true
    }

    @Override
    public void onError(@NonNull MRGSError error) {
    }
});

Important

These methods require permission to work with Groups. No dialogs will be shown to the user.


Last update: 2025-01-21
Created: 2020-05-28