VK API. Basics. Receiving a token. First requests to the API

Only for Lifeexample readers it is possible to open an online store on Moguta.CMS with a 15% discount

MySQL Full Text Search >>>

08.03.2013

Hello, dear readers of the LifeExample blog, many of us have our own page on the VKontakte social network, we all know that every VKontakte user has the opportunity to leave comments on the walls of other users and various communities. Today I want to show you how you can work with the data of this service through the vk api , namely how to use PHP to get all messages from any user and his friends.

The article will also tell you how to automatically send text to the group wall without using the VKontakte API.

VK-API blitz

VK provides several API implementations:

  • Streaming/Long Poll - allows you to get data in real time. Immediately, when updating data in VK, we receive up-to-date information, without refreshing the page. Streaming and Long Poll implement different approaches, but their essence is the same.
  • Widgets for the site - everything is simple here: you copied the code, without tricky settings, and you have a working widget on the site.
  • Open API - runs on the client. Just as easy to set up and use. The advantage is that it is not necessary to have a server to execute requests. Will work in regular HTML + JS.
  • Callback API - allows you to receive data from VK itself without executing a request. If the data is updated, VK itself sends us new data. For example, a user has subscribed to our group, and VK will automatically send information about this user to our script.
  • REST API - allows you to interact with VK data from a script. Allows you to automate any user actions.

For us, as programmers, at this stage the REST API . Which allows you to interact with users, groups, advertising, and other entities. You can read more about all available methods here.

To gain access to the REST API, you must have a special key vk api token . This unique value, similar to a login and password, identifies the user on whose behalf requests are made.

As Rule 2 of REST API design states, there should be no state saved between requests. The system, by definition, cannot use sessions, so the use of a token is important for identifying the user.

What is an API

From the technical side, the VKontakte website is a complex set of programs that run on the company’s servers. The result of their work is displayed in browsers or mobile applications in the form of a familiar social networking site. Users can interact with the site - publish articles, conduct searches, subscribe to communities, and so on. All these actions are provided by programs that work completely unnoticed by visitors.

There can be a lot of these programs (scripts, as programmers call them), and they must interact with each other. For this purpose, special rules and protocols have been developed, following which individual scripts are able to answer calls and receive responses from others. As a result, all the huge variety of different scripts work as a single whole.

The set of these rules constitutes a single interface for interaction with a complex software system. It is called API - Application Programming Interface.

The interaction of software modules precisely through the API library is a generally accepted norm. Without such a mechanism, it would be simply impossible to build complex software systems. After all, then each script would have its own rules for receiving external commands and producing results. The interaction of each two separate scripts would have to be programmed separately, and the entire project would be buried under a huge pile of disparate rules. There would be no way to understand them. If the project is initially based on the principle of modules operating only through the API, then the whole variety of interactions comes down to a few simple rules that are universal and suitable for any script. It is very comfortable.

How can this mechanism be useful to a simple programmer who is not on the staff of the VKontakte company and just wants to write some useful script for himself?

Illustration on the topic VK Api: interface description, examples of work, documentation

How to get a VK.COM token

Receiving a token consists of two parts: registering your application and receiving a token in this application.

