title: Upload to Google Cloud storage from App Script
body: <p>I've been bashing my head at this for over a day, but I can't figure out how to upload data to Google Cloud Storage via an app script attached to a google sheet. I've been running into issues with authorisation. I've copied the <code>getService</code> method from <a href="https://www.labnol.org/code/20074-upload-files-to-google-cloud-storage" rel="nofollow noreferrer">here</a> (pasted below) but the service keeps failing to receive authorisation. <code>service.hasAccess()</code> always returns false.</p>
  
  <pre><code>function uploadFileToGCS(dataJSON) {
  
    var service = getService();
    if (!service.hasAccess()) {
      Browser.msgBox("Failed to grant service access")
      return;
    }
  
    var url = 'https://www.googleapis.com/upload/storage/v1/b/BUCKET/o?uploadType=media&amp;name=FILE'
      .replace("BUCKET", params.BUCKET_NAME)
      .replace("FILE", encodeURIComponent(params.FILE_PATH));
  
    var response = UrlFetchApp.fetch(url, {
      method: "POST",
      payload: dataJSON,
      contentType: "application/json",
      headers: {
        Authorization: 'Bearer ' + service.getAccessToken()
      }
    });
  
    var result = JSON.parse(response.getContentText());
    Logger.log(JSON.stringify(result, null, 2));
  }
  
  function getService() {
    return OAuth2.createService('ctrlq')
      .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setClientId(params.CLIENT_ID)
      .setClientSecret(params.CLIENT_SECRET)
      .setCallbackFunction('authCallback')
      .setPropertyStore(PropertiesService.getUserProperties())
      .setScope('https://www.googleapis.com/auth/devstorage.read_write')
      .setParam('access_type', 'offline')
      .setParam('approval_prompt', 'force')
      .setParam('login_hint', Session.getActiveUser().getEmail());
  }
  
  function authCallback(request) {
    var service = getService();
    var authorized = service.handleCallback(request);
    if (authorized) {
      return HtmlService.createHtmlOutput('Connected to Google Cloud Storage');
    } else {
      return HtmlService.createHtmlOutput('Access Denied');
    }
  }
  </code></pre>
  
  <p>I've created OAUTH credentials for a web-app on the Google Cloud Console. I've also enabled the  Cloud Storage API and Google Cloud Storage JSON API. I'm unsure however on the redirect URL. (Ideally, I'd like to use a service account because I just want to take the values from the spreadsheet and upload them as a JSON file.)</p>
  
  <p>Anyway, appreciate the help!</p>