我已經閱讀了管理員ADK Directory API documentation中的所有相關頁面以及有關stackoverflow的幾個問題,並且我仍然卡住。在Google Apps腳本中創建一個包含Admin SDK Directory API的組不起作用「在表單提交中」
我是我的Google Apps域的超級用戶,我希望我的域中的用戶能夠創建自己的Google網上論壇。我製作了一個Google表單,供用戶指定該組的名稱和電子郵件。然後,Google表單響應表格中會有一個「表單提交」觸發器,用於調用我的代碼來創建組。
此代碼適用於從腳本編輯器運行createGroupTest()
。它立即在我的Google應用程序域中創建該組。
此代碼不是當「On form submit」觸發器運行onFormSubmit(e)
函數時工作。我從catch(e)
得到的電子郵件說Exception: Failed to authenticate for service: Groups
。
有誰知道是什麼導致oauth身份驗證工作從腳本編輯器內工作,但不是由onFormSubmit函數調用時?
function createGroupTest() {
var t = new Date();
t = t.getTime();
createGroup("AAA Test Group " + t,"aaa.testgroup." + t + "@mydomain.com","[email protected]");
}
var consumerKey="mydomain.com";
var consumerSecret="xxxxxxxxxxxxxxxxxxxxxxxx";
var domainName="mydomain.com";
function onFormSubmit(e) {
try {
var timestamp = e.values[0];
var groupName = e.values[1];
var groupEmail = e.values[2];
var owner = e.values[3];
createGroup(groupName,groupEmail,owner);
var recipient = "[email protected]";
var body = 'Group created! '+ groupName;
var subject = groupName + " Email Group Created";
var advancedArgs = {htmlBody:body , replyTo:email};
MailApp.sendEmail(recipient, subject, body, advancedArgs);
} catch(e) {
MailApp.sendEmail("[email protected]", "Error processing Create New Email Distribution Group form submit", e);
}
}
function createGroup(groupName,groupEmail,owner) {
owner = owner.split("@")[0];
var description = 'test';
var requestBody = '{"email": "'+groupEmail+'","name": "'+groupName+'","description": "'+description+'"}';
var scope="https://www.googleapis.com/auth/admin.directory.group";
var fetchArgs = googleOAuth_("Groups",scope);
fetchArgs.method = "POST";
fetchArgs.contentType = "application/json";
fetchArgs.payload = requestBody;
fetchArgs.muteHttpExceptions=true;
var url = 'https://www.googleapis.com/admin/directory/v1/groups?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
UrlFetchApp.fetch(url, fetchArgs);
}
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name)
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey(consumerKey);
oAuthConfig.setConsumerSecret(consumerSecret);
return {oAuthServiceName:name, oAuthUseToken:'always'};
}