我正在尝试在Gsuite for Education上根据自己的脚本自动创建电子邮件地址。
我已经尝试了所有https://developers.google.com/admin-sdk/directory/v1/reference/users/insert?authuser=4#try-it
如果我通过上面的链接在线尝试,它将被创建。但是当我尝试使用自己的代码时,
<?php
$post_fields = json_encode(array(
'name' =>array('familyName'=>'Dan', 'givenName'=>'Foster'),
'password' => '1234567890',
'primaryEmail' => 'dan.foster@domain.com',
'agreedToTerms' => false,
'isMailboxSetup' => false
));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.googleapis.com/admin/directory/v1/users?key=[ASCCESS_key]",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $post_fields,
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Authorization: Bearer [AUTHENTICATION TOKEN]",
"Content-Type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo $err;
} else {
echo $response;
}
?>
执行后出现以下错误
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
由于我的帐户是管理员并且该代码是从后端执行的,因此如何绕过OAuth登录。
***更新
我终于开始工作了
putenv('GOOGLE_APPLICATION_CREDENTIALS='.dirname(__FILE__).'/google/credentials.json');
$client = new Google_Client();
$client->setSubject($this->adminEmail);
$client->setScopes(Google_Service_Directory::ADMIN_DIRECTORY_USER);
$client->setAccessType('offline');
$client->useApplicationDefaultCredentials();
return $client;