VK API. Authorization for the site

In order not to write a very large article, I reduced the code only to the necessary minimum. Those. no checks, powerful filters for errors and other things. Only that which is directly necessary for authorization, for understanding what is happening. Also, the article is designed to have at least basic knowledge of PHP and HTML. Details will be described only functions and techniques that are very rare.

Before starting, I want to explain a little algorithm.


  1. We create the application on off site vk

  2. Get his ID

  3. We make a link on the site in which we send a request to the VK server

  4. We get the code in response

  5. We make another request, in which we insert the application id, the protected key and just this code

  6. We get the access_token needed for further use of the API. From this moment it can be considered that the user is authorized. Invalid user is not given a token

  7. ???

  8. profit !!! 11


First you need to create an “application”. This can be done here: https://vk.com/editapp?act=create



Everything is simple. We put a stamen in front of the website and fill in the info.
Yes, seriously, local hosts (localhost) can also be specified and they work quite well.

Once created, all you need to do is open the app settings and copy the app id and secure key somewhere. We're going to need them soon.

The next step is to get started with a piece of code. I will create a new file with a link, let it be authreg.php . Also, I will create another file that will handle everything else. I will name it auth_vk.php .

Open authreg.php . It will be just a link.

<?php

    $id_app     = 'ВАШ ID';                             //ID App

    $url_script = 'https://localhost/auth_vk.php'; //url auth_vk.php

?>

<a href='<?php echo 'https://oauth.vk.com/authorize?client_id='.$id_app.'&redirect_uri='.$url_script.'&response_type=code'; ?>'>Log in with VK</a></p>

Everything. This file we no longer need.

Open auth_vk.php .

In this example, I will save all the authorization data in the session. You can do otherwise.
First of all, I will open a small condition for checking the code value that came to us in GET from the VK server.
Next, we will send the VC server the received value code + the protected key and application id to get access_token , and we will immediately use it, having received the name and surname of the one who clicked the button. We write the entire result into the session and send the user to another page of the site. In practice, I would recommend finalizing this script and writing a new user to the database and so on.

 

[spoiler title='A little bit about how api vk requests should look']In order to call the VKontakte API method, you need to make a POST or GET request for the HTTPS protocol to the specified URL:

https://api.vk.com/method/&#39;METHOD_NAME?&#39;&#39; PARAMETERS access_token ACCESS_TOKEN

METHOD_NAME is the name of the method from the API feature list,
PARAMETERS are the parameters of the appropriate API method,
ACCESS_TOKEN is the access key gained as a result of successful application authorization.

(c) From official documentation[/spoiler]

<?php
session_start ();
if  (!empty($_GET ['code']))  {
 $id_app     =     'ID Apps' ;                      //ID Apps
 $secret_app =    'secret_key';         // Secret key. You can find out where you go
 $url_script   =    'https://localhost/auth_vk.php'; //url
 $token = json_decode(file_get_contents('https://oauth.vk.com/access_token?client_id='.$id_app.'&client_secret='.$secret_app.'&code='.$_GET['code'].'&redirect_uri='.$url_script), true);
 $fields       = 'first_name,last_name';
 $uinf = json_decode(file_get_contents('https://api.vk.com/method/users.get?uids='.$token['user_id'].'&fields='.$fields.'&access_token='.$token['access_token'].'&v=5.80'), true); 
 $_SESSION['name']         = $uinf['response'][0]['first_name'];
 $_SESSION['name_family']  = $uinf['response'][0]['last_name'];
 $_SESSION['uid']          = $token['user_id'];
 $_SESSION['access_token'] = $token['access_token'];

header("Location: /mypage.php");
    }
?>

The file_get_contents feature is used here to get a response from GET to php without rebooting the page. Straight to the variable. Convenient.
The json_decode allows you to decode JSON strings.
[spoiler title='A bit about JSON. For reference.']JSON lines look something like this:

"response":[{"cid":1,"name":"Moscow"}]"

[/spoiler]

You can add other things to the fields variable that this method allows to use. With the name and surname you can also get an avatar, online, city, gender and much more.
More details about the users.get method: https://vk.com/dev/users.get
More about the fields parameter: https://vk.com/dev/fields

Actually, that's all. Authorization has already been completed. Nevertheless, in order to make sure that everything is as it should, I also suggest creating mypage.php , we go there at the end of the script and display all the sessions that we received on the screen there for verification.
The content of mypage.php:

<?php
session_start();
echo 'user id = '.$_SESSION['uid'].'<br>';
echo 'access token = '.$_SESSION['access_token'].'<br>';
echo 'username = '.$_SESSION['name'].'<br>';
echo 'name family = '.$_SESSION['name_family'].'<br>';
?>

I whipped it up. If you make some mistakes or suddenly you need details - write in this topic, answer as soon as I can.