Automatically alert readers about news using VKontakte. Part 4

Published on January 29, 2012

Automatically alert readers about news using VKontakte. Part 4

    The habr already had several articles on 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 page layout or the order of the 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, we define our task. On the server side, we need to work with VC data, for example, automatically notify readers about news, search for video, audio, etc. Therefore, we will have to work through one user - the application administrator.

    Let's start by registering the application.
    On the page for developers, select "Connect the 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 authorization of applications 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 wrote .

    In the class, you need to register client_id: We perform


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

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

    We run the script in the browser and see the authorization page:


    Next, the application access request:


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

    write the access token inside the class:


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

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

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

    UPD Updated the class and examples.