从Google Apps脚本访问Salesforce时使用OAuth2 401 INVALID_SESSION_ID

时间:2018-07-31 15:57:10

标签: google-apps-script oauth-2.0 salesforce

我已成功将Google Apps脚本认证为Salesforce,并且可以使用gsuitedevs中的以下内容通过Google Apps脚本查询Salesforce中的记录:

function run() {
  var service = getService();
  if (service.hasAccess()) {
    Logger.log("Success.");
    var url = service.getToken().instance_url +
        '/services/data/v24.0/chatter/users/me';
    // Make the HTTP request using a wrapper function that handles expired
    // sessions.
    var response = withRetry(service, function() {
      return UrlFetchApp.fetch(url, {
        headers: {
          Authorization: 'Bearer ' + service.getAccessToken(),
        }
      });
    });
    var result = JSON.parse(response.getContentText());
    Logger.log(JSON.stringify(result, null, 2));
  } else {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log('Open the following URL and re-run the script: %s',
        authorizationUrl);
  }
}

但是,当我运行以下代码时,我得到了401:

function updateQuoteUrls3() {
  var service = getService();
  var accessToken = service.getAccessToken();
  var quoteId = "a1Gf200000GkZex"; // ID
  var folderUrl = "https://drive.google.com/drive/folders/DEFXXX";  // Google_Drive_Folde_URL__c
  var sheetUrl = "https://docs.google.com/spreadsheets/d/XXX";
  var instanceUrl = "https://na53.salesforce.com";
  var queryUrl = "/services/data/v25.0/sobjects/i360__Quote__c/" + quoteId + ".json";
  var payload = {
    "Google_Drive_Folde_URL__c": folderUrl,
    "Pricing_Sheet_URL__c": sheetUrl
  };
  var headers = {
    Authorization: 'Bearer ' + service.getAccessToken(),

    "Content-Type": "application/json"
  };
  var options = {
    "method": "patch",
    "contentType": "application/json",
    "headers": headers,
    "payload": JSON.stringify(payload)
  };
  var url = instanceUrl + queryUrl;
  var response = UrlFetchApp.fetch(url, options);
  return response; // HTTPresponse - https://developers.google.com/apps-script/reference/url-fetch/http-response
}
我无法弄清楚为什么出现以下错误:
returned code 401. Truncated server response: [{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}] (use muteHttpExceptions option to examine full response)

这是我的新手,已经搜索了几个小时,但到目前为止还没有提出任何建议。非常感谢您的帮助。

0 个答案:

没有答案