Created
December 6, 2018 07:40
-
-
Save emmaly/505bf87037020eab1db8a83f02eafea5 to your computer and use it in GitHub Desktop.
Google Form Apps Script to create new subscriber in MailChimp via API including GDPR opt-in
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// make sure you have added an event trigger for OnFormSubmit to run the onFormSubmit() function or this won't even run | |
var APIKEY = "1234567890abcdef1234567890abcdef-us11"; // your MailChimp API key | |
var LISTID = "ababababab"; // hint: not an integer | |
var GDPRID = "cdcdcdcdcd"; // hint: this seems to be unique per list, so you'll have to find this yourself | |
var FORMSHEETNAME = "Form Responses 1"; // your Google Sheets target sheet name (this is the likely name if you didn't change it) | |
var EMAILCOLUMN = 6; // the column number (1=first) that contains the email field name | |
var XTRAPARTCOLUMN = 5; // the column number (1=first) that contains the field name for whatever you want this field to be | |
var XTRAPARTNAME = "XTRAPART"; // the merge field name of the extra field you're storing in (you have to make this yourself; it's here as an example of how you might populate a custom field) | |
var BASEURL = "https://"+APIKEY.match(/-(.+)$/)[1]+".api.mailchimp.com/3.0"; | |
var FORMSHEET = SpreadsheetApp.getActive().getSheetByName(FORMSHEETNAME); | |
var EMAILFIELDNAME = FORMSHEET.getRange(1, EMAILCOLUMN).getValue(); | |
var XTRAPARTFIELDNAME = FORMSHEET.getRange(1, XTRAPARTCOLUMN).getValue(); | |
function addSubscriber(email, xtrapart) { | |
if (!email) return; | |
var url = BASEURL+"/lists/"+LISTID+"/members"; | |
var merge_fields = {}; | |
merge_fields[XTRAPARTNAME] = xtrapart || ""; | |
var result = UrlFetchApp.fetch(url, { | |
muteHttpExceptions: true, | |
headers: {"Authorization": "Basic " + Utilities.base64Encode(LISTID+":"+APIKEY)}, | |
method: "post", | |
contentType: "application/json; charset=utf-8", | |
payload: JSON.stringify({ | |
email_address: email, | |
status: "subscribed", | |
merge_fields: merge_fields, | |
marketing_permissions: [{ | |
marketing_permission_id: GDPRID, // GDPR Email Opt-in | |
enabled: true, | |
}], | |
}), | |
}); | |
Logger.log(result); | |
} | |
function onFormSubmit(e) { | |
Logger.log(e.namedValues); | |
var email = e.namedValues[EMAILFIELDNAME] ? e.namedValues[EMAILFIELDNAME][0] : ""; | |
var xtrapart = e.namedValues[XTRAPARTFIELDNAME] ? e.namedValues[XTRAPARTFIELDNAME][0] : ""; | |
if (!email) return; | |
addSubscriber(email, xtrapart); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment