Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Vk Laravel Package

getjump/vk

getjump/vk is a lightweight PHP client for the VKontakte API. It offers a simple, Composer-ready interface for making API requests and handling responses, making it easy to integrate VK authentication and social features into PHP applications.

View on GitHub
Deep Wiki
Context7

Getting Started

1. Install and sanity-check compatibility first.

composer require getjump/vk

Before writing anything, read composer.json in vendor/getjump/vk. The package was last released in October 2016 and is explicitly marked abandoned upstream. It targets PHP 5.4+ and talks to VK through raw cURL, so on PHP 8.1/8.2+ expect deprecation notices (dynamic properties, implicit nullable params) and possibly fatals in edge code paths. If you're on Laravel 10/11 you'll likely need to fork it into packages/ or vendor a patched copy rather than depend on Packagist.

2. Register a singleton wrapper, not the static.

Getjump\Vk\Core is a getInstance() singleton with mutable global state (token, app id, secret, API version). Never call Core::getInstance() from controllers or jobs. Bind it once in a service provider and expose a thin VkClient service:

// app/Providers/VkServiceProvider.php
$this->app->singleton(VkClient::class, function () {
    $core = Core::getInstance();
    $core->setAppId(config('services.vk.app_id'))
         ->setSecret(config('services.vk.app_secret'))
         ->setApiVersion(config('services.vk.api_version', '5.131'));

    return new VkClient($core);
});

3. Where to look first.

  • Getjump\Vk\Core — entry point, ->api('method.name'), token/version config.
  • Getjump\Vk\Api — the fluent request builder (param(), request(), batching).
  • Getjump\Vk\Auth — OAuth URL generation and code→token exchange.
  • Getjump\Vk\Response — the wrapper you actually read results from.
  • README.md in the repo — it's short and is the only real documentation; there is no docs site.

4. First use case: a service-token call.

Service tokens (from your VK app settings) are the fastest way to prove the plumbing works — no user login, no redirect URI:

$client = app(VkClient::class);

$response = $client->core()
    ->api('groups.getById')
    ->param('group_id', 'my_community')
    ->param('fields', 'members_count,description')
    ->request();

dump($response->response); // inspect shape once — it varies by method

If that returns data, the cURL transport, token, and API version are all correct. Only then wire up user OAuth.

Implementation Patterns

OAuth flow. Auth handles the redirect/callback dance:

// routes/web.php
Route::get('vk/redirect', fn () => redirect(
    Auth::getInstance()
        ->setAppId(config('services.vk.app_id'))
        ->setSecret(config('services.vk.app_secret'))
        ->setRedirectUri(route('vk.callback'))
        ->getUrl()
));

Route::get('vk/callback', function (Request $request) {
    $token = Auth::getInstance()
        ->setAppId(config('services.vk.app_id'))
        ->setSecret(config('services.vk.app_secret'))
        ->setRedirectUri(route('vk.callback'))
        ->getToken();          // reads the `code` query param

    // Persist per-user: token, expires_in, user_id
    auth()->user()->update(['vk_token' => $token]);
});

Store the token per user, not globally. Then set it on the client for that request/job:

$client->core()->setToken($user->vk_token);

Fluent builder + execute batching. For fan-out reads (profiles, group info, wall counts), build a batch instead of N serial HTTP calls — VK's execute method allows up to 25 sub-calls in one round trip, which is the single biggest performance lever you have:

$api = $client->core()->api('users.get');
$api->param('user_ids', implode(',', $ids))
    ->param('fields', 'photo_100,city,country');
$response = $api->request();

Check Api for the batch/execute helper before writing your own loop; it's the difference between 1 request and 25.

Pagination as a generator. Most list methods take offset/count (max 200 typically). Wrap it:

public function each(string $method, array $params, int $perPage = 200): \Generator
{
    $offset = 0;
    do {
        $page = $this->core->api($method)
            ->params($params + ['offset' => $offset, 'count' => $perPage])
            ->request()
            ->response;

        foreach ($page as $item) {
            yield $item;
        }
        $offset += $perPage;
        usleep(340_000); // stay under 3 req/s
    } while (count($page) === $perPage);
}

