• Stars
    star
    204
  • Rank 192,063 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP library for working with VK API

vk-php-sdk

PHP library for VK API interaction, includes OAuth 2.0 authorization and API methods. Full VK API features documentation can be found here.

This library has been created using the VK API JSON Schema. It can be found here. It uses VK API version 5.131

Packagist

1. Prerequisites

  • PHP 8.1

2. Installation

The VK PHP SDK can be installed using Composer by running the following command:

composer require vkcom/vk-php-sdk

3. Initialization

Create VKApiClient object using the following code:

$vk = new \VK\Client\VKApiClient();

Also you can initialize VKApiClient with different API version and different language like this:

$vk = new VKApiClient('5.131');
$vk = new VKApiClient('5.131', \VK\Client\Enums\VKLanguage::ENGLISH);

4. Authorization

The library provides the authorization flows for user based on OAuth 2.0 protocol implementation in vk.com API. Please read the full documentation before you start.

4.1. Authorization Code Flow

OAuth 2.0 Authorization Code Flow allows calling methods from the server side.

This flow includes two steps — obtaining an authorization code and exchanging the code for an access token. Primarily you should obtain the "code" (manual user access and manual community access) by redirecting the user to the authorization page using the following method:

Create VKOAuth object first:

$oauth = new \VK\OAuth\VKOAuth();

4.1.1. For getting user access key use following command:

$oauth = new \VK\OAuth\VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';
$display = \VK\OAuth\VKOAuthDisplay::PAGE;
$scope = [\VK\OAuth\Scopes\VKOAuthUserScope::WALL, \VK\OAuth\Scopes\VKOAuthUserScope::GROUPS];
$state = 'secret_state_code';

$browser_url = $oauth->getAuthorizeUrl(\VK\OAuth\VKOAuthResponseType::CODE, $client_id, $redirect_uri, $display, $scope, $state);

4.1.2. Or if you want to get community access key use:

$oauth = new \VK\OAuth\VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';
$display = \VK\OAuth\VKOAuthDisplay::PAGE;
$scope = [\VK\OAuth\Scopes\VKOAuthGroupScope::MESSAGES];
$state = 'secret_state_code';
$groups_ids = [1, 2];

$browser_url = $oauth->getAuthorizeUrl(\VK\OAuth\VKOAuthResponseType::CODE, $client_id, $redirect_uri, $display, $scope, $state, $groups_ids);

User access key and community access key uses different values inside scope array

After successful authorization user's browser will be redirected to the specified redirect_uri. Meanwhile the code will be sent as a GET parameter to the specified address:

https://example.com?code=CODE

Then use this method to get the access token:

$oauth = new \VK\OAuth\VKOAuth();
$client_id = 1234567;
$client_secret = 'SDAScasd'
$redirect_uri = 'https://example.com/vk';
$code = 'CODE';

$response = $oauth->getAccessToken($client_id, $client_secret, $redirect_uri, $code);
$access_token = $response['access_token'];

The redirect_uri should be the URL that was used to get a code at the first step.

4.2. Implicit flow

In difference with authorization code flow this flow gives you temporary access key.

Read more about user access key and community access key.

First step to get access using Implicit flow is creating VKOauth object:

$oauth = new \VK\OAuth\VKOAuth();

4.2.1. For getting user access key use following command:

$oauth = new \VK\OAuth\VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';
$display = \VK\OAuth\VKOAuthDisplay::PAGE;
$scope = [\VK\OAuth\Scopes\VKOAuthUserScope::WALL, \VK\OAuth\Scopes\VKOAuthUserScope::GROUPS];
$state = 'secret_state_code';
$revoke_auth = true;

$browser_url = $oauth->getAuthorizeUrl(\VK\OAuth\VKOAuthResponseType::TOKEN, $client_id, $redirect_uri, $display, $scope, $state, null, $revoke_auth);

If you want to make user getting access anyway, set revoke_auth as true.

4.2.2. Or if you want to get community access key use:

$oauth = new \VK\OAuth\VKOAuth();
$client_id = 1234567;
$redirect_uri = 'https://example.com/vk';
$display = \VK\OAuth\VKOAuthDisplay::PAGE;
$scope = [\VK\OAuth\Scopes\VKOAuthGroupScope::MESSAGES];
$state = 'secret_state_code';
$groups_ids = [1, 2];

