VKontakte comment widget for your site and storing the number of comments on the server

Moving in step with the times, I decided to post a VKontakte comment widget on my website. A little patience, google and documentation is enough to achieve the result. Posting the widget itself is not difficult, VKontakte provides a simple interface generating code for the site. I wanted to display the number of comments in some places. Here difficulties arose, as usually happens, the devil is in the details. I will try to sort through what the documentation is silent about.

1.Registration of the VKontakte website

To place the widget itself, first the site should be registered as a Vkontakte application >> here . Fill out the form, receive SMS, fill out the form again, as a result of registering the application, we should get two keys :

api_id - identifier of our website as a

VK application api_secret - secret key that only the application owner knows. It encrypts data that could otherwise be replaced / corrupted / distorted by an attacker in order to generate an electronic signature for this data on the VKontakte side, we need it in order to check it for validity. And yes, we will also need it in the future.

PS: Vkontakte provides a simplified method of registering the application for the Comments widget, but in this case it is impossible to get the api_secret key (at least for an hour I was looking for a way to get it and ... I didn’t find it), which is necessary if you store the number of comments. Therefore, do not be lazy and create an application.

2. Create a widget

We create the widget itself, I have no desire to duplicate the documentation for the widget, I will say that in the end something like this should turn out:
    VK.init({apiId: %ВАШ_api_id%, onlyWidgets: true});
    VK.Widgets.Comments("vk_comments", {limit: 10, width: "1000", attach: "*", onChange: addCommentCallback},   "post_");

what is onChange, read on; The third parameter is the ID of this comment widget (block), if you do not specify it as an id, the md5 hash from location.href (links to this page) is used. This did not suit me, since several different links pointed to one element. At this stage, the widget is already working, now you need to figure out the display of the number of comments.

3. Transfer of data on the number of comments to the server

Obviously, the most successful option is to store the number of comments in the database, even if we do not store the comments themselves, since getting the number of comments via the VKontakte API will slow down the site too much. I store the number of comments in a separate column of the data table. The only question is how to keep the value in the database in an updated state and to avoid desync.
The comment widget API has an onChange parameter . The function that the onChange parameter contains is called every time a comment is deleted / created. The onChange callback function is called with four parameters

num - the number of comments
last_comment - the last comment
date- date
sign - key

This is what we need. Now we write the addCommentCallback function itself, it will make an ajax request, passing all 4 parameters above, as well as the id of the record to the server. Here's what I got (using jquery):

function addCommentCallback(num, last_comment, date, sign){
         type: 'vkontakte',
         num: num,
         last_comment: last_comment,
         date: date,
         sign: sign,
         id: "post['id']?>"

I doubt that you want to turn your site into a fence on which you can write anything you like, and one day instead of the number of comments, find a three-letter word or an unflattering opinion about you and your site. Therefore, before we save the number of comments, we check that the data that came from the user is reliable.

4. Data validation

Now we need the api_secret key, which we received when registering the application. I repeat, personally, I did not find a way to get this code if I register the site through simplification.

php code that processes the request and writes the number of comments to the database:
$post = $_POST;
if (!isset($post['num'])){
     $error = 'не указано количество';
    $apiSecret = %ВАШ_API_SECRET%;//(да, за этим мы и прошли полную регистрацию)
    $hash = md5($apiSecret.$post['date'].$post['num'].$post['last_comment']);// до того, как обновить количество комментариев, мы получаем md5 - хэш от параметров api_secret, date, num, last_comment:
    if (strcmp($hash, $post['sign']) == 0){//проверяем что хэши совпадают
        //тут код сохранения в базу
        $error = 'не совпадает хэш';

That's all! If desired, you can save not only the number of comments to the database, but also the comments themselves. I hope that the article was useful and I did not waste time in vain.

Also popular now: