How to work with the VKontakte API. Connecting and working with vk api


  • Translation
  • Tutorial

The Beacon API is a JavaScript-based interface for:

sending a small amount of data to the server from the browser, without waiting for a response. In this article, we'll look at when the Beacon API is useful, how it differs from using XMLHTTPRequest (Ajax) for the same purposes, and how to use it.

Why do we need another API?

Beacon API is used to send small data to the server without waiting for an answer. The last part of the statement is the most interesting. The Beacon API is designed specifically so that you can send data and forget about it. There is no need to wait for an answer, as there will not be one.


Metaphor with postcards, these are cards that people send/sent to each other. As a rule, they wrote a small text on them (“Where are you? And I’m at the seaside lol.”, “The weather here is great, not like in your office”), threw it in the mail and forgot. No one expected an answer like “I’ve already left for you,” “It’s wonderful in my office.”


There are many cases where a "send and forget" approach would be appropriate.

Statistics Tracking and Analytical Information

This is the first thing that comes to mind. Such big solutions How Google Analytics can provide good review for basic things. But what if we want something more customized? We need to write some code to track what's happening on the page (how users interact with components, how far they scroll, which pages were displayed before the first sale), then send this data to the server when the user leaves the page. Beacon is ideal for this task since we simply send data and don't need a response from the server.

Debugging and Logging

Another application is logging information from JavaScript code. Imagine a situation when you have great app with rich UI/UX. All tests are green, but in production an error periodically pops up that you know about, but cannot debug it due to lack of information. IN in this case you can use Beacon for diagnostics.


In fact, any problem with logging can be solved using Beacon. This could be creating save points in games, collecting information about the use of new functionality, recording test results, and so on. If it's something that happens in the browser and you want the server to know about it, Beacon is what you need.

Haven't we done this before?

I know what you're thinking. None of this is new? We have been communicating with the north via XMLHTTPRequest for over 10 years. We recently started using the Fetch API, which essentially does the same thing, just with a new Promise interface. So why do we need another Beacon API?


The key feature is that we don't need a response from the server. The browser can queue the request and send the data without blocking the execution of any code. Since the browser is involved in this, it doesn’t matter to us whether the code is still running or not, the browser will simply quietly send requests to itself in the background.


With Beacon API there is no need to wait for the best moment for the CPU or network. Simply adding a request to the queue using a beacon costs almost nothing.


To understand why this is important, just look at how and where such logic is typically used. For example, in order to measure how long the user is on the page, we need to send a request to the server as close to the end of the session as possible.


This is usually done on unload or beforeunload . Such code can block execution and if there is a delay in unloading a page, then the loading of the next page is also delayed. This results in a less than stellar UX.


Do you understand how slow HTTP requests are? And the last thing you want is to cram an HTTP request between transitions.

Trying the Beacon API

The basic usage example is very simple:


let result = navigator.sendBeacon(url, data);

Using navigator.sendBeacon()

navigator.sendBeacon takes two parameters. The first is the URL to which the request will be sent, the second is the data that needs to be sent. The request is in the form of an HTTP POST.


data - this parameter can accept several data formats, all of which the Fetch API works with. This could be Blob, BufferSource, FormData or URLSearchParams, etc.


I like to use FormData for simple key-value data, it's not complicated and easy to use.


// URL where to send data let url = "/api/my-endpoint"; // Create a new FormData let data = new FormData(); data.append("hello", "world"); let result = navigator.sendBeacon(url, data); if (result) ( console.log("Added to queue!"); ) else ( console.log("Error."); )

Browser support

The support for this API is quite solid. The only browser that doesn't support this is Internet Explorer(I didn’t expect this) and Opera Mini. But everything works in Edge. In most cases there is support, but it’s better to check just in case:


