如何使用带有PHP的Google API创建Gmail业务用户帐户



我想使用 PHP 在 gmail 中创建一个新的gmail 企业用户帐户。 当我运行此代码时,它将显示一些消息,例如带有 URL 的Open the following link in your browser:并要求提供验证码。如果我在浏览器中运行链接,它将生成一些随机字符串。当我将随机字符串粘贴到终端中进行验证时,我收到403 错误。这是我的代码。

<?php
require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:n%sn", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %sn", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}

我的错误

致命错误:未捕获Google_Service_Exception:{ "错误": { "错误":[ { "域": "全局", "原因": "禁止", "消息": "无权访问此资源/api" } ], "代码":

403, "消息": "无权访问此资源/api" } }

致命错误:未捕获Google_Service_Exception:

{  
"error":{  
"errors":[  
{  
"domain":"global",
"reason":"forbidden",
"message":"Not Authorized to access this resource/api"
}
],
"code":403,
"message":"Not Authorized to access this resource/api"
}
}

表示您进行身份验证的用户无权访问管理员目录帐户

借助目录 API,您可以对帐号中的用户、群组、单位部门和设备执行管理操作。

解决方案:使用有权访问 G Suite 帐号的用户登录。

最新更新