Chunk ID lists. users.get accepts ~1000 ids, groups.getById ~500. Chunk in the caller and merge — otherwise you silently get a too many ids error.

Uploads are three-step. Photo/audio/video uploads are not a single API call: get an upload server (photos.getWallUploadServer), POST the file (use Laravel's Http::attach() — the package does not wrap file upload), then photos.save. Do this in a queued job; it's slow and failure-prone.

Queue everything that writes. Wrap wall.post, messages.send, groups.edit in jobs with RateLimited middleware. Combined with VK's error code 6, this is where most production incidents come from.

Cache reads aggressively. users.get, groups.getById, stats.get change slowly. Cache::remember("vk:user:{$id}", 3600, ...) cuts your call volume by an order of magnitude and keeps you far from the rate limit.

Mock the boundary, not the package. Because Core is a static singleton, testing through it is painful. Define a VkClient interface with call(string $method, array $params): array, implement it with the package, and bind a fake in tests. This also gives you a one-file migration path off the package later.

Gotchas and Tips

It's abandoned — treat it as a frozen dependency. No fixes for new VK API versions, no PHP 8 support, no security patches. Pin the commit hash if you fork it, and add a composer.json conflict/note so nobody silently upgrades. VK's auth surface moved to VK ID (OAuth 2.1) in 2023–24; this library predates all of it. Long-term the migration target is vkcom/vk-php-sdk or a ~200-line client on top of Laravel's Http facade.

Pin the API version explicitly. Newer VK methods and fields are gated behind v=. If you don't set setApiVersion(), you get ancient default behavior and confusingly missing fields. Also keep in mind that methods added after ~2016 (stories, clips, newer market endpoints, VK ID) simply aren't modelled by this package — you'll be calling raw method names through it, and newer response shapes may not fit Response.

The static singleton leaks across jobs. In a queue worker, Core::getInstance() persists between jobs. If job A sets user A's token and job B forgets to set one, B runs as A. Always setToken() at the start of every unit of work, or better, resolve a fresh wrapper per job.

Response shapes are inconsistent. $response->response is an array for list methods and a single object/array for single-entity methods (users.get with one id returns an array; groups.getById may not). Always dump() once per method and code defensively. ->first() exists on some paths but don't assume it everywhere.

Errors don't always throw. VK returns {"error": {"error_code": ..., "error_msg": ...}}. Check for an error key/exception explicitly after every call, and log error_code distinctly:

  • 5 — invalid token / expired
  • 6 — too many requests per second (back off, retry)
  • 9 — flood control (long backoff, minutes)
  • 14 — captcha required (needs user interaction; cannot solve server-side)
  • 15 — access denied (scope/privacy)
  • 100 — invalid parameter (usually a bad v or bad id format)

Token lifetimes and scopes. Implicit-flow user tokens are short-lived (24h classically); there is no refresh token. Build a re-auth path, don't assume a stored token is valid forever. Service tokens never expire but only access app-owned/community data — they can't read arbitrary users' private data. Community (group) tokens are what you need for wall.post as a group.

HTTPS and redirect URI. VK requires the redirect URI to match exactly and to be HTTPS. http://localhost dev flows are a common source of redirect_uri mismatch errors — use a tunnel or a staging domain registered in the app.

Tokens end up in query strings. The library sends access_token as a GET parameter. That means it lands in cURL debug logs, Laravel's HTTP client log, and any proxy. Never log the raw request URL; redact access_token.

cURL is used directly. No PSR-18, no Http::fake(), no timeout config exposed by default. In containers behind a proxy you may need to set CURLOPT_* yourself; and you can't intercept calls in tests. Another reason to keep the wrapper interface.

Rate limits. Roughly 3 req/s for user tokens, 20 req/s for service tokens. Enforce it yourself with a Redis-based limiter in the service — VK will happily return error 6 and repeated violations escalate to longer blocks.

Extension points. Core allows overriding the endpoint — point it at a local stub server for integration tests. You can also subclass Api to add your own param() helpers, and subclass Core if you need a non-singleton. Both are cheap ways to make the package tolerable without forking every file.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums