使用Google Directory API获取GSuite用户组的PHP技术问询
Hey there! Let's work through getting those Google Directory API group memberships pulled in for your NGO's PHP site. Since you already have the user data coming through from your callback, we just need to iron out the API call part.
First, let's cover the common pitfalls and then jump into code:
1. Make sure you've got the right setup in place
- Enable the Google Directory API: Head over to your Google Cloud Platform project, search for "Google Directory API" in the APIs & Services section, and make sure it's enabled. If it's off, flip the switch—this is a super common oversight!
- Add the correct OAuth scope: When you initialize your Google Client, you need to include the readonly scope for group access. Add this to your existing scopes:
This ensures your app asks the user for permission to view their group memberships during login.$client->addScope('https://www.googleapis.com/auth/admin.directory.group.readonly'); - Check domain permissions: If your NGO's Google Workspace (formerly GSuite) admin has restricted third-party app access to directory data, they'll need to allow your app to use this scope in the Admin Console under Security > API Controls.
2. Code to fetch user groups
Assuming you're using the official Google Client Library for PHP (if not, install it first with composer require google/apiclient:^2.0), here's how to extend your callback code to pull groups:
// Require the autoloader (if you haven't already) require __DIR__ . '/vendor/autoload.php'; // Initialize your Google Client with your existing config $client = new Google\Client(); $client->setClientId('YOUR_CLIENT_ID'); $client->setClientSecret('YOUR_CLIENT_SECRET'); $client->setRedirectUri('YOUR_REDIRECT_URI'); // Add your existing scopes plus the group readonly scope $client->addScope('openid'); $client->addScope('profile'); $client->addScope('email'); $client->addScope('https://www.googleapis.com/auth/admin.directory.group.readonly'); // Fetch and set the access token (you probably already do this part) if (isset($_GET['code'])) { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); $client->setAccessToken($token); // Get the user's email from your existing $userData $userEmail = $userData['email']; // Initialize the Directory Service $directoryService = new Google\Service\Directory($client); try { // Fetch all groups the user is a member of $groupsResponse = $directoryService->users->listUsersGroups($userEmail); $userGroups = $groupsResponse->getGroups(); // Loop through the groups to use them for access control $allowedGroups = []; foreach ($userGroups as $group) { // Example: Store group emails in an array to check permissions later $allowedGroups[] = $group->getEmail(); } // Now use $allowedGroups to restrict page access // e.g., if (in_array('members@yourngo.org', $allowedGroups)) { show member page } } catch (Google\Service\Exception $e) { // Catch and log the error to debug—this will tell you exactly what's wrong error_log("Directory API Error: " . $e->getMessage()); echo "Oops, we couldn't fetch your group memberships right now. Please try again later."; } }
3. Debug tips
If you're still hitting issues:
- Check the error message from the
Google\Service\Exception—it'll tell you if the API is disabled, permissions are missing, or there's an invalid token. - Verify that the user's Google Workspace account is allowed to view their own group memberships (most default setups allow this).
- Double-check that your client ID/secret and redirect URI match exactly what's in your GCP project.
Once you have the user's groups stored, you can easily use that array to conditionally show/hide pages based on their membership—perfect for your NGO's access control needs!
内容的提问来源于stack exchange,提问作者hdjakhds

