在google Admin SDK中使用google app脚本自动创建用户



我想在谷歌自动创建用户作为一个管理员,我使用应用程序脚本做到这一点,但从我正在阅读的文档我不太确定如果我这样做是正确的,因为我在我的代码中得到一些错误,如后POST和脚本不工作

function createUsers() {
const userjson = {
"primaryEmail": "atest@example.com",
"name": {
"givenName": "afirstName",
"familyName": "alastName"
},
"suspended": false,
"password": "pass2022",
"hashFunction": "SHA-1",
"changePasswordAtNextLogin": true,
"ipWhitelisted": false,
"orgUnitPath": "myOrgPath",
};
const optionalArgs = {
customer: 'my_customer',
orderBy: 'email'
};
POST https://admin.googleapis.com/admin/directory/v1/users
try {
const response = AdminDirectory.Users.list(optionalArgs);
const users = response.users;
//check if user exists
if (!users || users.length === 0) 
//create new user
return AdminDirectory.newUser(userjson);
// Print user exists
Logger.log('User Existing');

} catch (err) {
// TODO (developer)- Handle exception from the Directory API
Logger.log('Failed with error %s', err.message);
}
}

根据官方文档,如果你想用Google Apps Script做这件事,你应该格式化你的代码如下:

function createUsers() {
const userInfo = {
"primaryEmail": "jvd@domain.com",
"name": {
"givenName": "Jackie",
"familyName": "VanDamme"
},
"suspended": false,
"password": "thisisasupersecret",
"changePasswordAtNextLogin": true,
"ipWhitelisted": false
};
try{
AdminDirectory.Users.insert(userInfo);
console.log("User added");
} catch(error){
const {code, message} = error.details;
if(code === 409 && message === "Entity already exists."){
console.log("User already exists");
} else {
console.log(`${code} - ${message}`);
}
}  
}

如果您对如何使用用户资源负载有任何疑问,请参考REST API的官方文档。

最新更新