Coder Social home page Coder Social logo

vk-php-sdk's Introduction

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.

vk-php-sdk's People

Contributors

extype avatar mobyman avatar povargek avatar rthakohov avatar tsivarev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vk-php-sdk's Issues

Баги

Я кшн извиняюсь, но столько кусков не рабочего кода я еще не видел. Зачем вы используете приват константы в классах? Вылетает ошибка, пришлось в ручную убирать их из файлов + в конструкторе уберите ?, тоже вылетает ошибка.
И переделайте документацию, чтобы вызвать $vk = new VKApiClient(); нужно прописать сначала use VK\Client\VKApiClient;

PHP ошибка Argument 1 passed to VKApiError::__construct() must be of the type array, string given

В функции parseResponse после обработки в decode_body содержится следующий массив, где error передается не как массив, а как строка

Array
(
[error] => ERR_UPLOAD_BAD_IMAGE_SIZE: market photo min size 400x400
[bwact] => do_add
[server] => 854320
[_sig] => 0192528750fa266e7558211ed60ccaee
)

из-за этого php падает с ошибкой

Uncaught TypeError: Argument 1 passed to VK\Client\VKApiError::__construct() must be of the type array, string given, called in
... VK/Client/VKApiRequest.php on line 131 and defined in ... VK/Client/VKApiError.php:27
Stack trace:
#0 ... VK/Client/VKApiRequest.php(131): VK\Client\VKApiError->_construct('ERR_UPLOAD_BAD...')
#1 ... VK/Client/VKApiRequest.php(110): VK\Client\VKApiRequest->parseResponse(Object(VK\TransportClient\TransportClientResponse))
#2 xyz.php(2): VK\Client\VKApiRequest->upload('https://pu1-28....', 'file', '/home/c/92524...')

OAuth authorization cannot be used from native VK applications

I'm getting this issue when I try to give my app permission to connect to my account.
Here is my code, nothing special:

$oauth = new VKOAuth();
$client_id = ;
$redirect_uri = 'https://domaine.com/web/app_dev.php/en/back/callback-vk';
$display = VKOAuthDisplay::PAGE;
$scope = array(VKOAuthUserScope::WALL, VKOAuthUserScope::GROUPS);
$state = "
**************";
return $this->redirect ($oauth->getAuthorizeUrl(VKOAuthResponseType::CODE, $client_id, $redirect_uri, $display, $scope, $state));

And here is the error code returned by VK:
{"error":"invalid_request","error_description":"OAuth authorization cannot be used from native VK applications"}
Please help me to fix this issue.

Example 6.1 error

Example 6.1

`Warning: Declaration of CallbackApiMyHandler::messageNew($object) should be compatible with VK\CallbackApi\VKCallbackApiHandler::messageNew(int $group_id, ?string $secret, array $object) in on line 17

Warning: Declaration of CallbackApiMyHandler::wallPostNew($object) should be compatible with VK\CallbackApi\VKCallbackApiHandler::wallPostNew(int $group_id, ?string $secret, array $object) in on line 21
PHP Warning: Declaration of CallbackApiMyHandler::messageNew($object) should be compatible with VK\CallbackApi\VKCallbackApiHandler::messageNew(int $group_id, ?string $secret, array $object) in on line 17
PHP Warning: Declaration of CallbackApiMyHandler::wallPostNew($object) should be compatible with VK\CallbackApi\VKCallbackApiHandler::wallPostNew(int $group_id, ?string $secret, array $object) in on line 21`
code:

`require 'vendor/autoload.php';

const ACCESS_TOKEN = '*';

const GROUP_ID = *;

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

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'];
}

}

$handler = new CallbackApiMyHandler();
$executor = new VK\CallbackApi\LongPoll\VKCallbackApiLongPollExecutor($vk, ACCESS_TOKEN, GROUP_ID, $handler, 25);
$executor->listen();`

Конвертация объектов keyboard и template