You can create an application on the page. By specifying the name of the application and selecting its type. I choose Standalone because then it will be possible to get tokens with more opportunities than in other options (you'll have to take my word for it that this is true).

After creating the application and going to the settings tab, it will be shown: application id , secret key

Now, having the application id, you can get an access token. To do this, you need to create a link by substituting the id of your application into it.

https://oauth.vk.com/authorize?client_id={CLIENT_ID}&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends,notify,photos,wall,email,mail,groups,stats ,offline&response_type=token&v=5.74

where instead of {CLIENT_ID} you need to insert the id of your application. and the scope parameter lists the permissions that we want to give the token, a list of all permissions. However, here, one of the most important permissions is offline, which creates an indefinite token that does not have a limited lifetime.

If you do not want to create your own application, you can get a token using the link

By clicking on the generated link, a dialog box will open in which the rights will be read out, showing the permissions that the token is given (the more scope properties are specified, the larger this list will be)


Having confirmed, you will be redirected to a page in the address bar of which there will be access_token, expires_in equal to zero (which is logical, given that we indicated the creation of an eternal token)

I shortened the token to preserve readability. Yours will be longer

After copying this token, you can make your first requests to the API.

We create a Standalone application in VK and get an ID.

First, we need to create our Standalone application in VK. To do this, go to the application creation page. Enter the name of the application, select the platform “Standalone application” and click the “Connect application” button.

API VK - Standalone application
Next, VK will ask us to confirm the creation of the application and offer to send an SMS. After confirmation, you will be redirected to a page with information about the application, we are interested in the “Settings” tab, there we can get the “Application ID”.

We have received everything that is needed from the application; no additional settings need to be made.

How to make API requests

Let's save the received token, because it will need to be attached to each request to the VK API.

In order to make a request to the API from PHP, we need any of the available functions that can make an HTTP request: file_get_contents, curl.

By the way, even if you open the generated address in the browser, you will get the result

A request to API methods consists of the template: https://api.vk.com/method/{METHOD_NAME}?{PARAMETERS}&access_token={ACCESS_TOKEN}&v={V} where {METHODNAME} is the name of the method {PARAMETERS} is parameters, individual, depending on the method {ACCESS_TOKEN} - previously saved token {V} - API version (at the time of writing = 5.78)

Knowing all this, we will make the first request to receive all personal records from the wall. The wall entity is responsible for the wall, and its get method, which returns a list of all posts from the user’s wall. And, as a result, the name of the method will be formed as the name of the entity (wall). The name of the method (get) is wall.get

So, the first part of the URL has already been generated: https://api.vk.com/method/wall.get

Now you need to decide on the passed parameters (PARAMS). All available, required parameters with descriptions can be viewed on the method page.


I will pass owner_id which corresponds to my user id.

In fact, this field is optional in the current conditions. Since by default, ownwer_id will be set to the id of the current user.

And, you could simply add as a string to the existing URL: ...?owner_id=120159853

However, if you add many new parameters there, then adding them in this form is not convenient. Therefore, I will create an array of parameters, where the key will be the name of the parameter, and the value, respectively, will be its value. And using the http_build_query() function you can convert the array to the desired string form:

$params = [ 'owner_id' => 120159853, //params2 => 'value2', ]; http_build_query($params); //owner_id=120159853¶ms2=value2…

Now, all that remains is to put together all the parts that were discussed above. To do this, you can write the following code:

$method = 'wall.get'; $token = '38fa46d4c0c10bab105c760cc44ed373c0bc6a34405931f34c765ea'; $version = 5.78; $params = http_build_query([ 'owner_id' => 120159853, 'access_token' => $token, 'v' => $version //… ]); $url = "https://api.vk.com/method/{$method}?{$params}&access_token={$token}&v={$version}"; //https://api.vk.com/method/wall.get?owner_id=120159853&access_token=38fa46d4c0c10bab105c760cc44ed373c0bc6a34405931f34c765ea&v=5.78

Despite the fact that even the token and version can now be placed in the $params array, for a more centralized recording.

The last step remains - executing the http request. And, taking into account the fact that the data is returned in the form of JSON, then the result must be additionally wrapped in the json_decode function, which will convert the JSON to a regular PHP array. That's how easy it is to decode JSON.

$result = json_decode(file_get_contents($url), true);

As a result, we get a regular array of records that we can process as we wish

And, based on the answer above, to get the records we’ll do:

//all entries $orders = $result['response']['items']; //first entry $order = $result['response']['items'][0];

Where to find documentation for VK Api

The social network in its documentation offers a detailed description of its API for third-party developers. The main page of this documentation is located here: https://vk.com/dev/manuals. It describes software objects and their methods, a list of returned codes and errors, access rights, request templates, and so on.

A programmer who wants to develop any application (connected within VK or running on a separate website) can provide calls to VK methods in the code of his program, using these same API interaction rules. This will make it possible to access the functionality of the VKontakte social network. For example, you can get a list of subscribers of a particular community, send mass messages, publish new entries, and so on. The possibilities here are very wide. Many useful applications are based on the capabilities of the VK API. For example, music players for playing music from friends’ pages, various games, “My Guests” counters, alternative mobile clients such as VK Settings, VK Coffee, Kate Mobile and so on.

Numerous articles on the Internet are devoted to full-fledged work with the VKontakte API; this information is very extensive. Here we will show the solution to only two specific problems.

Rating
( 2 ratings, average 4 out of 5 )
Did you like the article? Share with friends: