javascript – 如何将google登录到我的网站并收集用户详细信息?
作者:互联网
我想将google登录按钮集成到my website.我知道HTML但我不确定php和java脚本.最终,我希望谷歌登录以登录用户并给我他们的信息,以便我可以安全地将它存储在我的数据库phpmyadmin上.我已经访问了the google tutorial,但发现它没有解释如何完全收集用户信息.我试图遵循这一点,到目前为止我有this,但它远没有它应该是什么样的.我已经看过其他教程,例如this one.但是我发现他们都没有按照谷歌说明,例如你必须在其中下载谷歌API,但是在谷歌网站上它没有提到下载任何东西.
以下是使用google教程的what i have managed to do so far的代码:
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="808271051181-424qcdq0emrd0pd77frfiuacvcetp58t.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
</body>
</html>
解决方法:
您可能能够在javascript中从配置文件中获取所有数据,但我想将所有数据都放入php变量中,以便我可以存储在我的数据库中.为此,我将google id令牌作为javascript的发布数据发送(如何做到here).
您仍然需要所有其他谷歌登录代码,但我用以下代码替换了onSingIn:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
document.getElementById("userid").value = googleUser.getAuthResponse().id_token;
document.getElementById("userid").form.submit();
}
还要在正文中添加表单代码:
<form action="login.php" method="post">
<input type="hidden" name="id" id="userid">
</form>
然后你需要另一个我称之为login.php的文件,它包含以下函数:
function get_var($var)
{
$id = $_POST["id"]; // id from google
$id_token = file("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" . $id); // decrypted id
foreach ($id_token as $part) {
// part is a factor of the user such as name or email
// remove unecessary charcters
$peice = str_replace("\"", "", $part);
$peice = str_replace(",", "", $peice);
$peice = substr($peice, 0, strpos($peice, ":") + 2);
if (strpos($peice, $var) !== false) {
$var = str_replace("\"", "", $part);
$var = str_replace(",", "", $var);
$var = substr($var, strpos($var, ":") + 2);
return $var;
}
}
}
有了这个,您应该能够获得所需的所有信息.示例用途:
$name = trim(get_var("name"));
$email = trim(get_var("email"));
要查看所有可访问的信息,请在get_var中打印$id_token,或者转到https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=,在末尾添加id标记.
有关从ID令牌here获取数据的更多信息.
标签:html,javascript,php,google-signin 来源: https://codeday.me/bug/20191002/1844071.html