$browser_url = $oauth->getAuthorizeUrl(\VK\OAuth\VKOAuthResponseType::TOKEN, $client_id, $redirect_uri, $display, $scope, $state, $groups_ids);

Arguments are similar with authorization code flow

After successful authorization user's browser will be redirected to the specified redirect_uri. Meanwhile the access token will be sent as a fragment parameter to the specified address:

For user access key will be:

https://example.com#access_token=533bacf01e11f55b536a565b57531ad114461ae8736d6506a3&expires_in=86400&user_id=8492&state=123456

And for community access key:

https://example.com#access_token_XXXXXX=533bacf01e11f55b536a565b57531ad114461ae8736d6506a3&expires_in=86400

access_token is your new access token.
expires_in is lifetime of access token in seconds.
user_id is user identifier.
state is string from authorize method.
access_token_XXXXXX is community access token where XXXXXX is community identifier.

5. API Requests

You can find the full list of VK API methods here.

5.1. Request sample

Example of calling method users.get:

$vk = new \VK\Client\VKApiClient();
$response = $vk->users()->get($access_token, [
    'user_ids'  => [1, 210700286],
    'fields'    => ['city', 'photo'],
]);

5.2. Uploading Photos into a Private Message

Please read the full manual before the start.

Call photos.getMessagesUploadServer to receive an upload address:

$vk = new \VK\Client\VKApiClient();
$address = $vk->photos()->getMessagesUploadServer('{access_token}');

Then use upload() method to send files to the upload_url address received in the previous step:

$vk = new \VK\Client\VKApiClient();
$photo = $vk->getRequest()->upload($address['upload_url'], 'photo', 'photo.jpg');

You will get a JSON object with server, photo, hash fields. To save a photo call **photos.saveMessagesPhoto ** with these three parameters:

$vk = new \VK\Client\VKApiClient();
$response_save_photo = $vk->photos()->saveMessagesPhoto($access_token, [
    'server' => $photo['server'],
    'photo'  => $photo['photo'],
    'hash'   => $photo['hash'],
]);

Then you can use owner_id and id parameters from the last response to create an attachment of the uploaded photo.

5.3. Uploading Video Files

Please read the full manual before the start.

Call video.save to get a video upload server address:

$vk = new \VK\Client\VKApiClient();
$address = $vk->video()->save($access_token, [
    'name' => 'My video',
]);

Send a file to upload_url received previously calling upload() method:

$vk = new \VK\Client\VKApiClient();
$video = $vk->getRequest()->upload($address['upload_url'], 'video_file', 'video.mp4');

Videos are processed for some time after uploading.

6. Groups updates

6.1. Long Poll

Enable Long Poll for your group and specify which events should be tracked by calling the following API method:

$vk = new \VK\Client\VKApiClient();
$vk->groups()->setLongPollSettings($access_token, [
  'group_id'      => 159895463,
  'enabled'       => 1,
  'message_new'   => 1,
  'wall_post_new' => 1,
]);

Override methods from VK\CallbackApi\VKCallbackApiHandler class for handling events:

class CallbackApiMyHandler extends VK\CallbackApi\VKCallbackApiHandler {
    public function messageNew($object) {
        echo 'New message: ' . $object['body'];
    }
    
    public function wallPostNew($object) {
        echo 'New wall post: ' . $object['text'];
    }
}

To start listening to LongPoll events, create an instance of your CallbackApiMyHandler class, instance of VK\CallbackApi\LongPoll\VKCallbackApiLongPollExecutor class and call method listen():

$vk = new \VK\Client\VKApiClient();
$access_token = 'asdj4iht2i4ntokqngoiqn3ripogqr';
$group_id = 159895463;
$wait = 25;

$handler = new CallbackApiMyHandler();
$executor = new \VK\CallbackApi\VKCallbackApiLongPollExecutor($vk, $access_token, $group_id, $handler, $wait);
$executor->listen();

Parameter wait is the waiting period.

While calling function listen() you can also specify the number of the event from which you want to receive data. The default value is the number of the last event.

Example:

$vk = new \VK\Client\VKApiClient();
$access_token = 'asdj4iht2i4ntokqngoiqn3ripogqr';
$group_id = 159895463;
$timestamp = 12;
$wait = 25;

$executor = new \VK\CallbackApi\VKCallbackApiLongPollExecutor($vk, $access_token, $group_id, $handler, $wait);
$executor->listen($timestamp);

