VK ID простая авторизация на PHP с проверкой возраста v=5.131
Подключаем вк id
и создаём приложение по ссылке
https://id.vk.com/about/business/
На фронте
```
<button id="vk-login">Войти через VK ID</button>
<script>
document.getElementById('vk-login').onclick = function () {
const appID = 'ИД_ПРИЛОЖЕНИЯ1'
const url = 'КУДА_РЕДИРЕКТ_ПРИ_РЕГИСТРАЦИИ1'
const vkAuthUrl = `https://oauth.vk.com/authorize?client_id=${appID}&display=page&redirect_uri=${url}&scope=email&response_type=code&v=5.131`
window.location.href = vkAuthUrl;
};
</script>
```
На бэке PHP
по адресу КУДА_РЕДИРЕКТ_ПРИ_РЕГИСТРАЦИИ1
```
<pre><?php //exit();
$appID = 'ИД_ПРИЛОЖЕНИЯ1';
$secret = 'СЕКРЕТНЫЙ_КЛЮЧ_ПРИЛОЖЕНИЯ';
$redirectURI = 'КУДА_РЕДИРЕКТ_ПРИ_РЕГИСТРАЦИИ1';
// Для получения данных
$context = stream_context_create([
'http' => [
'method' => 'GET',
],
]);
// Функция для расчёта возраста
function calculateAge($bdate) {
$parts = explode('.', $bdate);
if (count($parts) < 3) return 0; // Если год рождения не указан
[$day, $month, $year] = $parts;
$birthDate = new DateTime("$year-$month-$day");
$today = new DateTime();
$age = $today->diff($birthDate)->y;
return $age;
}
// Принимаем code
if (!isset($_GET['code']))
die('Ошибка: код авторизации не передан.');
$code = $_GET['code'];
//die($code);
// Обмен `code` на `access_token`
$tokenUrl = "https://oauth.vk.com/access_token?client_id=$appID&client_secret=$secret&redirect_uri=$redirectURI&code=$code";
$response = @file_get_contents($tokenUrl, false, $context);
if ($response == false)
die('Неудачное получение токена 1');
$data = json_decode($response, true);
if ($data == null)
die('Неудачное получение токена 2');
if (!isset($data['access_token']) || !isset($data['user_id']))
die('Неудачное получение токена 3');
$accessToken = $data['access_token'];
$userID = $data['user_id'];
// Получение данных пользователя
//$userInfoUrl = "https://api.vk.com/method/users.get?user_ids=$userId&fields=bdate&access_token=$accessToken&v=5.131"; // Это без подтверждения
$userInfoUrl = "https://api.vk.com/method/account.getProfileInfo?v=5.199&user_ids=$userID&access_token=$accessToken";
$userInfoResponse = @file_get_contents($userInfoUrl, false, $context);
if ($userInfoResponse == false)
die('Неудачное получение данных 1');
$userInfo = json_decode($userInfoResponse, true);
if ($userInfo == null)
die('Неудачное получение данных 2');
if (isset($userInfo['response']))
$userInfo = $userInfo['response'];
print_r([
$data,
$userInfo
]);
if (
!isset($userInfo['verification_status']) ||
$userInfo['verification_status'] != 'verified' ||
!isset($userInfo['account_verification_profile']) ||
!isset($userInfo['account_verification_profile']['birthdate'])
)
die('Подтвердите ВК аккаунт через гос-услуги');
$age = calculateAge($userInfo['account_verification_profile']['birthdate']);
if ($age < 18)
die("для регистрации Вам должно быть 18 лет или больше.");
echo "Допускаем к входу";
```