oshliaer / google-apps-script-snippets

Google Apps Script snippets
https://apps-script-snippets.contributor.pw
The Unlicense
245 stars 46 forks source link

Use cookies #10

Open oshliaer opened 7 years ago

oshliaer commented 7 years ago

Cookie handling in Google Apps Script - How to send cookies in header?

function example() {

  Logger.log(getContacts());

}

// Some API
function getContacts() {

  auth();

  var headers = {
    'Cookie': CacheService.getUserCache().get('auth')
  };
  var params = {
    'headers': headers,
    muteHttpExceptions: true
  };
  return UrlFetchApp.fetch( /* API URL */ , params);

}

// Auth flow
function auth() {

  var cache = CacheService.getUserCache().get('auth');
  if (!cache)
    auth_();

}

function auth_() {

  var params = {};
  params.method = 'post';
  params.payload = {
    LOGIN: 'USER LOGIN',
    PWD: 'USER PASSWORD'
  };
  var fetch = UrlFetchApp.fetch( /* API URL */ , params);

  CacheService.getUserCache().put('auth', fetch.getAllHeaders()['Set-Cookie'], /* IF IT EXPIRES */ );

  return fetch;

}
frontangel commented 5 years ago

work!

oshliaer commented 5 years ago

I'm so glad that this helps.