6.2. Callback API

CallbackApi handler will wait for event notifications form VK. Once an event has occurred, you will be notified of it and will be able to handle it. More information here.

To start using Callback API you need to configure it under the "Manage community" tab of your community page.

The first step is confirming your domain. VK sends a request to your server with the event type confirmation and you need to send back a confirmation string. For other types of events you need to send back ok string.

Take a look at this example:

class ServerHandler extends \VK\CallbackApi\VKCallbackApiServerHandler {
    const SECRET = 'ab12aba';
    const GROUP_ID = 123999;
    const CONFIRMATION_TOKEN = 'e67anm1';

    function confirmation(int $group_id, ?string $secret) {
        if ($secret === static::SECRET && $group_id === static::GROUP_ID) {
            echo static::CONFIRMATION_TOKEN;
        }
    }
    
    public function messageNew(int $group_id, ?string $secret, array $object) {
        echo 'ok';
    }
}

$handler = new ServerHandler();
$data = json_decode(file_get_contents('php://input'));
$handler->parse($data);

To handle events you need to override methods from VK\CallbackApi\Server\VKCallbackApiServerHandler class as shown above.

confirmation event handler has 2 arguments: group id, and secret key. You need to override this method.

More Repositories

1

kphp

KPHP — a PHP compiler
C++
1,322
star
2

VKUI

VKUI – это набор React-компонентов, с помощью которых можно создавать интерфейсы, внешне неотличимые от наших iOS и Android приложений.
TypeScript
995
star
3

YouTokenToMe

Unsupervised text tokenizer focused on computational efficiency
C++
951
star
4

noverify

Pretty fast linter (code static analysis utility) for PHP
Go
667
star
5

vk-android-sdk

Android library for working with VK API, authorization through VK app, using VK functions.
Kotlin
458
star
6

vk-ios-sdk

iOS library for working with VK API, authorization through VK app, using VK functions
Objective-C
298
star
7

vk-java-sdk

Java library for working with VK API
Java
290
star
8

vk-api-schema

JSON Schema of VK API
Shell
206
star
9

statshouse

StatsHouse is a highly available, scalable, multitenant monitoring system
C
206
star
10

vkompose

Kotlin Compiler Plugins, an IDEA Plugin, and a Detekt Rule that will help to improve your experience with Jetpack Compose
Kotlin
190
star
11

kittenhouse

Go
185
star
12

lighthouse

Lightweight interface for ClickHouse
JavaScript
185
star
13

joy4

Golang audio/video library and streaming server
Go
180
star
14

nocolor

Validate the architecture of your PHP project based on the concept of function colors
Go
161
star
15

nginx-quic

C
151
star
16

KNet

Android network library with QUIC protocol supporting.
Kotlin
148
star
17

nocc

A distributed C++ compiler: like distcc, but faster
Go
142
star
18

bot-example-php

Пример бота для VK
PHP
134
star
19

icons

Набор SVG иконок, представленный в виде React компонентов.
JavaScript
124
star
20

vk-bridge

A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web
TypeScript
70
star
21

php-parser

PHP parser written in Go
Go
69
star
22

modulite

A plugin for PHPStorm that brings modules to the PHP language
Kotlin
65
star
23

vk-qr

VK QR Code generator library
TypeScript
58
star
24

create-vk-mini-app

Create VK Apps with no build configuration.
TypeScript
53
star
25

vk-miniapps-deploy

NPM module for deploy VK Mini Apps on VK hosting
JavaScript
49
star
26

kphpstorm

A PhpStorm plugin that makes IDE understand KPHP specifics
Kotlin
41
star
27

vkui-tokens

TypeScript
39
star
28

fastXDM

fast library for cross-domain messaging
JavaScript
39
star
29

node-vk-call

Simple API wrapper for VK.com social network
JavaScript
35
star
30

elephize

Typescript to PHP translation tool
TypeScript
33
star
31

vk-streaming-api

Go
33
star
32

vk-mini-apps-api

The official package for quick and easy development of VK Mini Apps
TypeScript
28
star
33

vk-mini-apps-router

TypeScript
27
star
34

Appearance

JavaScript
26
star
35

vkid-android-sdk

Kotlin
25
star
36

vkjs

VK shared JS libs
TypeScript
23
star
37

vk-router

TypeScript
22
star
38

vk-windowsphone-sdk

VK SDK for Windows Phone
C#
22
star
39

