title: Get and post data from Google Spreadshets via Google Script
body: <p>I'm developing HTML5 app and I want to read/write some data from/to Google Spreadsheets.</p>
  
  <p><strong>Attempt 1. Pure JavaScript</strong></p>
  
  <p>I tried to call a webservice situated in .gs file on Google Script.</p>
  
  <pre><code>gapi.auth.signIn({
      'clientid' : 'MY_CLIENT_ID',
      'cookiepolicy' : 'single_host_origin',
      'callback' : 'loginCallback',
      'scope' : 'https://www.googleapis.com/auth/plus.me https://spreadsheets.google.com/feeds'
  });
  
  $.get('https://script.google.com/macros/s/APP_CODE/exec');
  </code></pre>
  
  <p>This only works for one .gs script. For another .gs script I get error "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'domainname.xx' is therefore not allowed access." According to Google API documentation it's not allowed to call functions in .gs files remotely with AJAX. How to make them work?</p>
  
  <p><strong>Attempt 2. PHP application as proxy</strong></p>
  
  <p>I managed to authenticate with Google using OAuth 2 but how to send GET/POST requests as authenticated user? Can I access functions in .gs files or spreadsheets directly?</p>
  
  <pre><code>// OAuth getting the token - works fine
  $params['client_id'] = self::OAUTH_CLIENT_ID;
  $params['response_type'] = 'code';
  $params['scope'] = self::OAUTH_SCOPE;
  $params['redirect_uri'] = self::OAUTH_REDIRECT_URI;
  $this-&gt;response-&gt;redirect('https://accounts.google.com/o/oauth2/auth?'.  http_build_query($params));
  
  // OAuth exchange tokens - works fine
  $fp = fsockopen('ssl://www.googleapis.com', 443, $errno, $errstr, 30);
  $postData['code'] = $_GET['code'];
  $postData['redirect_uri'] = self::OAUTH_REDIRECT_URI;
  $postData['client_id'] = self::OAUTH_CLIENT_ID;
  $postData['client_secret'] = self::OAUTH_CLIENT_SECRET;
  $postData['scope'] = '';
  $postData['grant_type'] = 'authorization_code';
  $postContent = http_build_query($postData);
  
  $out  = "POST /oauth2/v3/token HTTP/1.0\r\n";
  $out .= "Host: www.googleapis.com\r\n";
  $out .= 'Content-length: '.strlen($postContent)."\r\n";
  $out .= "Content-Type: application/x-www-form-urlencoded\r\n\r\n";
  $out .= $postContent;
  
  fwrite($fp, $out);
  $response = strstr(fread($fp, 4096), '{');
  </code></pre>
  
  <p>How to call doGet() and doPost() functions from .gs files as authenticated user? If it's impossible, how to read and write to spreadsheets on Google Drive?</p>