You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何制作谷歌验证注册框并将用户G+邮箱及数据存入数据库?

实现带Google验证的网站注册功能(存储Google邮箱及用户数据到数据库)

Alright, let's walk through building a registration system with Google Sign-In that stores users' Google Account emails (previously tied to G+) and related data in your database. I'll break this down into manageable parts with code examples you can adapt.

1. Front-End: Integrate Google Sign-In

First, you'll need to set up the Google Sign-In button on your front-end and capture user data to send to your back-end.

Step 1: Add the Google Sign-In Script

Include the Google platform script in your HTML:

<script src="https://apis.google.com/js/platform.js" async defer></script>

Step 2: Add the Sign-In Button

Add the pre-built Google Sign-In button (you can customize styling later):

<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>

Step 3: Handle Sign-In Callback

Write a function to grab user details and send them to your back-end registration endpoint:

function onSignIn(googleUser) {
  // Fetch the ID Token for back-end verification (critical for security)
  const idToken = googleUser.getAuthResponse().id_token;
  
  // Extract user profile data
  const profile = googleUser.getBasicProfile();
  const userData = {
    email: profile.getEmail(),
    fullName: profile.getName(),
    googleUserId: profile.getId(),
    idToken: idToken
  };

  // Send data to your back-end
  fetch('/api/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData)
  })
  .then(res => res.json())
  .then(result => {
    if (result.success) {
      alert("Registration successful! 🎉");
      // Redirect to dashboard or home page here
    } else {
      alert(`Oops: ${result.message}`);
    }
  })
  .catch(err => console.error("Registration error:", err));
}

2. Back-End: Validate Token & Store Data

I'll use Node.js + Express + MySQL for this example, but you can adapt the logic to any back-end language (Python/Flask, PHP, etc.).

Step 1: Install Dependencies

npm install express mysql2 google-auth-library

Step 2: Back-End Code

Replace placeholder values (like your Google Client ID and database credentials) with your actual info:

const express = require('express');
const { OAuth2Client } = require('google-auth-library');
const mysql = require('mysql2/promise');
const app = express();

// Parse JSON requests
app.use(express.json());

// Initialize Google OAuth client (get this from Google Cloud Console)
const GOOGLE_CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID';
const client = new OAuth2Client(GOOGLE_CLIENT_ID);

// Database configuration
const dbConfig = {
  host: 'localhost',
  user: 'YOUR_DB_USER',
  password: 'YOUR_DB_PASSWORD',
  database: 'YOUR_DB_NAME'
};

// Registration endpoint
app.post('/api/register', async (req, res) => {
  const { email, fullName, googleUserId, idToken } = req.body;

  try {
    // 1. Validate the Google ID Token (never skip this!)
    const ticket = await client.verifyIdToken({
      idToken: idToken,
      audience: GOOGLE_CLIENT_ID
    });
    const payload = ticket.getPayload();
    
    // Ensure the email matches what Google returned (prevents tampering)
    if (payload.email !== email) {
      return res.json({ success: false, message: "Email verification failed" });
    }

    // 2. Connect to database
    const connection = await mysql.createConnection(dbConfig);

    // 3. Check if user already exists
    const [existingUsers] = await connection.execute(
      'SELECT id FROM users WHERE google_user_id = ? OR email = ?',
      [googleUserId, email]
    );

    if (existingUsers.length > 0) {
      await connection.end();
      return res.json({ success: false, message: "User already registered" });
    }

    // 4. Insert new user into database
    await connection.execute(
      'INSERT INTO users (google_user_id, email, full_name, created_at) VALUES (?, ?, ?, NOW())',
      [googleUserId, email, fullName]
    );

    await connection.end();
    res.json({ success: true, message: "User registered successfully" });

  } catch (err) {
    console.error("Backend error:", err);
    res.json({ success: false, message: "Server error occurred" });
  }
});

// Start server
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

3. Database Setup (MySQL Example)

Create a users table to store the data:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  google_user_id VARCHAR(255) NOT NULL UNIQUE,
  email VARCHAR(255) NOT NULL UNIQUE,
  full_name VARCHAR(255) NOT NULL,
  created_at DATETIME NOT NULL
);

Key Important Notes

  • Google Cloud Console Setup: You must create a project in the Google Cloud Console, enable the Google Sign-In API, and generate a client ID. Make sure this ID matches in both front-end and back-end.
  • Security First: Always validate the ID Token on the back-end—never trust front-end data alone. This prevents fake registration requests.
  • Unique Constraints: The google_user_id and email fields should be unique in your database to avoid duplicate accounts.
  • Error Handling: Expand the error handling to cover edge cases like database connection failures or expired tokens.

内容的提问来源于stack exchange,提问作者user7994613

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:46:24