Vk sdk php composer

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

tsivarev/vk-php-sdk

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

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.69.

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

composer require vk/php-sdk

Create VKApiClient object using the following code:

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

$vk = new VKApiClient(VKLanguage::ENGLISH, '5.69');

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.

3.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:

3.1.1. For getting user access key use following command:

$oauth->authorize(OAuthResponseType::CODE, '', '', '' [, '', '']);

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

$oauth->authorize(OAuthResponseType::CODE, '', '', '' [, '', '', ']');

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

As a » you should pass a constant from the OAuthDisplay class. The » should be an array of constants from the OAuthUserScope class. » is array of community id`s you want to get access.

User access key example:

$oauth->authorize(OAuthResponseType::CODE, 6125390, 'http://example.com', OAuthDisplay::POPUP, array(OAuthUserScope::AUDIO, OAuthUserScope::DOCS), 'some state');

Community access key example:

$oauth->authorize(OAuthResponseType::CODE, 6125390, 'http://example.com', array(149019044), OAuthDisplay::POPUP, array(OAuthGroupScope::MESSAGES), 'some state');

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:

Then use this method to get the access token:

$access_token = $oauth->getAccessToken('', '', '', '');

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

$access_token = $oauth->getAccessToken(6125390, 'Dv3Ef3srY3d2GE1c1X0F', 'http://example.com', '4g2h79rd3f7580a23d');

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

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

3.2.1. For getting user access key use following command:

$oauth->authorize(OAuthResponseType::TOKEN, '', '', '' [, '', '', ]);

Note: if you want to make user getting access anyway, set as 1 .

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

$oauth->authorize(OAuthResponseType::TOKEN, '', '', '' [, '', '', '');

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 GET parameter to the specified address:

For user access key will be:

http://REDIRECT_URI#access_token=533bacf01e11f55b536a565b57531ad114461ae8736d6506a3&expires_in=86400&user_id=8492&state=123456

And for community access key:

http://REDIRECT_URI#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.

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

Example of calling method users.get:

$response = $vk->users()->get($access_token, array( 'user_ids' => array(1, 210700286), 'fields' => $array('city', 'photo'), ) );

Uploading Photos into a Private Message

Please read the full manual before the start.

Call photos.getMessagesUploadServer to receive an upload address:

$address = $vk->photos()->getMessagesUploadServer('');

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

$photo = $vk->request()->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:

$response_save_photo = $vk->photos()->saveMessagesPhoto($access_token, array( '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.

Please read the full manual before the start.

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

$address = $vk->video()->save($access_token, array( 'name' => 'My video', ) );

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

$video = $vk->request()->upload($address['upload_url'], 'video_file', 'video.mp4');

Videos are processed for some time after uploading.

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

$vk->groups()->setLongPollSettings($access_token, array( 'group_id' => 159895463, 'enabled' => 1, 'message_new' => 1, 'wall_post_new' => 1, ));

Override methods from CallbackApiHandler class for handling events:

class CallbackApiMyHandler extends CallbackApiHandler < 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 CallbackApiLongPollExecutor class and call method listen():

$handler = new CallbackApiMyHandler(); $executor = new CallbackApiLongPollExecutor($vk, '', '', $handler, ''); $executor->listen();

Parameter » 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.

$executor = new CallbackApiLongPollExecutor($vk, $access_token, 159895463, $handler, 25); $executor->listen(12);

CallbackApi handler will wait until VK send notification about event when it happened you may handle this event. More information here.

You should to configure Callback API inside your community settings.

First step will be approve your domain. VK sends you request to your server with event type confirmation and you should to send back confirmation string. In other types of event you should to send back ok string.

use VK\CallbackApi\Server\CallbackApiServerHandler; class CallbackServer extends CallbackApiServerHandler < const SECRET = 'ab12aba'; const GROUP_ID = 123999; const CONFIRMATION_TOKEN = 'e67anm1'; function confirmation(int $group_id, ?string $secret) < if ($secret === static::MY_SECRET && $group_id === static::GROUP_ID) < echo static::CONFIRMATION_TOKEN; > > public function messageNew(int $group_id, ?string $secret, array $object) < echo 'ok'; > > $callback_handler = new CallbackServer(); $data = json_decode(file_get_contents('php://input')); $callback_handler->parse($data);

To handle events you should to override methods from CallbackApiServerHandler class like this.

confirmation event handler contains 2 fields: group id, and secret key. You must to override confirmation method.

Источник

VK api SDK установка и подключение, как правильно?

Не получается вникнуть в суть. Сегодня первый раз в жизни с git установил что-то на сайт через терминал.
Решил полюбопытствовать как устроена VK api SDK, но даже подключить не получилось ))))
В сети инфы мало, в инструкции об этом ни слова.

В какую папку надо устанавливать SDK? в pablic_html?
Подключать я так понял можно autoload.php а дальше уже функциями, а подтянет нужные файлы он сам?

dimastik1986

Вот рабочий вариант, проблема была в том, что нельзя использовать классы, которые находятся не в одном пространстве имён с текущим сценарием.

require_once __DIR__.'/vendor/autoload.php'; use \VK\Client\VKApiClient; use \VK\OAuth\VKOAuth; use \VK\OAuth\VKOAuthDisplay; use \VK\OAuth\Scopes\VKOAuthUserScope; use \VK\OAuth\VKOAuthResponseType; $vk = new VKApiClient(VER); $oauth = new VKOAuth(); $client_id = API_CLIENT_ID; $redirect_uri = REDIR; $display = VKOAuthDisplay::PAGE; $scope = array(VKOAuthUserScope::WALL, VKOAuthUserScope::GROUPS); $state = 'secret_state_code'; $browser_url = $oauth->getAuthorizeUrl(VKOAuthResponseType::CODE, $client_id, $redirect_uri, $display, $scope, $state); print $browser_url;

Здравствуйте, можете помочь с персональной проблемой настройки VK-бота? пожалуйста свяжитесь со мной 592530210_turbo@mail.ru

Пришло время открывать для себя чудесный мир пакетных менеджеров!

1. Для начала устанавливаем composer: https://getcomposer.org/doc/00-intro.md
2. Следуя инструкции (https://github.com/VKCOM/vk-php-sdk), в папке с проектом пишем: composer require vkcom/vk-php-sdk
3. У вас появятся файлы composer.json, composer.lock и папка vendor.
3. Создаём рядом с ними index.php и подключаем пакеты, установленные через composer:

dimastik1986

Вроде как все сделал как вы сказали, проверил актуальность id и тд?
Не работает (((

$vk = new VK\Client\VKApiClient(); $oauth = new VK\Client\VKOAuth(); $client_id = API_CLIENT_ID; $redirect_uri = 'http://site.ru/index.php'; $display = VKOAuthDisplay::PAGE; $scope = array(VKOAuthUserScope::WALL, VKOAuthUserScope::GROUPS); $state = 'secret_state_code'; $browser_url = $oauth->getAuthorizeUrl(VKOAuthResponseType::CODE, $client_id, $redirect_uri, $display, $scope, $state);

__DIR__ не надо менять на public_html, оставьте прямо так — это константа PHP, которая означает текущую папку. error_reporting желательно включить, чтобы видеть описание ошибки, а не просто 500.

dimastik1986

antoo, я не менял, я просто показал где лежит, а константа на месте.
в общем, методом научного тыка перестала ошибку кидать на $vk = new \VK\Client\VKApiClient(‘5.92’);
но какой бы адрес я не прописывал для

Митя ТоДаСё, https://github.com/VKCOM/vk-php-sdk/blob/4d270e1c0. — он на месте.
Какая версия PHP? Вы точно через composer ставите, а не просто файлы копируете?

dimastik1986

5c0c0e935daeb811851449.jpeg

  • где что лежит, прикладываю скрином к сообщению, получается файлы сайта, на уровень назад — pablic_html, перед ним папка сайта, и в самом начале корень, в котором лежит .local в котором установлен composer
  • может быть я не туда установил или еще где накосячил?

    Митя ТоДаСё, `composer-php7.2` — довольно странная команда, каким образом вы её выполняете и где? Что выводит в ответ?
    Папка vk-php-sdk должна быть в vendor, но она должна сама там создаться (не руками), каким образом она появилась в корне — непонятно, можете удалять оттуда.

    dimastik1986

    antoo, это мне посоветовала служба поддержки.
    я руками ничего не трогал )) я прекрасно понимаю, что вся суть этой затей — автоматическая установка, а не в ручную файлы заливать.
    может мне удалить composer и sdk и по новой все сделать, находясь в тех папках, которые вы порекомендуете? как правильно удалить?

    vp2vk@dock2:~ [0] $ composer-php7.2 update Loading composer repositories with package information Updating dependencies (including require-dev) Nothing to install or update Generating autoload files vp2vk@dock2:~ [2] $ composer-php7.2 install Loading composer repositories with package information Installing dependencies (including require-dev) from lock file Package operations: 1 install, 0 updates, 0 removals - Installing vkcom/vk-php-sdk (5.80.1): Downloading (100%) Generating autoload files

    Источник

    Читайте также:  Roadmap java на русском
    Оцените статью