G Suite のAPIを使って作成済みのグループの一覧を取得する
問題
G SuiteのGoogleグループで、APIを利用して、グループの一覧を取得したり、まとめて設定を確認したりしたいです。

答え
google/apiclient を使う例。
1.場所を作る
$ mkdir xxx
$ cd xxx
2.google/apiclient をcomposerで持ってくる
$ composer require google/apiclient
3.Googleグループを作るphpスクリプトを書く
$ vi getlist.php
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
// Googleの公式のサンプルのまね
function getClient()
{
$client = new Google_Client();
$client->setApplicationName("sample application");
$client->setScopes(implode(' ', array(
'https://www.googleapis.com/auth/admin.directory.group',
)));
$client->setAuthConfigFile(__DIR__ . '/client_secret_000000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = __DIR__ . '/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
$client = getClient();
$service = new Google_Service_Directory($client);
$service2 = new Google_Service_Groupssettings($client);
$result = $service->groups->listGroups(array(
'customer' => 'my_customer',
'maxResults' => 1000,
'orderBy' => 'email',
));
foreach ($result as $group) {
$group_detail = $service2->groups->get($group->getEmail(), ["alt" => "json"]);
// $group_detail にグループの設定情報が入っている
var_dump($group_detail);
// これをCSVに出力したりデータベースに保存するなどして管理できる
}
4.OAuth 2.0 クライアント IDを作成
※すでに作成済み、認証情報取得済みなら不要です
https://console.developers.google.com/apis/credentials
JSON形式の認証情報をダウンロードして保存する。
3のphpのプログラム中の client_secret_000000000000-xxxxxxxxxxxxx.json のファイル名はダウンロードしたものにする。
5.コマンドラインで実行する
$ php getlist.php

G Suite への移行作業が大変なときはご相談ください
- 既存のメーリングリストをGoogleグループに移したい
- 既存のメーリングリストの過去ログをGoogleグループに入れたい
- 多数のGoogleグループの設定を管理したい
- 既存のメールアドレスで G Suite(Gmail)に移行したい
内容に応じてお見積りします。
➡ お問い合わせはこちらまで rs@softel.jp