Естественно 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>";
?>