GithubHelp home page GithubHelp logo

pratik0809 / gsheetstomailchimp Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 1.0 2 KB

A script written for Google Sheets that allows you to send edits on your spreadsheet to Mailchimp merge fields instantly.

JavaScript 100.00%

gsheetstomailchimp's Introduction

Google Sheets to Mailchimp

GSheetsToMC is a script written for Google Sheets that allows you to send edits on your spreadsheet to Mailchimp merge fields instantly. In this case, this script was written to accomodate my on-campus organization's needs (UNICEF at Illinois Tech).

At UNICEF, we use a point system to keep track of members' volunteering hours, attendance, and eligibility for prizes. This point system is updated via a private spreadsheet on Google Drive accessible only to our executive board. We also use Mailchimp for our weekly newsletters and heavily rely on merge fields to update each member about their points. The biggest problem was the lack of synchronization between Mailchimp and Google Sheets (no, we weren't interested in paying Zapier to automate the task). We often forgot to re-import the spreadsheet and thus, received complaints about outdated points from our members.

The spreadsheet's layout is as follows:

First Name Last Name Email Total Points Event 1 Event 2 More Events
Pratik Sampat [email protected] 5 2 3 0

Resources

gsheetstomailchimp's People

Contributors

pratik0809 avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Forkers

yujinchung

gsheetstomailchimp's Issues

Everything seems to work but... no record is updated

Trying your function, it seems to solve a lot of time with API documentation. Anyway I read it and it made it work... but no update occurs on Mailchimp list.

Execution console from Google shots "Complete" (so success when executing the functions).
I had to move from onEdit to its own function name and trigger it with onEdit trigger.

And at Mailchimp latest API calls messages are always:
Result: Ok
Throtteld: --
Response: n/a

I don't know if it's because field format, but I tried just updating one single value and it doesn't get updated in mailchimp list.

Any clue about what could be wrong? Script is like this now:

function sendToMailChimp(id_customer,id_shop,id_gender,fn,ln,em,optin,date_add,last_order,num_pedidos,aov,good_experience){
var API_KEY = '3e61f4b01ca32c8258117d22b971fb82-us10';
var mc_base_url = 'https://us10.api.mailchimp.com/3.0';
var mc_list_id = '3ad825a38e';

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('');
//Header of PUT request
var headers = {
'Authorization': 'Basic ' + Utilities.base64Encode('username' + ':' + API_KEY, Utilities.Charset.UTF_8),

};

//MailChimp API requires MD5 hash of email to identify a subscriber
function md5(str) {
    return Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, str).reduce(function(str,chr){
    chr = (chr < 0 ? chr + 256 : chr).toString(16);
    return str + (chr.length==1?'0':'') + chr;
    },'');
}
var emHash = md5(em.toString().toLowerCase());

//Body of PUT request
var payload =  JSON.stringify({ 
  "status_if_new": "subscribed", 
  "email_address": em,
  "merge_fields": {
    "id_customer": id_customer,
    "id_shop": id_shop,
    "id_gender": id_gender,
    "optin": optin
  }
});

//put the above variables together into 'options'
var options = {
"headers" : headers,
"payload": payload,
"method" : "put",
"muteHttpExceptions" : true
};
//PUT request to specific subscriber in Mailchimp
var response = UrlFetchApp.fetch(mc_base_url + '/lists/' + mc_list_id + '/members/' + emHash,options);
if( response.getResponseCode() == 200 ) {
console.info( "SUCCESS to PROD for " + em + payload);
} else {
console.log(response);
}
}

/**

  • onEdit Trigger Function
    */
    function actualiza_usuario(e) {
    var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var range = e.range;
    //gets Index value of row which contains edited cell (e.g. cell A60 was edited, rowedited = 60)
    var rowedited = range.getRowIndex();
    //if edited sheet is not "Points", die. else continue
    if (activeSheet.getName() !== "Mailchimp"){
    return;
    Logger.log("Oops :(");
    }
    else {
    //capture value of first name, last name, email, and points specifically of the row that was edited
    var values = activeSheet.getRange(rowedited, 1, 1, 12).getValues()[0];
    //separate values variable
    var id_customer = values[0];
    var id_shop = values[1];
    var id_gender = values[2];
    var fn = values[3];
    var ln = values[4];
    var em = values[5];
    var optin = values[6];
    var date_add = values[7];
    var last_order = values[8];
    var num_pedidos = values[9];
    var aov = values[10];
    var good_experience = values[11];
    sendToMailChimp(id_customer,id_shop,id_gender,fn,ln,em,optin,date_add,last_order,num_pedidos,aov,good_experience);
    Logger.log("Enviado");
    }
    }

"Invalid Resource","status":400,"detail":"Blank email address","instance

I keep receiving this error in the execution logs when I edit a cell in my sheet. I'm not sure what I need to fix, as I do have all the variables properly aligned. Checked all over stackoverflow and my question on SO hasn't been getting responses.

Here are my vars for the mailchimp function:

var payload =  JSON.stringify({ 
"status_if_new": "subscribed", 
"email_address": email,
"merge_fields": {
    "LEAD": lead,
    "LATECOUNT": latecount,
    "CALLOFFCNT": calloffcnt,
    "WFHCNT": wfhcnt,
    "WFHOCCUR": wfhoccur,
    "WFHREMAIN": wfhremain,
    "ANNCALLOFF": anncalloff,
    "OCCURTOTAL": occurtotal,
    "USEDPTO": usedpto,
    "USEDSICK": usedsick,
    "PTOREMAIN": ptoremain,
    "SICKREMAIN": sickremain
}
});

And then this is the cadence for the the google sheet part:

else {
  //capture values specifically of the row that was edited
  var values = sheet.getRange(rowedited, 1, 1, 13).getValues()[0];
  //separate values variable
   var em = values[2];
   var email = values[2]
   var lead = values[1];
   var latecount = values[6];
   var calloffcnt = values[7];
   var wfhcnt = values[8];
   var wfhoccur = values[9];
   var wfhremain = values[10];
   var anncalloff = values[11];
   var occurtotal = values[21];
   var usedpto = values[22];
   var usedsick = values[23];
   var ptoremain = values[24];
   var sickremain = values[25];      
  sendToMailChimp_(em,email,lead,latecount,calloffcnt,wfhcnt,wfhoccur,wfhremain,anncalloff,occurtotal,usedpto,usedsick,ptoremain,sickremain);

I have the email variable twice because I was trying to find if there was a conflict with the email and subscriber hash, but anyway way I run it, I still get the blank email error.

Cannot read property "source" (line 59, file "Code")

Thank you for posting the script - it's exactly what we were looking for!

When adding the mailchimp details and trying to run the script I get:

ERR: TypeError: Cannot read property "source" from undefined. (line 59, file "Code")

On this line:
var activeSheet = e.source.getActiveSheet();

Am I missing something?

Many thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.