function runDemo() {
  try {
    var firstProfile = getFirstProfile();
    var results = getReportDataForProfile(firstProfile);
    outputToSpreadsheet(results);
  } catch(error) {
    Browser.msgBox(error.message);
  }
}
function getFirstProfile() {  
  var accounts = Analytics.Management.Accounts.list();
  if (accounts.getItems()) {
    var firstAccountId = accounts.getItems()[0].getId();
    var webProperties = Analytics.Management.Webproperties.list(firstAccountId);
    if (webProperties.getItems()) {
      var firstWebPropertyId = webProperties.getItems()[0].getId();
      var profiles = Analytics.Management.Profiles.list(firstAccountId, firstWebPropertyId);
      if (profiles.getItems()) {
        var firstProfile = profiles.getItems()[0];
        return firstProfile;
      } else {
        throw new Error('No profiles found.');
      }
    } else {
      throw new Error('No webproperties found.');
    }
  } else {
    throw new Error('No accounts found.');
  }
}
function getReportDataForProfile(firstProfile) {
  var profileId = firstProfile.getId();
  var tableId = 'ga:' + profileId;
  var startDate = getLastNdays(2);   
  var endDate = getLastNdays(0);      
  var optArgs = {
    'dimensions': 'ga:date,ga:medium,ga:source,ga:campaign',        
    'sort': '-ga:date',
    'start-index': '1',
    'max-results': '10000'
  };
  // Make a request to the API.
  var results = Analytics.Data.Ga.get(
      tableId,                 
      startDate,               
      endDate,                  
    'ga:visits,ga:transactions,ga:transactionRevenue', 
      optArgs);
  if (results.getRows()) {
    return results;
  } else {
    throw new Error('No profiles found');
  }
}
function getLastNdays(nDaysAgo) {
  var today = new Date(); 
  var before = new Date();
  before.setDate(today.getDate() - nDaysAgo);
  return Utilities.formatDate(before, 'GMT', 'yyyy-MM-dd');
}
function outputToSpreadsheet(results) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();
  // Print the headers.
  var headerNames = [];
  for (var i = 0, header; header = results.getColumnHeaders()[i]; ++i) {
    headerNames.push(header.getName());
  }
  sheet.getRange(1, 1, 1, headerNames.length)
      .setValues([headerNames]);
  // Print the rows of data.
  sheet.getRange(2, 1, results.getRows().length, headerNames.length)
      .setValues(results.getRows());
}