Добрый вечер! Я пользуюсь библиотекой vk php sdk очень давно, я написал большое кол-во проектов связанных с ботами и с использованием api вконтакте. Мои коллеги и я сам столкнулся с тем, что конструировать объекты клавиатур или недавно появившихся темплейтов без библиотеки или какой-то тулзы довольно сложно. Не так давно я выложил свою библиотеку по конструированию таких объектов (https://github.com/Sally-Framework/vk-keyboard).

В связи с этим я хотел задать вопрос. Могу ли я адаптировать свою библиотеку в вашу php sdk, если вы сочтёте её приемлемой?

Неотловимый Exception при загрузке файла через video.save

Шаги воспроизведения:

  1. Создать любой файл который не является видео.
  2. Попытаться его загрузить через методы (vk->video()->save => получаем данные для загрузки видео файла, после с помощью vk->request()->upload загружаем файл из первого шага на сервер.)
  3. Сервер возвращает ошибку НЕ в JSON схеме, а именно обычную надпись "File is not a video."
  4. SDK пробует обработать с помощью JSON схемы эту надпись как ошибку и отправить ее на класс VKApiError, но тот не может ее обработать из-за отсутствия обязательных параметров в виде 'error_code' и 'error_msg'.

Фактический результат: Мы получаем глобальный Exception который невозможно отловить.
Ожидаемый результат: Мы получаем Exception о том, что загруженный файл не является видеофайлом.

Лично я исправил баг добавлением 1 строчки кода, в котором идет проверка на отсутсвие массива (оригинальный код на 1 скриншоте, код исправленный мною на 2 скриншоте)
tXKk8TrHfec
KQUeGid-EGM

Class 'VK\Exceptions\Api\VKApiException' not found

yii\base\ErrorException: Class 'VK\Exceptions\Api\VKApiException' not found in E:\PHP\pikabustore\engine\vendor\vkcom\vk-php-sdk\src\VK\Exceptions\Api\VKApiParamUserIdException.php:5
Stack trace:
#0 E:\PHP\pikabustore\engine\vendor\composer\ClassLoader.php(322): ::Composer\Autoload\includeFile(''E:\\\\PHP\\\\pikab...')
#1 E:\PHP\pikabustore\engine\vendor\vkcom\vk-php-sdk\src\VK\Exceptions\Api\ExceptionMapper.php(67): Composer\Autoload\ClassLoader->loadClass(''VK\\\\Exceptions...')
#2 E:\PHP\pikabustore\engine\vendor\vkcom\vk-php-sdk\src\VK\Exceptions\Api\ExceptionMapper.php(67): ::spl_autoload_call(''VK\\\\Exceptions...')
#3 E:\PHP\pikabustore\engine\vendor\vkcom\vk-php-sdk\src\VK\Client\VKApiRequest.php(134): VK\Exceptions\Api\ExceptionMapper::parse('class VK\\Client...')
#4 E:\PHP\pikabustore\engine\vendor\vkcom\vk-php-sdk\src\VK\Client\VKApiRequest.php(90): VK\Client\VKApiRequest->parseResponse('class VK\\Transp...')
#5 E:\PHP\pikabustore\engine\vendor\vkcom\vk-php-sdk\src\VK\Actions\Users.php(53): VK\Client\VKApiRequest->post(''users.get'', ''ed2d3e12ed2d3e...', 'array ('user_id...')
#6 E:\PHP\pikabustore\engine\controllers\ListingController.php(123): VK\Actions\Users->get(''ed2d3e12ed2d3e...', 'array ('user_id...')
#7 E:\PHP\pikabustore\engine\vendor\yiisoft\yii2\base\InlineAction.php(57): app\controllers\ListingController->actionIndex(''a-tvoj-truba-s...')
#8 E:\PHP\pikabustore\engine\vendor\yiisoft\yii2\base\InlineAction.php(57): ::call_user_func_array:{E:\PHP\pikabustore\engine\vendor\yiisoft\yii2\base\InlineAction.php:57}('array (0 => cla...', 'array (0 => 'a-...')
#9 E:\PHP\pikabustore\engine\vendor\yiisoft\yii2\base\Controller.php(157): yii\base\InlineAction->runWithParams('array ('slug' =...')
#10 E:\PHP\pikabustore\engine\vendor\yiisoft\yii2\base\Module.php(528): yii\base\Controller->runAction(''index'', 'array ('slug' =...')
#11 E:\PHP\pikabustore\engine\vendor\yiisoft\yii2\web\Application.php(103): yii\base\Module->runAction(''listing/index'', 'array ('slug' =...')
#12 E:\PHP\pikabustore\engine\vendor\yiisoft\yii2\base\Application.php(386): yii\web\Application->handleRequest('class yii\\web\\R...')
#13 E:\PHP\pikabustore\index.php(9): yii\base\Application->run()
#14 {main}

Установлено через composer.
В исключении подгружает по такому пути
'E:\\PHP\\pikabustore\\engine\\vendor\\composer/../vkcom/vk-php-sdk/src/VK\\Exceptions\\Api\\VKApiParamUserIdException.php'

Я так понимаю автозагрузка не происходит из-за отсутствия класса по указанному в namespace пути

namespace VK\Exceptions\Api;

class VKApiException extends \Exception

Если скопировать класс по указанному пути неймспейса проблема ликвидируется.

"vkcom/vk-php-sdk": "^0.1.7",

Deprecation Notice

Deprecation Notice: Class VK\Actions\Enum\GroupsDocs located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsDocs.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsWall located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsWall.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\StoriesLinkText located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/StoriesLinkText.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsPhotos located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsPhotos.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsAudio located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsAudio.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsAccess located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsAccess.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsVideo located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsVideo.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsMarketCurrency located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsMarketCurrency.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsWiki located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsWiki.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsTopics located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsTopics.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsWorkInfoStatus located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsWorkInfoStatus.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsAgeLimits located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsAgeLimits.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsRole located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsRole.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class VK\Actions\Enum\GroupsSubject located in ./vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums/GroupsSubject.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v1.11+. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185

Keyboard format is invalid: keyboard should be array

Пытаюсь создать клавиатуру. Получаю сообщение об ошибке, мол массив надо передавать. Но я передаю массив. Однако сообщением ранее, видимо, происходит преобразование в строку.

#!/usr/bin/env php

<?php

require "vendor/autoload.php";
use VK\Client\VKApiClient;
use VK\OAuth\VKOAuth;
use VK\OAuth\VKOAuthDisplay;
use VK\OAuth\VKOAuthResponseType;
use VK\OAuth\Scopes\VKOAuthUserScope;

$access_token = "secretToken";

$vk = new VKApiClient();

$response = $vk->messages()->send($access_token, [
  'user_id' => 31587373,
  'random_id' => 123132,
  'message' => "Hello in code",
  'keyboard' => ['one_time' => false, 'buttons' => []]
]);

print_r($response);
PHP Notice:  Array to string conversion in ... vkapi/vendor/vkcom/vk-php-sdk/src/VK/Client/VKApiRequest.php on line 152
PHP Fatal error:  Uncaught VK\Exceptions\VKApiException: Keyboard format is invalid: keyboard should be array in ... vkapi/vendor/vkcom/vk-php-sdk/src/VK/Exceptions/Api/ExceptionMapper.php:90

Что я делаю не так? Или это баг?

VK\Exceptions\Api\VKApiAccessException Access denied: no access to call this method

Standalone-приложение. Не получается опубликовать ни картинку ни просто текст на стене группы.
$data = array( "owner_id" => "-" . strval($group), "message" => $text, "form_group" => 1, "attachments" => (!empty($attachments) ? $attachments : ""), ); return $vk->wall()->post($access_token, $data);

"тут access_token" array:4 [▼ "owner_id" => "-172101050" "message" => "Test" "form_group" => 1 "attachments" => "photo117898960_456239041," ]

Метод messages.sendMessageeEventAnswer не работает в этом SDK

Шаги воспроизведения:

  1. Написать моему Боту vk.com/site_bots_ru сообщение "/test_callback" без кавычек
  2. Бот вернёт callback кнопку "<— Назад", нажимаем на неё
  3. Начинается загрузка в течении минуты и ничего не происходит на стороне клиента

На стороне сервера :
Выдаёт ошибку : Uncaught Error: Call to undefined method VK\Actions\Messages::sendMessageEventAnswer()

Библиотеку PHP SDK уже скачивал заново, ошибка остаётся. Через приложение Postman все работает!
Версия API - 5.120

Still no wall.editAdsStealth and wall.postAdsStealth

Hi guys, first of all thank you for great job. You can be sure that we all having a good time while working on our projects with this SDK.

I've noticed that SDK doesn't contains wall.editAdsStealth and postAdsStealth methods as well. Is there any chance that they will be added in the future?

Email scope

VK API returns email along with access token if email scope specified.
As I can understand, there is no other way to get user email.

VKOAuth\getAccessToken doesnt return the email, and there is no way to get it.

Wrong ENUM namespace

Files of namespace VK\Actions\Enum are located in dir vendor/vkcom/vk-php-sdk/src/VK/Actions/Enums. Therefore PHP Compiler not found these files.

These files must have namespace VK\Actions\Enums, but not VK\Actions\Enum.

Connection timed out

Добрый день!

Столкнулся с такой проблемой, что когда пользователь дает разрешение на доступ к своему аккаунту, после этого, при попытке получить токен пользователя, происходит ошибка (прикреплен скриншот).

Вызов производится через метод getAccessToken класса VKOAuth (прикреплен скриншот).

Что нужно предпринять, что бы избавиться от ошибки? Спасибо!

https://sun9-35.userapi.com/c858132/v858132925/20ad6f/KiwVfMr0lWg.jpg
https://sun9-33.userapi.com/c858132/v858132925/20ad77/QBHbd24aq04.jpg

VKApiCaptchaException: Captcha needed

Здравствуйте!

Каким образом можно вместе Exceptions отдавать изображение капчи, для того, что бы её распознать, и продолжить выполнения скрипта согласно условиям, которые описаны тут https://vk.com/dev/captcha_error

Заранее спасибо!

One of the parameters specified was missing or invalid: invalid photo crop.

Возникает проблема при отправке запроса на загрузку файла через vk-php-sdk.

В документации формат ответа в поле crop_data, не соответствует ответу который я получаю.

array:5 [
  "server" => 204516
  "photo" => "[{"markers_restarted":true,"photo":"04914fa9e7:w","sizes":[],"latitude":0,"longitude":0,"kid":"76773f0968e622e4565c1569f69a8e4e","sizes2":[["s","6d3ccf1f62fa7764dfe4b4cae135a20f07eb7c3ae037c0c3fd4f6a92","-4517628954411015465",75,56],["m","bb6a7e5577b2f06227f05ce4d67c3e15fef361833134df31487120a6","-3219168273734240088",130,97],["x","04e0cd1d4e363ac137f7730a5dd3b1f947f9c94d647fa34c32c1baae","879059161582419064",604,453],["y","bdb21ba50d99a4355dd8c9435a9153d4280ef370ebb080708ee8634e","-3446015447328514989",807,605],["z","c083f91878ac5010007a63ff6137c3f1f6cd1778fe8cd0a4cd8cabcd","1636530027326253434",1280,960],["w","88ef2bee876cc034688e125bfa93edcae72f1f46455cc1c89671c487","-3571565795873561491",1707,1280],["o","e6afaa8eab96cc91e47729db706fcc8c54ff77beb76b912032bf8196","-7087800100686053181",130,98],["p","fa7a25f29b7324b231a495f14591af84994448c0ab96209959aa0815","-189001268309978181",200,150],["q","98ac8c68832cb859ce4f48e23f4d6b2a4752684d65893ae86bbd2e52","2620709748951465733",320,240],["r","797578611f222079ae05474c6c800aababb3d6c46d941027a4665077","5513853384305142618",510,383]],"urls":[],"urls2":["bTzPH2L6d2Tf5LTK4TWiDwfrfDrgN8DD_U9qkg/1-JPwWYoTsE.jpg","u2p-VXey8GIn8Fzk1nw-Ff7zYYMxNN8xSHEgpg/qPjcy4I3U9M.jpg","BODNHU42OsE393MKXdOx-Uf5yU1kf6NMMsG6rg/eDysZqYLMww.jpg","vbIbpQ2ZpDVd2MlDWpFT1CgO83DrsIBwjuhjTg/U5x5WzVLLdA.jpg","wIP5GHisUBAAemP_YTfD8fbNF3j-jNCkzYyrzQ/eqkKn2MfthY.jpg","iO8r7odswDRojhJb-pPtyucvH0ZFXMHIlnHEhw/bWQF5dQ_b84.jpg","5q-qjquWzJHkdynbcG_MjFT_d763a5EgMr-Blg/w0Chd1wTo50.jpg","-nol8ptzJLIxpJXxRZGvhJlESMCrliCZWaoIFQ/uxNJDFmIYP0.jpg","mKyMaIMsuFnOT0jiP01rKkdSaE1liTroa70uUg/Bb-nraGhXiQ.jpg","eXV4YR8iIHmuBUdMbIAKq6uz1sRtlBAnpGZQdw/WusXe3AkhUw.jpg"]}]"
  "hash" => "fcaa92081bb1f7840d3162dd8d1917b5"
  "crop_data" => "{"photo":"ae76f89b9cx","sizes":[],"sizes2":[["max","88ef2bee876cc034688e125bfa93edcae72f1f46455cc1c89671c487","-3571565795873561491",1707,1280],["o","b00f33290b14ed627b4f8af91c6a8b76649fe0baca08ab19a511502f","-5262697729503875943",1280,1280],["a","29ed1a7f83bf5f99b605e56ddcb09ce85dc15132c0c4ca953be1b1ee","5207115201554571762",800,800],["b","a89e9067309ca12cfa202497776258a118b7a96f0a00fca35f3de2b3","7020543332242167603",400,400],["c","11b03b01c3d1ad45749a531613f074b2f403b065d11f52df23ad5c96","2432084958403114920",300,300],["d","ce56029601588451ea86b5702cd21bcf6c4096edaf40c087251f09ea","8604732787506478826",200,200],["e","b213c93ae273c285308c166248da728b0a9442f633c019830e271aa0","8045853810572302009",150,150],["f","2030e855cb2074b72077331227683abd265811d6b5d5ec20332d7eae","-3169222953874798815",100,100],["g","4d459c7952973d4be2404d7fae913823dd204ace8231ce43a71cb515","8803986932355152554",50,50]],"urls":[],"urls2":["iO8r7odswDRojhJb-pPtyucvH0ZFXMHIlnHEhw/bWQF5dQ_b84.jpg","sA8zKQsU7WJ7T4r5HGqLdmSf4LrKCKsZpRFQLw/mayqSEwk97Y.jpg","Ke0af4O_X5m2BeVt3LCc6F3BUTLAxMqVO-Gx7g/8mEy9a9jQ0g.jpg","qJ6QZzCcoSz6ICSXd2JYoRi3qW8KAPyjXz3isw/MxeI2Pb6bWE.jpg","EbA7AcPRrUV0mlMWE_B0svQDsGXRH1LfI61clg/qDcwSWKAwCE.jpg","zlYClgFYhFHqhrVwLNIbz2xAlu2vQMCHJR8J6g/6v56YuEmanc.jpg","shPJOuJzwoUwjBZiSNpyiwqUQvYzwBmDDicaoA/uZbidWmdqG8.jpg","IDDoVcsgdLcgdzMSJ2g6vSZYEda11ewgMy1-rg/IUdHxIOoBNQ.jpg","TUWceVKXPUviQE1_rpE4I90gSs6CMc5Dpxy1FQ/qro1LngLLno.jpg"]}"
  "crop_hash" => "a86306bc6ed34bbbdcd337247a4e334e"
]

Этот ответ получаю из метода:

$photo = $this->vk
    ->getRequest()
    ->upload($url, 'photo', 'test_photo.JPG');

В дальнейшем при создании товара с идентификаторами фото полученных на предыдущих шагах я получаю такую ошибку:

VK\Exceptions\Api\VKApiParamException
One of the parameters specified was missing or invalid: invalid photo crop.

Подскажите может ли это быть связанно, с тем, что приходит не корректный ответ от метода который загружает фото на сервер ВК?

Ошибка Failed curl request. Curl error 60: SSL certificate problem: self signed certificate.

Здравствуйте! После работы с библиотекой, у меня стала появляться ошибка: Failed curl request. Curl error 60: SSL certificate problem: self signed certificate. Причем раньше ее не было. Я почитал вопросы здесь, и нашел ответ - добавить эти две строчки:

CURLOPT_SSL_VERIFYHOST => 0, // new
CURLOPT_SSL_VERIFYPEER => 0, // new

Но после добавления этих строк кода, у меня возникает другая ошибка:
Invalid http status: 404.
Подскажите пожалуйста в чем может быть причина ошибки!? Ведь вчера у меня все хорошо работало!

SSL certificate problem

Проблема с ssl сертификатом

Trace

Fatal error: Uncaught VK\Exceptions\VKClientException: VK\TransportClient\TransportRequestException: Failed curl request. Curl error 60: SSL certificate problem: self signed certificate in certificate chain. in F:\Project\vkcom\vendor\vkcom\vk-php-sdk\src\VK\TransportClient\Curl\CurlHttpClient.php:115

решить можно поправив код
vendor\vkcom\vk-php-sdk\src\VK\TransportClient\Curl\CurlHttpClient.php:40

    public function post(string $url, ?array $payload = null): TransportClientResponse {
        return $this->sendRequest($url, array(
            CURLOPT_POST       => 1,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_SSL_VERIFYHOST => 0, // new 
            CURLOPT_SSL_VERIFYPEER => 0, // new
        ));
    }

или добавить сетер на доп. параметры для curl

PHP 7.1.11 (cli) (built: Oct 25 2017 21:07:06) ( NTS MSVC14 (Visual C++ 2015) x86 )
Zend Engine v3.1.0, Xdebug v2.6.0, Curl 7.56
Windows 10

Ошибка в функции getHttpStatus()

Ошибка при получении заголовка в функции:
VK\TransportClient\Curl\CurlHttpClient->getHttpStatus(string $raw_response_header):

Запрос:

HTTP/1.1 200 OK
Date: Thu, 19 Apr 2018 21:31:58 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: 36f31b17b1bf427188a0662b182b8c3f

Ответ:

<br />
<b>Notice</b>:  Undefined offset: 1 in <b>.../vendor/vkcom/vk-php-sdk/src/VK/TransportClient/Curl/CurlHttpClient.php</b> on line <b>188</b><br />
ok

Запрос сделан через CallBack API.
image

Для справки, запускал так:
image

Баг с выводом ошибок

В ExceptionMapper.php есть список вызовов классов ошибок:

		switch ($error->getErrorCode()) {
		    case 1:
		        return new VKApiErrorUnknownException($error);
		    case 2:
		        return new VKApiErrorDisabledException($error);
		    case 3:
		        return new VKApiErrorMethodException($error);
		    case 4:
		        return new VKApiErrorSignatureException($error);
		    case 5:
		        return new VKApiErrorAuthException($error);
		    case 6:
		        return new VKApiErrorTooManyException($error);
		    case 7:
		        return new VKApiErrorPermissionException($error);
		    case 8:
		        return new VKApiErrorRequestException($error);
		    case 9:
		        return new VKApiErrorFloodException($error);
		    case 10:
		        return new VKApiErrorServerException($error);
		    case 11:
		        return new VKApiErrorEnabledInTestException($error);
		    case 14:
		        return new VKApiErrorCaptchaException($error);
		    case 15:
		        return new VKApiErrorAccessException($error);
		    case 16:
		        return new VKApiErrorAuthHttpsException($error);
		    case 17:
		        return new VKApiErrorAuthValidationException($error);
		    case 18:
		        return new VKApiErrorUserDeletedException($error);
		    case 20:
		        return new VKApiErrorMethodPermissionException($error);
		    case 21:
		        return new VKApiErrorMethodAdsException($error);
		    case 23:
		        return new VKApiErrorMethodDisabledException($error);
		    case 24:
		        return new VKApiErrorNeedConfirmationException($error);
		    case 25:
		        return new VKApiErrorNeedTokenConfirmationException($error);
		    case 27:
		        return new VKApiErrorGroupAuthException($error);
		    case 28:
		        return new VKApiErrorAppAuthException($error);
		    case 29:
		        return new VKApiErrorRateLimitException($error);
		    case 30:
		        return new VKApiErrorPrivateProfileException($error);
		    case 100:
		        return new VKApiErrorParamException($error);
		    case 101:
		        return new VKApiErrorParamApiIdException($error);
		    case 113:
		        return new VKApiErrorParamUserIdException($error);
		    case 150:
		        return new VKApiErrorParamTimestampException($error);
		    case 200:
		        return new VKApiErrorAccessAlbumException($error);
		    case 201:
		        return new VKApiErrorAccessAudioException($error);
		    case 203:
		        return new VKApiErrorAccessGroupException($error);
		    case 300:
		        return new VKApiErrorAlbumFullException($error);
		    case 500:
		        return new VKApiErrorVotesPermissionException($error);
		    case 600:
		        return new VKApiErrorAdsPermissionException($error);
		    case 603:
		        return new VKApiErrorAdsSpecificException($error);
		    default:
		        return new VKApiException($error->getErrorCode(), $error->getErrorMsg(), $error);}
	}

Теперь заглянем в папку VK\Exceptions\Api: в ней нет ни одного класса (файла) с именем, который бы начинался с VKApiError. Часть Error в названиях отсутствует, поэтому при возникновении ошибок отображается ошибка вызова класса, а не конкретная ошибка со стороны ВК. Когда я поубирал часть Error из этой switch-конструкции, всё магическим образом пришло в норму. Ну как так, ребята?

Работа через HTTP2

Добрый день. Обнаружил проблему работы вашего php-sdk через http2. При вызове любого метода (например, database.getCountries()) возникает одна и та же ошибка:
yii\base\ErrorException: Undefined offset: 1 in ../vendor/vkcom/vk-php-sdk/src/VK/TransportClient/Curl/CurlHttpClient.php:188

В этом участке происходит определение статуса запроса по полученному HTTP-заголовку.

При использовании HTTP1.1 парсится следующий заголовок: "HTTP/1.1 200 OK". Получаем статус 200.
При использовании HTTP2 парсится заголовок такого вида: "HTTP/2 200". А вот здесь статус получить не удается.

Регулярное выражение, используемое для этого, явно не так универсально:
https://regex101.com/r/hrkAr7/1

Может лучше так?
https://regex101.com/r/YRnSpT/1

Make VKOAuth PARAM constans be public

Allow public access to constants in the VK\OAuth\VKOauth class. It's useful for a target application.
For I compel to duplicate constants from the same class.

// here const
$code = $request->get(VKOAuthResponseType::CODE);

if ($code === null) {
   // but here string, instead VKOAuth::RESPONSE_KEY_ERROR_DESCRIPTION
    $errorDescription = $request->get('error_description');
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.