📜 ⬆️ ⬇️

Automatic notification of readers about the news using VKontakte. Part 4

On Habré, there have already been several articles about working with VKontakte ( one , two , three ), but it was done through simple requests for pages with its subsequent parsing. This is terribly wrong, because if the layout of the page or the order of requests changes, the script will stop working. In addition, if I am not mistaken, this is prohibited by the rules of the site.
For this there is an official API from VKontakte.


First, let's define our task. On the server side, we need to work with VK data, for example, automatically notify readers of news, search for video, audio, etc. Therefore, we will work through one user - the application administrator.

Start by registering the application.
On the page for developers, select "Connect site" .
')
Type of application - Standalone. With it, we will have more methods available that are not available if you just connect a website.


Next we see the application management page:


You can read more about application authorization in the documentation .

After registering for work, we need to get access token.
For this, and the rest of the work with the API, we will use the class I have written .

In the class you need to register client_id:


Perform the authorization method:
VkApi::auth(array('offline', 'wall')); 

In the auth () method, you can specify an array of application rights. The entire list can be found in the documentation .
I want to note that the resulting access token we will register in the body of the class. And since the normal session does not live long, we will have to constantly update the token. There is a way out - add offline rights to the list of required rights. Then we will get a long-lived session, which will fail only if the current user's password is changed.

Run the script in the browser and see the authorization page:


Next, the application access request:


After permission to exit, we are given all the necessary parameters:
access_token = % access_token% & expires_in = 0 & user_id =% userid%

Register access token inside the class:


Everything! Done, now we can use API methods.
The documentation has a list and description of the methods.

For example, send a message to the wall. If you are sending to a page or group, add a minus before page number to owner_id. To write on behalf of the page indicated from_group.
 VkApi::invoke('wall.post', array( 'owner_id' => '%id%', 'message' => '%message%', 'from_group' => 1 )); 

It remains to build a script to get the necessary news, send them using the method written above, and hang the script in cron. But it depends on your application and goals.

UPD Updated class and examples.

Source: https://habr.com/ru/post/137240/


All Articles