2
<?php
include_once "templates/base.php";
session_start();

require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');

$client_id = '*******';
$client_secret = '*******';
$redirect_uri = '*********';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);

$client->addScope("https://www.googleapis.com/auth/admin.directory.group");

$directory = new Google_Service_Directory($client);

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

if ($client->getAccessToken())
{
    $groupKey = "MY_EMAIL";
    $group = $directory->members->listMembers($groupKey);

    $_SESSION['access_token'] = $client->getAccessToken();
}

echo pageHeader("Group Members");

if (strpos($client_id, "googleusercontent") == false) {
  echo missingClientSecretsWarning();
  exit;
}
?>
<div class="box">
      <div class="request">
        <?php 
        if (isset($authUrl)) {
          echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
        } else {
          echo "<a class='logout' href='?logout'>Logout</a>";
        }
        ?>
      </div>

      <div class="shortened">
        <?php
        if (isset($group)) {
          var_dump($group);
        }
        ?>
      </div>
</div>

I have implemented this example in my local system to find all members of groups using google api client php. but i dont know why when i m connect to google using auth and allow permission to access directory, when redirect its not return list.

So please help me and suggest me where i m doing wrong in this code.

I m using Email as my groupKey.

3 Answers 3

2

Here is some code I wrote that I think might help you. This code will pull a listing of all the groups you have read access to and their memberships.

When pulling the groups, I check if the variable nextPageToken is set. If this is set, it means you have reached the 200 max limit result set. If nextPageToken is set, the code will continue to loop and grab the next set until nextPageToken is blank.

I make use of the batch class in the first pass at getting group memberships to speed things up. After the first pass, I again then check for the existence of the nextPageToken variable and continue to loop until all members are returned.

After the script runs, an array called $lists is populated with all the groups and their respective memberships.

<?php
  $start = microtime(true);

  require_once('/path/to/google-api-php-client/src/Google/autoload.php');
  $service_account_name = 'your service account address'; //Email Address
  $key_file_location = '/path/to/your.p12'; //key.p12

  $client = new Google_Client();
  $client->setApplicationName("Client_Library_Examples");
  $dir = new Google_Service_Directory($client);
  $domain = 'yourdomain.com';

  if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
  }

  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/admin.directory.group.readonly'),
    $key
  );

  $cred->sub = "[email protected]"; // a privilidged users email address
  $client->setAssertionCredentials($cred);
  if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }

  $_SESSION['service_token'] = $client->getAccessToken();

  // Get all of our groups
  $googleGroups = $dir->groups->listGroups(array('domain'=>$domain));
  $groups = $googleGroups->getGroups();

  // if we have a paginated result set, continue doing a lookup until we are at the end
  while (isset($googleGroups->nextPageToken) && ($googleGroups->nextPageToken != '')) {
    $googleGroups = $dir->groups->listGroups(array('domain'=>$domain,'pageToken'=>$googleGroups->nextPageToken));
    $groups = array_merge($groups, $googleGroups->getGroups());
  }

  // Ok, we have all our groups. Now lets build an array that we can use later to populate with group members
  $lists = array();
  foreach ($groups as $key=>$val) {
    $lists[$val->id] = array('id'=>$val->id,'description'=>$val->description,'email'=>$val->email,'name'=>$val->name,'members'=>'');
  }

  // Doing a batch query for all members of the groups to reduce execution time
  $client->setUseBatch(true);
  $batch = new Google_Http_Batch($client);
  foreach ($groups as $k=>$v) {
    $members = $dir->members->listMembers($v->email);
    $batch->add($members, $v->id);
  }

  // execute our batch query
  $results = $batch->execute();

  // turn off batch queries now so we can query for more members in the case of paginated result sets
  $client->setUseBatch(False);
  foreach ($results as $k=>$v) {
    $all = $v->getMembers();
    $id = substr($k, 9); // the array key is in the form of response-XXX, lets get rid of the response- bit

    while (isset($v->nextPageToken) && ($v->nextPageToken != '')) {
      $members = $dir->members->listMembers($lists[$id]['email'],array("pageToken"=>$v->nextPageToken));
      $v->nextPageToken = $members->nextPageToken;
      $all = array_merge($all, $members->getMembers());
    }

    foreach ($all as $key=>$val) {
      $lists[$id]['members'][] = $val->email;
    }

  }

  $time_elapsed_secs = microtime(true) - $start;
  print "\n\n" . $time_elapsed_secs . "\n\n";
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to Stack Overflow! This is a pretty big code block, so it would be helpful both to the original poster and to future visitors if you described how it worked.
1

https://developers.google.com/admin-sdk/directory/v1/reference/members/list

You can check this link and this is the "GET" for it

GET https://www.googleapis.com/admin/directory/v1/groups/groupKey/members

Comments

1
public function getAllGroupMembers($groupid, $role = null)
{

     $allmembers = array();
      try {
             $pageToken = NULL;

    $optParams = array(
        'roles' => $role,
       
    );
        do {
            if ($pageToken) {
                $optParams['pageToken'] = $pageToken;
            }
            try {
                $results = self::$service_directory->members->listMembers($groupid,$optParams);
            } catch (Exception $e) {
                print 'An error occurred: ' . $e->getMessage() . 'calling listmemembers function';
            }
            $pageToken = $results->getNextPageToken();
               
            $allmembers = array_merge($allmembers, $results->getMembers()); 

            
        } while ($pageToken);
    } catch (Exception $e) {
        print 'An error occurred: ' . $e->getMessage();
    }
 
   return  $allmembers;
    
    
}

1 Comment

While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. You can use the edit button to improve this answer to get more votes and reputation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.