admin管理员组

文章数量:1357702

I have the following Google AppScript script trying to populate a Google Sheet wiht a list of projects from Zoho Projects, using the Zoho Projects API, but authoritization with OAuth2 doesn't appear to be working. service.hasAccess() is returning false every time.

Any help greatly appreciated.

/**
 * Retrieves a list of projects from Zoho Projects using OAuth 2.0.
 */
function getZohoProjectsOAuth() {
  var service = getZohoService();
    if (service.hasAccess()) {
    var accessToken = service.getAccessToken();
    var url = '/' + portalId + '/projects/?index=1&range=3';
    var headers = headers_opt || {};
    headers['Authorization'] =
        Utilities.formatString('Bearer %s', accessToken);
    var resp = UrlFetchApp.fetch(url, {
      'headers': headers,
      //'method' : method,
      'muteHttpExceptions': true, // Prevents thrown HTTP exceptions.
    })

    var json = JSON.parse(response.getContentText());

    Logger.log(JSON.stringify(json, null, 2)); // Log the entire JSON response

    if (json.projects) {
      processProjects(json.projects);
      //Logger.log("Success");
    } else {
      Logger.log("Error: " + JSON.stringify(json));
    }
  } else {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log('Authorize the script: ' + authorizationUrl);
    //SpreadsheetApp.getUi().alert('Authorize the script: ' + authorizationUrl);
  }
}


/**
 * Creates the OAuth 2.0 service.
 */
function getZohoService() {
  return OAuth2.createService('ZohoProjects')
    .setAuthorizationBaseUrl('')
    .setTokenUrl('')
    .setClientId(PropertiesService.getScriptProperties().getProperty('ZOHO_CLIENT_ID'))
    .setClientSecret(PropertiesService.getScriptProperties().getProperty('ZOHO_CLIENT_SECRET'))
    .setCallbackFunction('authCallback')
    .setPropertyStore(PropertiesService.getUserProperties())
    .setCache(CacheService.getUserCache())
    .setScope('ZohoProjects.projects.READ') // Adjust scope as needed.
    .setParam('access_type', 'offline'); // For refresh tokens
}

/**
 * Callback function for OAuth 2.0 authorization.
 */
function authCallback(request) {
  var service = getZohoService();
  var authorized = service.handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput('Success!');
  } else {
    return HtmlService.createHtmlOutput('Denied');
  }
}

/**
 * Processes the retrieved projects and populates the sheet.
 */
function processProjects(projects) {
  if (projects && projects.length > 0) { // Check if projects exists and is not empty
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('ZohoProjects');
    if (!sheet) {
      sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet('ZohoProjects');
    }

    var headers = Object.keys(projects[0]);
    sheet.appendRow(headers);

    projects.forEach(function(project) {
      var row = headers.map(function(header) {
        return project[header];
      });
      sheet.appendRow(row);
    });
  } else {
    Logger.log('No projects found or projects array is empty.');
    SpreadsheetApp.getUi().alert('No projects found or projects array is empty.');
  }
}

/**
 * Sets up Script Properties for OAuth 2.0 credentials.
 */
function setupZohoOAuthProperties() {
  var clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // Zoho Client ID.
  var clientSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // Zoho Client Secret.
  var portalId = 'xxxxxxxxxx'; // Zoho Portal ID.
  
  PropertiesService.getScriptProperties().setProperty('ZOHO_CLIENT_ID', clientId);
  PropertiesService.getScriptProperties().setProperty('ZOHO_CLIENT_SECRET', clientSecret);
  PropertiesService.getScriptProperties().setProperty('ZOHO_PROJECTS_PORTAL_ID', portalId);

  Logger.log('OAuth 2.0 Script Properties set up.');
}

I know the API keys work because I've tested it with Postman, but I've run out of things to try.

本文标签: Google AppScript failing with Zoho Projects APIStack Overflow