Mailchimp Batch Operation | Salesforce ~ Mailchimp Integration

MailChimp API allows batch operations to perform multiple functions in a single call, potentially reducing the risk of exceeding your API call-out limit. This is useful in scenarios such as subscribing and unsubscribing from records simultaneously. The batch operation runs on the MailChimp server, and its status may be checked after the callout.

MailChimp Batch Operation: We can use the MailChimp API’s batch operation to complete multiple operations in a single call. Consider the case where you need to subscribe and unsubscribe to records. You must make a separate call in the simple API call to make the single record to subscribe and unsubscribe in the MailChimp list, which may exceed your API call-out limit. The batch operation runs in the background on the MailChimp server, performing multiple actions in a single API call. We can check the batch status after the callout.

Scenario: On Contact records, there is an ‘Email Opt Out’ field that is updated whenever the user unchecks subscribe to the record in the MailChimp list and vice versa.

MCSubscribeUnsubscribeTrg

/* Name:MCSubscribeUnsubscribeTrg
* Description: On contact record insert/update subscribe/unsubscribe member in Mailchimp list.
* Created Date: 05/05/2019
* Last ModifiedDate : 05/05/2019
* Created By: Arun Kumar
*/
trigger MCSubscribeUnsubscribeTrg on Contact (after insert, after update) {
if(trigger.isAfter && trigger.isUpdate){
system.debug('Contact Email has Opted Out: ');
set<string> contactEmailSet=new set<string>();
for(contact co:trigger.new){
if(co.HasOptedOutOfEmail==true && co.email!=null){
contactEmailSet.add(co.email+'|false');
}
if(co.HasOptedOutOfEmail==false && co.email!=null){
contactEmailSet.add(co.email+'|true');
}
}
system.debug('Contact Email has Opted Out: '+contactEmailSet);
if(contactEmailSet.size()>0){
if (System.isFuture() || System.isBatch()){ // If Trigger initiated through future and Batch Process,
}
else{
MCSubscribeUnsubscribeHelper.doSubscribeUnsubscribe(contactEmailSet);
}
}
}
}

MCSubscribeUnsubscribeHelper

public class MCSubscribeUnsubscribeHelper {
@future(callout=true) // make callout in future method
//Future mehtod called by trigger to subscribe/unsubscribe the member from mailchimp list.
public static void doSubscribeUnsubscribe(Set<string> conEmail){ //
//Get member ids in MD5 format
map<string,string> emailMemberIdMap=new map<string,string>();
map<string,boolean> emailBolMap = new map<string,boolean>();
for(string str:conEmail){ // iterate over set of email ids.
String emailStr = str.substringBefore('|');
//email into blob
Blob targetBlob = Blob.valueOf(emailStr);
Blob hash = Crypto.generateDigest('MD5', targetBlob);
String requestSignature = EncodingUtil.convertToHex(hash);
system.debug('MD5 '+requestSignature);
Boolean bool = Boolean.valueOf(str.substringAfter('|'));
emailBolMap.put(emailStr, bool);
emailMemberIdMap.put(emailStr,requestSignature);
}
string api_Key = 'ee6c451ec8c6057034568e7435dbxxxx-usxx'; // put your actual Mailchimp API key
String mailChimpListId = 'f37ef2xxxx'; // put your Mailchimp list id
Http h = new Http();
HttpRequest req = new HttpRequest();
string endPointValue ='https://usxx.api.mailchimp.com/3.0/batches&#39;; // replace usxx = your mailchimp datacenter name
req.setEndpoint(endPointValue);
req.setHeader('Authorization', 'apikey '+api_Key);
req.setHeader('content-type', 'application/json');
//req.setHeader('X-HTTP-Method-Override','PATCH');
req.setMethod('POST');
string requestBody;
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeFieldName('operations');
//Start Array
gen.writeStartArray();
for(string str:emailMemberIdMap.keyset()){
system.debug('Email: '+str);
system.debug('Member Id: '+emailMemberIdMap.get(str));
//Start object
gen.writeStartObject();
gen.writeStringField('method','PUT');
gen.writeStringField('path','lists/'+mailChimpListId+'/members/'+emailMemberIdMap.get(str));
string stringBody;
if(emailBolMap.get(str)==true){
stringBody='{\"email_address\":\"'+str+'\",\"status\":\"subscribed\"}'; //JSON string for subscribe
}else{
stringBody='{\"email_address\":\"'+str+'\",\"status\":\"unsubscribed\"}'; //JSON string for unsubscribe
}
gen.writeStringField('body',stringBody);
//End object
gen.writeEndObject();
//end object
}
//End Array
gen.writeEndArray();
//End Object
gen.writeEndObject();
String jsonBody = gen.getAsString();
system.debug('Json string: #### '+jsonBody );
req.setBody(jsonBody);
HttpResponse res;
try{
//send request
res = h.send(req);
}
catch(Exception e){
system.debug('Exception has Occured !'+ e.getMessage());
}
system.debug('response returned: '+res.getBody());
}
}

Happy Coding…

Reference:

https://developer.mailchimp.com/documentation/mailchimp/reference/batches/

https://developer.mailchimp.com/

Arun Kumar
Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

Articles: 162

Leave a Reply

Discover more from SFDC Lessons

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from SFDC Lessons

Subscribe now to keep reading and get access to the full archive.

Continue reading