我想使用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%s\n", $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 %s\n", $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:{&#34;错误&#34;:{&#34;错误&#34;:[{&#34;域名&#34;:&#34;全球&#34;,& #34;原因&#34;:&#34;禁止&#34;,&#34;消息&#34;:&#34;未授权访问此资源/ api&#34; },&#34;代码&#34;:403,&#34;消息&#34;:&#34;未授权访问此资源/ api&#34; }}
答案 0 :(得分:0)
致命错误:未捕获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"
}
}
表示您要通过身份验证的用户无权访问管理员目录帐户
通过Directory API,您可以对帐户中的用户,群组,单位部门和设备执行管理操作。
解决方案:使用有权访问G套件帐户的用户登录。