在Google Apps脚本中使用Admin SDK Directory API创建组 - 错误403

时间:2014-06-24 18:42:32

标签: google-apps-script oauth-2.0 google-admin-sdk google-directory-api

我已经阅读了Admin ADK Directory API documentation中的所有相关页面以及有关stackoverflow的几个问题,我仍然被卡住了。

我正在尝试使用Google Apps脚本(Google表格的脚本编辑器中的容器绑定)来创建群组。我是Google Apps域的超级管理员,脚本将像我一样运行。

以下是我到目前为止在脚本编辑器中所做的事情:

  1. 去资源 - 高级Google服务...... - 打开了管理目录API

  2. 单击下面的链接以获取Google Developers Console并启用Admin SDK

  3. 使用我用来设置用户电子邮件签名的工作代码(改编自this blog post,并修改它以创建组:

    function createGroupTest() {
    
      var t = new Date();
      t = t.getTime();
    
      createGroup("AAA Test Group " + t, "aaa.testgroup." + t + "@mydomain.com" , "test@mydomain.com", "test");
    
    }
    
    function createGroup(groupName,groupEmail,owner,description) {
    
      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;
    
      var url = 'https://www.googleapis.com/admin/directory/v1/groups';
    
      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'};
    }
    
  4. 当我跑步时,我得到了这个回复:

    Request failed for returned code 403. Truncated server response: { "error": { "errors": [ { "domain": "usageLimits", "reason": "dailyLimitExceededUnreg", "message": "Daily Limit for Unauthentica... (use muteHttpExceptions option to examine full response) (line 60, file "Main")
    

    当我添加fetchArgs.muteHttpExceptions=true;时,错误输出更改为Failed to authenticate for service: Groups

1 个答案:

答案 0 :(得分:0)

想出来:

  1. 去资源 - 高级Google服务......
  2. 点击了Google Developers Console的链接
  3. 点击侧栏中的“凭据”部分
  4. 点击“在公共API访问下创建新密钥”
  5. 点击浏览器密钥
  6. 添加"?key ="然后是它生成到url字符串
  7. 末尾的密钥

    所以完整的url字符串看起来像这样:

    var url = 'https://www.googleapis.com/admin/directory/v1/groups?key=XXXXXXXXXXX-XXXXXXXXXXXXX-XXXXXXXXXXXXX';