React Google Login and Store Data to backend

237 Views Asked by At

My frontend can login success with google but when I want store data to backend alway get Google ID token is missing in the response.Seem need pass the google id to backend then only backend can store...But where to get the google id token , it is no same with client_id right?

This is my frontend code

function handleCallbackResponse(response) {
    // Check if the response contains the Google ID token
    if (response.credential && response.credential.id_token) {
      var googleIdToken = response.credential.id_token;

      // Send the Google ID token to the backend
      axios
        .post("http://your_back_end_url/register", {
          googleAccessToken: googleIdToken, // Send the Google ID token to the server
        })
        .then((backendResponse) => {
          console.log("Backend response:", backendResponse.data);
          navigate("/"); // Redirect the user to the desired page after successful login
        })
        .catch((error) => {
          console.error("Error making the backend request:", error);
          // Handle the error as needed
        });
    } else {
      // Handle the case where the Google ID token is missing in the response
      console.error("Google ID token is missing in the response.");
      // Handle the error as needed
    }
  }

  useEffect(() => {
    /* global google */
    window.google.accounts.id.initialize({
      client_id:
        "YOUR_CLINET_ID":,
      callback: handleCallbackResponse,
    });

    return () => {};
  }, []);

  const handleCustomGoogleSignIn = () => {
    // Trigger the Google Sign-In process
    window.google.accounts.id.prompt();
  };

Then my backend is using php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Assuming you receive the user's data as JSON
    $inputJSON = file_get_contents('php://input');
    $data = json_decode($inputJSON, true);

    // Verify the Google token
    $client = new Google_Client(['client_id' => 'YOUR_CLIENT_ID']); // Replace with your actual client ID
    $payload = $client->verifyIdToken($data['googleAccessToken']);

    if ($payload) {
        // User data from Google
        $googleUserData = [
            'name' => $payload['name'],
            'email' => $payload['email'],
        ];

        // Get the database connection from your Config class (assuming it's working correctly)
        $objDb = new Config();
        $conn = $objDb->connect();

        // Prepare and execute an SQL query to insert the user data into your users table
        $sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
        $stmt = $conn->prepare($sql);
        $stmt->execute($googleUserData);

        // Respond with a success message
        $response = [
            'message' => 'User data stored successfully',
        ];

        echo json_encode($response);
    } else {
        // Token verification failed
        http_response_code(401); // Unauthorized
        echo json_encode(['error' => 'Token verification failed']);
    }
} else {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['error' => 'Invalid request method']);
}
1

There are 1 best solutions below

0
BugHunter On

In the frontend, you need only the GOOGLE_CLIENT_ID to initiate the Google Sign-In process. However, in your backend, you need both the GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET to securely verify and authenticate user access through Google's OAuth services.