Google Oauth авторизация на сайте [php-код]

Відповісти
Аватар користувача
admin
Администратор
Повідомлень: 26
З нами з: 11 травня 2020, 12:32

Google Oauth авторизация на сайте [php-код]

Повідомлення admin »

Как регистрировать свое приложение на https://console.cloud.google.com/apis я не буду описывать, это легко найти в интернете. А вот рабочий код PHP вообще не реально найти, везде предлагают практически один и тот же код, но он не рабочий. А вернее работает только в Mozilla Firefox. Поэтому предлагаю свой вариант кода. Библиотеку jQuery.ajax можете подключить и свою, для примера прилагаю файл.
jquery-1.11.3.min.js
(93.71 Кіб) Завантажено 123 разів

Естественно client_id и client_secret заменить на свои. Не забудьте добавить в https://console.cloud.google.com/apis ваш redirect_uri.
Полученные данные уже обрабатывайте как вам угодно.

Код: Виділити все

<?php
$client_id="ВАШ_client_id";
$client_secret="ВАШ_client_secret";
$redirect_uri=$_SERVER["SCRIPT_URI"];

if(isset($_GET["action"])){
	if($_GET["action"]=="retinfo"){
		$aaa=json_decode($_GET["u_info"], true);
		print_r($aaa);
		die;
	}
}
if(isset($_GET["action"])){
	if($_GET["action"]=="rettoken"){
		$params = array(
			"access_token" => $_GET["access_token"],
			"id_token"     => $_GET["id_token"],
			"token_type"   => "Bearer",
			"expires_in"   => 3599
		);
		$info = file_get_contents("https://www.googleapis.com/oauth2/v1/userinfo?" . http_build_query($params));
		print_r($info);
		die;
	}
}

if(!isset($_GET["code"])) {
	$params = array(
		"redirect_uri"	=> $redirect_uri,
		"client_id"	=> $client_id,
		"response_type"	=> "code",
		"scope"		=> "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
	);
	echo "<html>
<head>
	<meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\" />
	<title>Аутентификация через Google</title>
	<script type=\"text/javascript\" src=\"js/jquery-1.11.3.min.js\"></script>
</head>
<body>\n";
	echo "<p><a href=\"https://accounts.google.com/o/oauth2/auth?".http_build_query($params)."\">Аутентификация через Google</a></p>";
} else {
	$params = array(
		"client_id"     => $client_id,
		"client_secret" => $client_secret,
		"redirect_uri"  => $redirect_uri,
		"grant_type"    => "authorization_code",
		"code"          => $_GET["code"]
	);
	echo "<script type=\"text/javascript\" src=\"js/jquery-1.11.3.min.js\"></script>
<script>
<!--
	jQuery.ajax({
		url: \"https://accounts.google.com/o/oauth2/token\",
		type: \"post\",
		dataType: \"html\",
		data: {client_id: \"".$client_id."\", client_secret: \"".$client_secret."\", redirect_uri: \"".$redirect_uri."\", grant_type: \"authorization_code\", code: \"".$_GET["code"]."\"},
		success: function(response) {
			arr = JSON.parse(response);
			jQuery.ajax({
				url: \"?action=rettoken&access_token=\"+arr[\"access_token\"]+\"&id_token=\"+arr[\"id_token\"],
				type: \"post\",
				dataType: \"html\",
				success: function(response) {
					location.href=\"?action=retinfo&u_info=\"+encodeURI(response);
				},
				error: function(response) {
				}
			});
		},
		error: function(response) {
		}
	});
-->
</script>\n";
}

echo "</body>
</html>";
?>
Відповісти