我正在开发一个简单的个人项目,该项目将允许用户使用 Google GSI 库 OAauth 2.0 使用 google 帐户登录。我探索了有关如何使用 GSI 库并在我的代码中实现它的文档。
流程是这样的:用户在 Google Sign In 中选择帐户后,将检查电子邮件(google_signin.php)是否已存在于数据库中。如果为 true,则继续创建会话并将用户重定向到 index.php。问题是选择Google帐户后,它仅重定向到login.php而不是index.php并创建会话。
这些文件是:login.php、google_signin.php(用于检查电子邮件)、index.php(用户登录后必须重定向)。
这是代码
<script>
function onSignIn(response) {
const { id_token, access_token, email } = response.credential; // Include email in response
fetch('google_signin.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id_token, access_token, email }), // Include email in JSON
})
.then(response => response.json())
.then(data => {
if (data.success) {
// User's email address is valid, create a session and log them in
// Implement your session creation and login logic here
console.log('User is authenticated and can be logged in.');
// You can redirect to index.php here
// window.location.href = 'index.php';
} else {
// Display an error message or prompt the user to create a new account
console.error('User email address not found in the database:', email);
}
})
.catch(error => {
console.error('Server verification failed:', error);
});
}
</script>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="34178471422-5chptlf4ujd05p5a6suhvglmcc2f9jgk.apps.googleusercontent.com"
data-callback="onSignIn"
data-auto_prompt="false"
data-ux_mode="redirect"
data-login_uri="http://localhost/public_html/index.php">
</div>
<div class="g_id_signin" data-type="standard"></div>
这是 google_signin (PHP 代码)https://pastecode.io/s/to2n4d0u
任何建议都将受到高度赞赏。
在您的 onSignIn 函数中,您正在调用 fetch,这是一个异步函数调用,您是否应该在返回函数之前等待(带 wait fetch 的异步函数)结果?
function async onSignIn(response) {
await fetch('google_signin.php', {...})
}