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 listmembers.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',
'https://www.googleapis.com/auth/admin.directory.group.member'
)));
$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;
}
// 設定対象のグループの一覧
$entries = array(
'test001@example.com',
'test002@example.com',
'test003@example.com'
);
$client = getClient();
$service = new Google_Service_Directory($client);
foreach ($entries as $entry) {
try {
$result = $service->members->listMembers($entry);
foreach ($result as $member) {
var_dump($member->email);
}
} catch (Google_Service_Exception $e) {
// @todo エラー時の対応
throw $e;
}
}
https://developers.google.com/admin-sdk/directory/v1/reference/members/update
4.OAuth 2.0 クライアント IDを作成
※すでに作成済み、認証情報取得済みなら不要です
https://console.developers.google.com/apis/credentials
JSON形式の認証情報をダウンロードして保存する。
3のphpのプログラム中の client_secret_000000000000-xxxxxxxxxxxxx.json のファイル名はダウンロードしたものにする。
5.コマンドラインで実行する
$ php listmembers.php

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