Skip to content

Instantly share code, notes, and snippets.

@vinknee
Last active May 12, 2021 06:58
Show Gist options
  • Save vinknee/ef2a37657c6a46650f9bba6ac650698c to your computer and use it in GitHub Desktop.
Save vinknee/ef2a37657c6a46650f9bba6ac650698c to your computer and use it in GitHub Desktop.
Google Script to interact with MailChimp API v3.0
var API_KEY = 'XXXXXXX';
var API_USER = 'anystring';
var mc_list_id = 'XXXXX'; //List ID found in list settings
// Using adding members with custom signup forms in this example
var mc_base_url = 'https://us14.api.mailchimp.com/3.0/lists/' + mc_list_id + '/members';
//var mc_send = 'https://us14.api.mailchimp.com/3.0/automations/XXXX/emails/XXXXX/queue';
/**
* Used to convert email to MD5 hash to allow auto update of user information with MailChimp 3.0 API w/ PUT
*/
function sign(message){
message = message || "thisisteststring";
var signature = Utilities.computeDigest(
Utilities.DigestAlgorithm.MD5,
message,
Utilities.Charset.US_ASCII);
Logger.log(signature);
var signatureStr = '';
for (i = 0; i < signature.length; i++) {
var byte = signature[i];
if (byte < 0)
byte += 256;
var byteStr = byte.toString(16);
// Ensure we have 2 chars in our byte, pad with 0
if (byteStr.length == 1) byteStr = '0'+byteStr;
signatureStr += byteStr;
}
Logger.log(signatureStr);
return signatureStr;
}
/**
* Uses the MailChimp API to add a subscriber to a list.
*/
function sendToMailChimp_( em, src ) {
// format to add any custom merge tags, here i'm just pushing the source
var user = {
"SRC" : src
};
var payload = {
"merge_fields" : user,
"email_address": em,
"status" : "subscribed",
//"update_existing" : false // left the update_existing on this way existing emails
};
var headers = {
"content-type" : "application/json",
"Authorization" : " Basic " + Utilities.base64Encode(API_USER + ":" + API_KEY)
};
var options = {
"method": "put",
"headers" : headers,
"payload": JSON.stringify( payload ),
"followRedirects" : true,
"muteHttpExceptions": true,
};
Logger.log(mc_base_url);
Logger.log( options );
//var options = JSON.stringify( options ) );
var emailHash = sign( em ); //to use PUT command to auto-update existing subscribers
var response = UrlFetchApp.fetch(mc_base_url +"/"+emailHash , options );
if( response.getResponseCode() == 200 ) {
console.info( "SUCCESS to PROD for " + em );
} else {
console.log(response);
}
}
/**
* Trigger function. Based on Google Script tutorial.
* @param {Object} e The event parameter for form submission to a spreadsheet;
* see https://developers.google.com/apps-script/understanding_events
*/
function onFormSubmit(e) {
Logger.log( "hit the function" );
var email = e.namedValues['Email'][0];
var source = "EXAMPLE";
sendToMailChimp_( email, source ); //set initial person with no refby
}
/**
* Main function. Creates onFormSubmit trigger.
*/
function myFunction(){
var sheet = SpreadsheetApp.getActive();
var a = ScriptApp.newTrigger("onFormSubmit");
var b = a.forSpreadsheet(sheet);
var c = b.onFormSubmit();
var d = c.create();
}
@andrewSWNY
Copy link

Hey, Thanks for posting. This works perfectly to add a subscriber. However if I want to update a member or change the status to unsubscribe.

I get the following error response: "example@example.com is already a list member. Use PUT to insert or update list members."

And I'm using the method "put" as in your script.

Any suggestions?

Thanks in advance.

@naoswilbrink
Copy link

Really nice!
Wondering if I want to send a single email through mailchimp,... how can I add a subscriber to an automation with a dynamic text?

@naoswilbrink
Copy link

Like could you expand it with Transactional email in Mailchimp.
https://us8.api.mailchimp.com/3.0/automations/AUTOMATIONCODE/emails/EMAILINAUTOMATIONCODE/queue

@harshdoshi
Copy link

harshdoshi commented May 12, 2021

Hi! I'm writing one more time.

Your code works perfectly, but I am struggling to make it work for a onEdit instead of onFormSubmit.

Could you please assist?

Would really really appreciate it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment