- Saved searches
- Use saved searches to filter your results more quickly
- License
- VKCOM/vk-php-sdk
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Сообщения с сайта в ВК – просто и эффективно – PHP+CUrl
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.
PHP library for working with VK API
License
VKCOM/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.131
The VK PHP SDK can be installed using Composer by running the following command:
composer require vkcom/vk-php-sdk
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\Client\Enums\VKLanguage::ENGLISH);
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:
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.
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:
$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.
You can find the full list of VK API methods here.
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('');
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.
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.
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.
$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);
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.
Сообщения с сайта в ВК – просто и эффективно – PHP+CUrl
Доставка сообщений в ВК удобна большинству сайтов разной направленности: емайлы многие не читают, в таких мессенджерах как Вотсап и Вайбер все сложно. А рассылка новостей и личных уведомлений с сайта в ВК – самое то – легко, просто и сразу видно пользователю.
Для своего сервиса уведомлений о новых объявлениях мне необходимо быстро и бесплатно доставлять уведомления о новых объявлениях пользователям. Базовый канал – емайл – не удобен. Другой хороший канал – мессенджер Телеграмм – решил побороться за приватность и стал не надежен. Поэтому пришлось добавить альтернативу в виде ВК (тем более что сервис умеет еще отслеживать группы в ВК на появление новых записей и комментариев). Был приятно удивлен простотой и продуманностью настройки, даже Телеграмм рядом не стоял.
1. Подключаем виджет «Разрешить писать сообществу»
Виджет выглядит в виде кнопки. Я встроил кнопку в настройки аккаунта пользователя сервиса.
В тексте нужно заменить 74449217 на id своей группы. Также продумать куда будет сохраняться полученный userId ВКонтакте. В приведенном ниже коде он присваивается полю vk_id, а потом сохраняется вместе с другими настройками.
Разрешение от пользователя у нас получено, теперь организуем отправку сообщений.
В настройках своего сообщества включаем сообщения сообщества.
Генерируем токен своего сообщества.
В общем все готово. Для отправки сообщения используем PHP+CUrl. В функцию отправки в качестве входных параметров передаем ранее полученный id пользователя ВК и текст сообщения. Также функция использует константы vk_token – токен сообщества.
//отправка сообщения в vk function send_vk($vk_id, $text_source) < $url="https://api.vk.com/method/messages.send?user_id=$vk_id&v=5.76&access_token=".vk_token; $text=rawurlencode($text_source); $ch = curl_init($url); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POSTFIELDS, "&message=".$text); $hh=curl_exec($ch); //если отправка не удалась if (!strpos(" ".$hh,'<"response":')) < //если нет сообщения об ошибке, отправляем повторно if (!strpos(" ".$hh,'error')) <$hh=curl_exec($ch);>> $html=$hh; curl_close($ch); return $html; >
Вместе с изучением возможностей и материала я потратил на организацию отправки оповещений в ВК один день — считаю, что это один из самых простых вариантов коммуникации с пользователем.