PHP开发

Google Group添加成员代码实例

接上一篇文章用Directory API管理Google Groups,本文只写代码,注释在代码中。需要下载google client library,并将autoload.php和oauth-credentials.json的路径设置正确。第一次运行需要获取授权,之后每运行一次就会添加一个email到指定的 group里。

<?php
// 引入autoload.php,base.php仅定义获取密钥文件等函数,并非必须
include_once __DIR__ . '/google-api-php-client-2.1.3/vendor/autoload.php';
include_once "base.php";

// 定义在base.php的函数,显示页头标题
echo pageHeader("Add a member to google group");


// 检查密钥文件是否存在,密钥文件为oauth-credentials.json
if (!$oauth_credentials = getOAuthCredentialsFile()) {
	echo missingOAuth2CredentialsWarning();
	return;
}

// 设置当前页面为返回地址
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

// 初始化google client,设置密钥信息、scope和redirect uri(此地址需要在项目中设置)
$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/admin.directory.group");
$service = new Google_Service_Directory($client);


// 如需重新获取token,通过logout参数清空session
if (isset($_REQUEST['logout'])) {
	unset($_SESSION['group_access_token']);
	exIt;
}


// 用户点击同意授权,返回一个code,从code中获取token,存入session,再重定向到当前地址
if (isset($_GET['code'])) {
	$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
	$client->setAccessToken($token);

	$_SESSION['group_access_token'] = $token;

	// 返回原始地址,去掉参数,否则会导致invalid token错误
	header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
	exit;
}


// 如果session中存有token,存到$client中使用,如果没有,生成获取授权的链接并定向到该地址
if (!empty($_SESSION['group_access_token'])) {
	$client->setAccessToken($_SESSION['group_access_token']);
	if ($client->isAccessTokenExpired()) {
		unset($_SESSION['group_access_token']);
	}
} else {
	$authUrl = $client->createAuthUrl();
	header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}

if (!empty($_SESSION['group_access_token'])) {
	// 创建一个用户,添加到group中
	$email = 'testuser8@test.com';
	$memberInstance = new Google_Service_Directory_Member();
	$memberInstance->setEmail($email);
	$memberInstance->setRole('MEMBER');
	$memberInstance->setType('USER');

	try
	{
		$insertMembersResult = $service->members->insert('testgoogle@solagirl.net', $memberInstance);
		echo "$email is added to the group";
	}
	catch ( Google_Service_Exception $gioe)
	{
		echo "Error in connection: ".$gioe->getMessage();
	}
}
?>

<?php pageFooter(__FILE__) ?>

可能遇到的问题

Fatal error: Uncaught exception ‘GuzzleHttp\Exception\ConnectException’ with message ‘cURL error 7: Failed to connect to www.googleapis.com port 443: Timed out

解决方法:编辑windows/systems32下的host文件,添加记录172.217.5.106 www.googleapis.com,IP地址不一定是这个,请自己查询一下,参考了这里

Fatal error: Uncaught exception ‘GuzzleHttp\Exception\RequestException’ with message ‘cURL error 60: SSL certificate problem: unable to get local issuer certificate

解决方法:

  • https://curl.haxx.se/docs/caextract.html下载cacert.pem
  • 将cacert.pem放到D:\wamp\bin\php\php5.6.25\extras\ssl\cacert.pem,这是我本地wampserver的配置,请根据自己的安装调整路径
  • 修改php.ini,添加下面的代码并重启
    curl.cainfo ="D:\wamp\bin\php\php5.6.25\extras\ssl\cacert.pem"

参考地址:https://stackoverflow.com/questions/29822686/curl-error-60-ssl-certificate-unable-to-get-local-issuer-certificate

api中用到了scope,请看这里https://developers.google.com/admin-sdk/directory/v1/guides/authorizing