title: google script editor mailchimp - fetch segment subscriber
body: <p>I'm currently trying to fetch mailchimp data for the total amount of subscribers within a predefined auto updating segment within our subscriber list into Google sheets using the script editor. However, I must confess I'm not very knowledgeable in this area and have tried various ways of customizing this code with no luck. I have looked at Mailchimps documentation regarding this but still cannot seem to get this work.</p>
  
  <pre><code>function chimpSubscribers() {
  var API_KEY = ''; // MailChimp API Key
  var LIST_ID = ''; // MailChimp List ID
  var SEGMENT_ID =''; //Mailchimp Segment ID
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Subscribers");
  
  var dc = API_KEY.split('-')[1];
  var api = 'https://'+ dc +'.api.mailchimp.com/3.0';
  
    var memberList = '/lists/'+LIST_ID
    var memberSegment = '/segments/'+SEGMENT_ID
      var apiCall = function(endpoint){
      options = {"headers": {"authorization": 'apikey '+API_KEY}};
          apiResponseMembers = UrlFetchApp.fetch(api+endpoint,options);
          json = JSON.parse(apiResponseMembers);
          return json
      }
  
  var members = apiCall ("memberList", "memberSegment");
  if (members) {
  
    var d = new Date();
    var member_count = members.stats.member_count;
    var unsubscribe_count = members.stats.unsubscribe_count;
    var open_rate = members.stats.open_rate;
    var click_rate = members.stats.click_rate;
  
    var report = [d, member_count, unsubscribe_count, open_rate, click_rate,];
  
  Logger.log(report);
  
  // Clear MailChimp data in Spreadsheet
     sheet.clear();
  // Append MailChimp data to Spreadsheet
     sheet.appendRow(["Date", "Total Subscribers", "Unsubscribe Count", "Open Rate", "Click Rate"]);
     sheet.appendRow(report);
   }  
  }
  </code></pre>