Mailchimp Batch Operation | Salesforce – Mailchimp Integration | Mailchimp REST API

3

MailChimp Batch Operation: We can use this batch operation in the MailChimp API to complete more than one operation in just a single call. Let’s take an example where you need to subscribe and unsubscribe the records. In the simple API call, you have to do separate call to make the single record to subscribe and unsubscribe in the MailChimp list this may exceed your API call out limit. The batch operation runs in the background on the MailChimp server and does the more than one action in just a single API call. After callout, we can check the batch status.

Scenario: There is a field on Contact records ‘Email Opt Out’, whenever user update the field to uncheck subscribe 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/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s