1

如何将新用户添加到 Google 日历的 ACL?我正在尝试发送一个 POST HTTP 请求。也许 XML 有问题?下面的代码会生成服务器错误 (400)。(编辑:显示 oAuth)。

//---------------------------------------------------------------
// Add a rule to the Access Control List for 'Fake Calendar 1.0'
//---------------------------------------------------------------
function addRule() {
  // Get Calendar ID, script user's email, and the API Key for access to Calendar API
  var calId = '12345calendar.google.com';
  var userEmail = Session.getActiveUser().getEmail();
  var API_KEY = 'ABC123';
  var newUserEmail = 'person@example.net';

  // Get authorization to access the Google Calendar API
  var apiName = 'calendar';
  var scope = 'https://www.googleapis.com/auth/calendar';
  var fetchArgs = googleOAuth_(apiName, scope);

  fetchArgs.method = 'POST';
  var rawXML = "<entry xmlns='http://www.w3.org/2005/Atom' " +
               "xmlns:gAcl='http://schemas.google.com/acl/2007'>" +
               "<category scheme='http://schemas.google.com/g/2005#kind' " +
               "term='http://schemas.google.com/acl/2007#accessRule'/>" +
               "<gAcl:role value='owner'/>" +
               "<gAcl:scope type='user' value='"+userEmail+"'/>" +
               "</entry>";

  fetchArgs.payload = rawXML;
  fetchArgs.contentType = 'application/atom+xml';

  // Get the requested content (the ACL for the calendar)
  var base = 'https://www.googleapis.com/calendar/v3/calendars/';
  var url = base + calId + '/acl?key=' + API_KEY;
  var content = UrlFetchApp.fetch(url, fetchArgs).getContentText();
  Logger.log(content);
}

//--------------------------------------------------------------
// Google OAuth 
//--------------------------------------------------------------
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("anonymous");
  oAuthConfig.setConsumerSecret("anonymous");
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}
4

2 回答 2

0

在执行这段代码之前,您是否经过了 oAuth 授权过程。您的应用必须先获得明确授权,然后才能使用 Calendar API 执行任何重要操作

于 2012-07-27T03:11:05.037 回答
0

斯里克是对的。您需要在 UrlFetchApp 中使用 oAuth 参数。给定的参考 URL 显示了一些在 Apps 脚本中使用 oAuth 以使用 Google 的 REST API 的示例 https://sites.google.com/site/appsscripttutorial/urlfetch-and-oauth

于 2012-07-27T05:57:44.197 回答