if (navigator.sendBeacon) ( // Beacon code ) else ( // Use XHR? )

Example: logging the time spent on the page

In order to see this whole thing in practice, let's create simple system counting the time the user is on the page. When the page loads we look at the time and when it leaves we send a request from the start time of viewing and the current one to the server.


Since we're only interested in the time spent on the page, and not the actual time, we can use performance.now() to get the base timestamp when the page loads:


let startTime = performance.now();

Let's wrap a small piece of logic into an easy-to-use function:


let logVisit = function() ( // Test that we have support if (!navigator.sendBeacon) return true; // URL to send the data to, e.g. let url = "/api/log-visit"; // Data to send let data = new FormData(); data.append("start", startTime); data.append("end", performance.now()); data.append("url", document.URL); // Let's go! navigator.sendBeacon(url, data); );

And finally, we need to call this function when the user leaves the page. My first thought was to use unload , but Safari on Mac seems to block the request for security reasons. Therefore, it is better to use beforeunload:


window.addEventListener("beforeunload", logVisit);

When the page loads (or before), our logVisit() function will be called and, if the browser supports the Beacon API, will send a request to the server.

A couple of points

Since most of the problems that the Beacon API will be used to solve revolve around activity tracking, it will be important to note the social and legal side of the whole kitchen.

GDPR

Just remember him.

DNT: DO NOT TRACK

In addition, browsers have an option that allows users to indicate that they do not want their activity to be tracked. Do Not Track sends an HTTP header that looks like this:


DNT: 1

If you are tracking data that may indicate a user and there is DNT: 1 in the request headers, then it is better to listen to the user and not save any data. For example, using PHP, you can check this as follows:


if (!empty($_SERVER["HTTP_DNT"])) ( // I don’t want, I don’t need )

Finally

Beacon API is really very convenient way to send data to the server, especially in the context of logging. Browser support is quite good and allows you to easily log any information without any negative consequences for the performance and responsiveness of your UI. The non-blocking nature of these requests plays a very good role in this, it is much faster than the alternatives XHR and Fetch.


Tags: Add tags

Hello, Habr!

At one time, surfing the Internet for rational API usage VKontakte, I could not find anything intelligible, the only libraries that I found were implemented without using any generally accepted practices and without beautiful code. I decided to correct the misunderstanding and wrote my own library for working with the VKontakte API.
Vital details and approaches under the summary.

It just so happens that the VK API is implemented quite well, with the exception of some illogical points, which I will mention later. But today we are not talking about quality, but about specific application.

It is immediately necessary to make a reservation; in addition to the description, I will provide pieces of working code for my library, a link to which I will provide at the end of the article. The library runs on the latest stable version 5.5, if you cut out the generators from the batch receipt, it should work on 5.4.

  • Server authorization (so-called site authorization)
  • Client authorization(Standalone)
  • Application server authorization
The most interesting for the developer are the first two. The first one allows you to authorize a user on the site and get his access key, the second one allows you to authorize your application, for example Dekstop or Mobile. Looking ahead, the second option gives us huge opportunities, and the first, only a small part of them.

The obtaining algorithm in the first case boils down to performing the following points:

  • We display a link for user authorization, which we format in accordance with the documentation
  • The user follows it and logs in
  • The user is redirected to our application's REDIRECT_URI from GET parameter code
  • Our application must make a request to the API containing code to obtain the user's access key
  • The API responds with either an object containing the access key or an error.

An example of code with which you can accomplish this tricky task.

$auth = getjump\Vk\Auth::getInstance(); $auth->setAppId("3470411")->setScope("SCOPE")->setSecret("SECRET CODE")->setRedirectUri("http://localhost/test.php"); $token=$auth->startCallback(); printf("LINK", $auth->getUrl());

It is assumed that our domain is localhost and the current file is test.php. If everything went well, then our $token variable will contain the access key of the user who has been authorized.

From the moment we have the access key, we can perform API requests. The general request logic is simple, you pass a specially crafted request to the API URL. The request must contain the method name and arguments.

api.vk.com/method/METHOD_NAME?PARAMETERS&access_token=ACCESS_TOKEN

List of methods, this is one of the rich things of the API. In it you can find methods that do not require an access key for their work, therefore you can call them without receiving it.

When using the library we need to create base object, for example like this:
$vk = getjump\Vk\Core::getInstance()->apiVersion("5.5")->setToken($token);

A couple of example queries using the library:

Exactly 100 objects will pass through the anonymous function in each, containing data about users from 1 to 100. Note that if we remove the function call, no request will occur, all because an object will be returned that has the magic methods __call and __get overridden, which allows us to make a request when we really need it.
$vk->request("users.get", ["user_ids" => range(1, 100)])->each(function($i, $v) ( if($v->last_name == "" ) return; print $v->last_name . "
"; });

One of the things that the use of generators opens up for us is batch receiving. That is, we receive data only when we need it. The following example will allow us to receive ALL our messages, in requests of 100. Be careful, method requires you to have rights for messages, Standalone applications, the same authorization and, accordingly, transfer of the access key.
foreach($vk->request("messages.get")->batch(100) as $data) ( $data->each(function($i, $m) ( if(isset($m->body) ) print $m->body .PHP_EOL; )); )

Good method, which can be found in the API - execute. It takes a code parameter as an argument, code is some pseudo JavaScript that allows us to execute our code on the server side, and it also allows us to execute stored procedures that we can create when editing our application.

I couldn’t ignore this thing and implemented it in the library. In a nutshell, it allows you to execute multiple queries as one. Look next example code.

$js1 = $vk->request("messages.get", ["count" => 200, "offset" =>0 * 200])->toJs(); // Returns an object of type VkJs $js2 = $vk->request("messages.get", ["count" => 200, "offset" =>1 * 200])->toJs(); $js3 = $vk->request("messages.get", ["count" => 200, "offset" =>2 * 200])->toJs(); $js4 = $vk->request("messages.get", ["count" => 200, "offset" =>3 * 200])->toJs(); $js1 ->append($js2) // We append js2 to js1 ->append($js3) ->append($js4) ->execute() // We want to execute this (actually this will return a RequestTransaction) - >response //The request will be executed only now ->each(function($i, $v) //The first anonymous function is needed to traverse all elements of the array received from execute(array of 4 elements, 4 requests) ( $v->each( function($c, $d) ( // Next to go through all 200 messages in each array if(isset($d->body)) print $d->body; // Print a message if such a field is present )); ) );

As promised, one of those misunderstandings that you may encounter in current version API(5.21), method

I am often asked how to work with API. The most popular problem related to API, is - working with the VKontakte API. In this article I will show how to work with the VKontakte API, and, most importantly, I will show you that all APIs work according to the same principle.

Here procedure which you need to do in order to start working with any API:

  1. Find documentation as needed API.
  2. Look API connection examples. There may be different variants. For example, on one service they will require The secret key, issued after registration. On the second service, all requests do not require secret keys. On the third service, there are options for working with a secret key and without. Sometimes, the secret key is called token.
  3. Copy simple ready code from the documentation site and check its operation. If it doesn’t work, then look for the error yourself, since the service is unlikely to have one.
  4. Find in the documentation method, which solves your problem.
  5. Using examples and description of the method, send the correct request to the API.
  6. Depending on the format of the response, parse it into " components", and then do what is required - display it to the user, save it to a file, send it to the database, and the like.

And as an example of following these instructions, we will look at VKontakte API. So:

  1. Link to documentation.
  2. In this case, there are methods that are public and therefore do not require a token, and there are methods that require one.
  3. In this case, I did not find any examples in a specific language. Perhaps they are there, but clearly not in plain sight. Usually, at API There are examples for each method in different languages.
  4. We want to withdraw 5 latest posts from the wall specific user, and then display them on your website. The method we need.

Now we have to send a request to the API using the method description. We will do this through PHP:

$wall = file_get_contents("https://api.vk.com/method/wall.get?v=5.3&filter=others&domain=myrusakov&count=5");
print_r($wall);
?>

In this case, I use API 5.3 (v=5.3), I display all entries regardless of the author ( filter=others) from your page ( domain=myrusakov) in quantity 5 things ( count=5). I think everything is very transparent here.

We received a response in the format JSON, and now we need to move on to the last point - parsing the answer to " components". Next, we will display the posts from the wall in a more or less readable form on the page of our website. The resulting PHP code:

$wall = file_get_contents("http://api.vk.com/method/wall.get?v=5.3&filter=others&domain=myrusakov&count=5"); // Send the request
$wall = json_decode($wall); // Convert the JSON string to an array
$wall = $wall->response->items; // Get an array of comments
for ($i = 0; $i< count($wall); $i++) {
echo "

".($i + 1).". ".$wall[$i]->text."
".date("Y-m-d H:i:s", $wall[$i]->date)."

"; // Display records
}
?>

As you can see, everything is very simple. The hardest part is breaking it down into its component elements. I prefer to output the result from API through print_r, and only then write processing of this. Although you can look at an example response in the method description, and then write a parser.

Those who decide to develop applications for VKontakte will sooner or later have to deal with such a concept as API (application programming interface), which literally means application programming interface.


More simply - API it's a whole complex of different ready-made functions, ready-made classes, constants, etc., which can be used in third-party . The VKontakte API is constantly being improved and today it is already a fully functional set of add-ons that allows.

You can read the documentation in detail here.
The last global transformation of this development environment was carried out back in April 2009. Of course, even after that the site was constantly modified. Let's note the main API capabilities In contact with

  1. The API allowed applications to access friends, their photos, and videos. Applications can now create albums yourself and place information in them. This didn't happen before. What is important is that when installing such an application, the user decides whether to give him access to personal data or not.
  2. Sending notifications by applications. Yes, it's annoying sometimes pop-up notification in the lower left part of the screen is also implemented using the API.
  3. Inviting friends to apps has also become easier thanks to application programming interface, on which it was implemented this function mass invitation. Subsequently, these invitations began to be used for advertising.
  4. Advertising from VK has disappeared from application pages. Now the developer of a game or program for VK decides for himself whether he needs advertising in his flash drive. If yes, he has the right to place his own and receive from it 100% profit.
  5. As VK developers called it, users integrating applications gained access to the internal economy of the network. Simply put, it has become accessible API allowing use VKontakte as internal payments.
  6. Opportunity launch applications in full screen mode . Increase maximum size frame made it possible to place additional banners with advertising, so today developing applications for VK is not just pleasure, but a rather profitable activity when deciding to engage in advertising and selling banners from it.
  7. Third-party applications are spreading now and via news feed. This is another step to popularize them. In addition (even though it was a long time ago, a miniature icon became available to the application).
  8. Application output order also implemented using API. Today, by default, those games that are launched most often are in your first positions. The ones you haven’t used for a long time can be found at the end of the list.
  9. Thanks to the API, it became available and detailed built-in statistics. Today you can easily count visitors, page views, gender, age, location of the application user. All information is presented in the most visual way possible, in the form of flash graphs, which are built instantly. This was done primarily for advertising (selling advertising space). You get statistics, you see that the application is used by tens of thousands of people. You show this to the advertiser, who will probably want to pay for the banner in such an application.
  10. For the most popular applications became possible registration of short subdomains(for example chat.vk.com and similar) for simple memorization and quick access.
  11. Well, finally, the opportunity has arisen displaying information on users’ personal pages.

First, let's define what the VK API is and what capabilities it provides us. VKontakte API - allows a developer to interact directly with the VKontakte database using special http requests. How can this be useful to us as developers? Using the API, we can retrieve the most various information about users, groups, wall posts, photos and much more. Of course, the service has certain limitations; more about this below the cut.

I warn you right away, the article is not for beginners and I will not explain some points, as the article will turn out to be very long. With these articles I just want to show the principle of working with the VK API and code examples. And of course the code will be available on github.

basic information

The first thing we need to create our application is to go to https://vk.com/dev. Next we go to "My Applications" and press the button "Create an application". VKontakte allows you to register 3 types of applications, short description each:

  • Standalone application- it is for mobile clients, desktop programs and sites on which interaction with the API will be carried out from Javascript.
  • Web site- if you want to write a script for a website that will use the API, indicate this option.
  • IFrame/Flash application- games on VKontakte, etc.

We write the name of the application, select the type “Website”, in the site address and base domain we indicate the actual address of your site and domain. If you are developing locally, you can specify http://localhost.

Creating an application

Our application has been created, now in the editing section, go to “Settings”. This page will contain the data we need, namely id, protected key And service key. All this is needed for user authorization. The algorithm for interacting with the API is very simple:

  1. User authorizes account VK in the application.
  2. Receives a special token.
  3. Makes requests to the API.

Now we need to actually write the code that will allow us to interact with the API. We will write in PHP with the inclusion of some libraries. We will need composer, if you don’t have it installed, you can download it by following this link.

In the project folder, create a composer.json file and write the following into it:

( "require": ( "slim/slim": "^3.0", "twbs/bootstrap": "4.0.0-alpha.6", "illuminate/database": "^5.4", "slim/twig-view ": "^2.2", "guzzlehttp/guzzle": "~6.0" ) )

We save the file, open the console and go to the folder with our project, which contains the file we created. Run the composer install command.
With this command we installed the mini framework Slim, Bootstrap for fast layout, a package for working with a database and a template engine.

Application structure

The structure is very simple and includes several files and folders.

  • app— for application settings, we will keep routes, classes and other settings files in this folder.
  • public— the main folder containing the file index.php and style files
  • resources- folder for views

Creating files

public/index.php

run();

In this file we only launch our application; all settings will be made in other files. This is our entry point.

app/app.php

include "../vendor/autoload.php"; // Debug $config = [ "settings" => [ "displayErrorDetails" => true, "LogLevel" => "debug", "vk" => [ "client_id" => "ID OF YOUR APPLICATION", "client_secret" = > "THE SECRET KEY OF YOUR APPLICATION", "redirect_uri" => "http://vk-tutor.com/authorize", "display" => "popup", "scope" => "friends,wall,offline", " response_type" => "code" ] ], ]; $app = new Slim\App($config); // DI for twig view $container = $app->getContainer(); $container["view"] = function ($container) ( $view = new \Slim\Views\Twig("../resources/views", [ "cache" => false ]); $basePath = rtrim(str_ireplace ("index.php", "", $container["request"]->getUri()->getBasePath()), "/"); $view->addExtension(new Slim\Views\TwigExtension($container[ "router"], $basePath)); return $view; ); include "classes/VK.php"; // Routes require "routes.php";

Don't be alarmed, there is nothing complicated. We simply connect the loader, inject the dependency for using Twig and include the file with routes.

app/routes.php

get("/", function ($request, $response) ( $vk = new VK($this->get("settings")["vk"]); if (isset($_SESSION["vk"]) ) ( if (!isset($_SESSION["account"])) ( // Set the token $vk->accessToken = $_SESSION["vk"]->access_token; // Get information about the current user // Record all information to session $_SESSION["account"] = $vk->getAccountInfo($_SESSION["vk"]->user_id); ) return $this->view->render($response,"index.html", [" vk" => $vk, "account" => $_SESSION["account"]->response]); ) return $this->view->render($response,"index.html", ["vk" = > $vk]); )); $app->get("/authorize", function ($request, $response) ( // Check if there is code in the address bar if ($request->getQueryParam("code") != NULL) ( $vk = new VK($this->get("settings")["vk"]); // Get the token $_SESSION["vk"] = $vk->getAccessToken($request->getQueryParam("code")); ) return $response->withStatus(302)->withHeader("Location", "../"); ));

Now our application is completely ready for use. To render the page, you need to place the template in the resources/views directory. We can start writing the code itself, which will allow us to interact with the VKontakte API. Since we will need to make HTTP requests to the API, I installed Guzzle. This is an HTTP client that will allow us to very easily perform HTTP requests to vkontakte.

Class for working with VK API

client_id = $params["client_id"]; $this->client_secret = $params["client_secret"]; $this->redirect_uri = $params["redirect_uri"]; $this->display = $params["display"]; $this->scope = $params["scope"]; $this->response_type = $params["response_type"]; ) public function getLoginLink() ( $params = [ "client_id" => $this->client_id, "redirect_uri" => $this->redirect_uri, "scope" => $this->scope, "response_type" => $ this->response_type ]; return $this->loginUrl . http_build_query($params); ) public function getAccessToken($code) ( $client = new \GuzzleHttp\Client(); $response = $client->request("POST ", $this->queryUrl, [ "form_params" => [ "client_id" => $this->client_id, "client_secret" => $this->client_secret, "redirect_uri" => $this->redirect_uri, "code " => $code, ], "verify" => false, ]); $data = json_decode($response->getBody()); return $data; ) public function getAccountInfo($id) ( $url = "https ://api.vk.com/method/users.get"; $client = new \GuzzleHttp\Client(); $response = $client->request("POST", $url, [ "form_params" => [ "user_ids" => $id, "fields" => "photo_50,counters", "name_case" => "Nom", "access_token" => $this->accessToken ], "verify" => false ]); $ data = json_decode($response->getBody()); return $data; ) )

I wrote a small class that so far only knows how to authorize a user.
The getLoginLink() method generates a login link, the getAccessToken() method requests an access token, and the last getAccountInfo() method loads information about the authorized user.

This completes the application logic and when the user logs in, we will receive an array with user data in the session and can display it.
Since I connected Twig template engine, my templates are written in html files, but you can use regular php files or another template engine.

File code for displaying information.

(% extends "layout/app.html" %) (% block content %)

(% if account %)

Account


(% for acc in account %)
(( acc.first_name )) (( acc.last_name ))
Friends: (( acc.counters.friends ))
Followers: (( acc.counters.followers ))
(% endfor %) (% else %)

Authorize user


Authorization (% endif %)
(%endblock%)

Framework slim it is very well suited for creating small applications and APIs for your projects, which is why I used it in this article and will continue to use it further. In the next article, we'll see how you can get posts from the wall in a group and process them.







2024 gtavrl.ru.