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 create-group.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;
}
// 作成したいGoogleグループのリスト
$entries = array(
'abc@example.com',
'def@example.com',
'ghi@example.com'
);
$client = getClient();
$service = new Google_Service_Directory($client);
foreach ($entries as $entry) {
try {
$group = new Google_Service_Directory_Group();
$group->setEmail($entry);
// $group->setName('名前');
// $group->setDescription('説明');
$result = $service->groups->insert($group);
// $result には作成されたグループについての情報が入っている
// var_dump($result);
echo '作成できました: ' . $result->getEmail() . "\n";
} catch (Google_Service_Exception $e) {
// 例外が発生した場合、500、503ならリトライする、スキップする、400系なら制限がかかったかもなど対応する
if ($e->getCode() == 503) {
echo $e->getMessage() . "\n";
} else {
throw $e;
}
}
}
4.OAuth 2.0 クライアント IDを作成
※すでに作成済み、認証情報取得済みなら不要です
https://console.developers.google.com/apis/credentials
JSON形式の認証情報をダウンロードして保存する。
3のphpのプログラム中の client_secret_000000000000-xxxxxxxxxxxxx.json のファイル名をダウンロードしたものにする。
5.コマンドラインで実行する
$ php create-group.php

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