admstorm

PhpStorm plugin aimed at simplifying tasks at the junction of the local repository and the repository on the dev server
Kotlin
20
star
40

vk-unity-sdk

C#
20
star
41

vk-tunnel-client

TypeScript
19
star
42

kive

Go
19
star
43

tl

C++
18
star
44

vkdata-sketchplugin

Sketch plugin for using data from your account at vk.com
JavaScript
17
star
45

vk-apps-launch-params

Пример работы с параметрами запуска
JavaScript
17
star
46

nginx-http-vkupload-module

C
16
star
47

kphp-polyfills

PHP implementations of functions supported by KPHP natively (a Composer package)
PHP
15
star
48

superappkit-android-demo

Kotlin
15
star
49

vkid-web-sdk

TypeScript
15
star
50

vk-mini-apps-examples

TypeScript
15
star
51

IOSDevice

A set of hacks and workarounds for iOS Safari & Co.
JavaScript
14
star
52

docker-emulator-android

Dockerfile
13
star
53

modulite-phpstan

Bring modules into PHP and PHPStan
PHP
13
star
54

vk-apps-tensorflow-example

VK apps + tensorflow-js demo app
JavaScript
12
star
55

api-schema-typescript-generator

TypeScript
11
star
56

vkid-ios-sdk

Swift
11
star
57

api-schema-typescript

TypeScript
10
star
58

VKSDK-iOS

Swift
10
star
59

Delegate

Python
10
star
60

engine-go

Common libraries for our go engines (microservices)
Go
10
star
61

vk-direct-games-example

JavaScript
10
star
62

vk-ios-urlprotocol-example

This is an example iOS app with custom URLProtocol
Swift
10
star
63

swc-plugin-css-modules

Rust
9
star
64

vk-bridge-mock

The VK Bridge mock library
TypeScript
9
star
65

ktest

Test and benchmark KPHP code
Go
9
star
66

vk-ads-retargeting-demo

Демонстрация JavaScript API ретаргетинга ВКонтакте
HTML
8
star
67

eslint-config

JavaScript
8
star
68

useWeb3

JavaScript
8
star
69

TL-Schema-idea-plugin

Plugin for JetBrains products for coloring TL Schema files
Java
8
star
70

vk-connect-promise

A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web with events based on promises
JavaScript
8
star
71

torch_mobile

Torch7 for mobile devices
C
7
star
72

vkui-benchmarks

JavaScript
7
star
73

noverify-phpstorm

NoVerify plugin for PhpStorm
Kotlin
6
star
74

superappkit-ios

Ruby
6
star
75

swc-plugin-transform-remove-imports

Rust
6
star
76

VideoPlayer-iOS

Swift
6
star
77

statshouse-go

StatsHouse client library for Go
Go
6
star
78

create-vkui-app

JavaScript
6
star
79

m3u8

Parser and generator of M3U8-playlists for Apple HLS.
Go
5
star
80

nginx-statshouse-module

StatsHouse module for nginx
C
5
star
81

statshouse-cpp

StatsHouse client library for C++
C++
5
star
82

statshouse-php

StatsHouse client library for PHP and KPHP
PHP
5
star
83

stylelint-config

TypeScript
4
star
84

statshouse-java

Java
4
star
85

modulite-example-project

This example project contains some Modulite errors, detected by IDE, PHPStan, and KPHP
PHP
4
star
86

kphp-tools

A set of independent tools to work with KPHP compiled code
JavaScript
4
star
87

kphp-snippets

Libraries written in PHP aimed to be compiled with KPHP
PHP
4
star
88

vk-mini-apps-course-frontend

TypeScript
4
star
89

graph-cache

Easy way to build and maintain persistent dependency graph for any type of files/languges
JavaScript
4
star
90

gulp-portal

JavaScript
4
star
91

sprites

Module for generate SVG sprites and PNG fallback
JavaScript
4
star
92

swc-plugin-pre-paths

Rust
3
star
93

mask-assets

AngelScript
3
star
94

mini-apps-analytics

TypeScript
3
star
95

vk-apps-currency

JavaScript
3
star
96

eslint-plugin

JavaScript
3
star
97

vk-apps-qr

VK Apps + QR demo app
JavaScript
2
star
98

ktest-script

PHP
2
star
99

mvk-mini-apps-scroll-helper

JavaScript
2
star
100

prettier-config

JavaScript
2
star