PHP集成Google OAuth2.0生成令牌后获取用户邮箱并存储
Hey there! Nice job getting the access and refresh tokens working already. Let's walk through how to grab the user's email and save both that and the refresh token to your database.
Step 1: Add the Email Scope
First, you need to request permission to access the user's email. Update your scope list in both the authorization redirect code and callback code to include the email scope. You can use either the full scope URL or the shorthand email (both work):
// In your authorization redirect code $client->addScope(['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/userinfo.email']); // OR shorthand version (more readable) $client->addScope(['calendar', 'email']);
This tells Google that your app needs access to the user's email address along with calendar permissions.
Step 2: Fetch User Email in the Callback
Once the user grants access and you have the access token, you can fetch their profile data (including email) using Google's OAuth2 service. Also, note that setAuthConfigFile is deprecated—replace it with setAuthConfig to match your redirect code:
<?php require 'vendor/autoload.php'; $client = new Google_Client(); $client->setAuthConfig('client_secret_2344056t4.apps.googleusercontent.com.json'); // Replaced deprecated method $client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/google_calendar2/oauth2callback.php'); $client->addScope(['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/userinfo.email']); // Added email scope // Authenticate with the code from the request $client->authenticate($_GET['code']); $access_token = $client->getAccessToken(); $refresh_token = $access_token['refresh_token']; // Grab refresh token from the access token array // Fetch user email using OAuth2 service $oauth_service = new Google_Service_Oauth2($client); $user_info = $oauth_service->userinfo->get(); $user_email = $user_info->getEmail(); // This gives you the user's verified email // Optional: Test output echo "Refresh Token: " . $refresh_token . "<br>"; echo "User Email: " . $user_email;
Step 3: Save to Database
Now that you have both values, you can save them to your database. Below is a secure PDO example (update your database credentials as needed):
// Database configuration $db_host = 'localhost'; $db_name = 'your_database_name'; $db_user = 'your_db_username'; $db_pass = 'your_db_password'; try { // Connect to database with PDO $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Prepare insert statement (use ON DUPLICATE KEY UPDATE to refresh tokens for returning users) $stmt = $pdo->prepare("INSERT INTO google_auth_tokens (email, refresh_token) VALUES (:email, :refresh_token) ON DUPLICATE KEY UPDATE refresh_token = :refresh_token"); // Bind parameters (prevents SQL injection) $stmt->bindParam(':email', $user_email); $stmt->bindParam(':refresh_token', $refresh_token); // Execute the statement $stmt->execute(); echo "Token and email saved successfully!"; } catch(PDOException $e) { echo "Error: " . $e->getMessage(); }
Quick Notes:
- Make sure your
google_auth_tokenstable has theemailcolumn set as a unique key to avoid duplicate entries for the same user. - Always use parameter binding (like we did with PDO) to protect against SQL injection attacks.
- Consider encrypting the refresh token before storing it in the database for extra security.
- Double-check that the OAuth2 API is enabled in your Google Cloud Console (it's usually enabled by default, but it's worth confirming if you run into issues).
内容的提问来源于stack exchange,提问作者web crew24

