Salesforce Integration with Mailchimp using oAuth 2.0

Salesforce Integration with Mailchimp using oAuth 2.0
Salesforce Integration with Mailchimp using oAuth 2.0

Today, I will tell you how to integrate Salesforce with Mailchimp using oAuth2.0 flow. In this post, I will show you only to fetch the Access token so that you can use it in your further HttpRequest.

Mailchimp’s access token doesn’t expire so there is no need to perform any kind of refresh of Access Token.

Notice that we have implemented lightning:isUrlAddressable interface so that we can access component using the URL directly. And we will use this URL as a redirect uri.

Use below Aura Controller and Apex class to know how to integrate it.

Follow this tutorial to register an app and get Client ID and Client Secret https://mailchimp.com/developer/guides/how-to-use-oauth2/

Aura Component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction,lightning:isUrlAddressable" 
                access="global"
                controller = "oAuthConnection">
    <aura:attribute name="accessToken" type="String" />
    <aura:handler name='init' value='{!this}' action='{!c.doInit}' />
    <div class = 'slds-grid slds-wrap slds-align_absolute-center' style="background-color:white;height:15rem;width:25rem;">
        <div class = 'slds-col slds-size_12-of-12 slds-align_absolute-center'>
            <lightning:button variant="brand" label="Connect To MailChimp" title="Base action" onclick="{! c.handleClick }"/><br></br>
        </div>
        <div class = 'slds-align_absolute-center'>
            Access Token is : {!v.accessToken}
        </div>
    </div>
</aura:component>
Controller:
({	
    doInit : function(component, event, helper) {
    	helper.doInit(component, event, helper);
    },
	handleClick : function(component, event, helper) {
		helper.handleClick(component, event, helper);
	}
})
Helper:
({
    doInit : function(component,Event,helper){
        var myPageRef = component.get("v.pageReference");
        var code = myPageRef.state.code;
        var url = window.location.href;
        if(code!=null && code.trim().length!=null && code!=undefined){
            var action=component.get("c.doFetchAccessToken");
            action.setParams({
                'code' : code,
                'redirectUri' : url.substr(0, url.indexOf('?'))
            });
            action.setCallback(this, function(response){
                var state =response.getState();
                if(state==='SUCCESS'){
                    var res = response.getReturnValue();
                    component.set('v.accessToken',res);
                }
            });
            $A.enqueueAction(action);
        }
    },
    handleClick : function(component, event, helper) {
        var action=component.get("c.connectToMailchimp");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state =response.getState();
            if(state==='SUCCESS'){
                var res = response.getReturnValue();
                //console.log('URL FOR Mailchimp LOGIN-'+res.url);
                if(res.Error === undefined) {
                    console.log('Mailchimp Login Started');
                    window.open(res.url, '_top');
                }
                else if (res.Error != undefined && res.Error != null){
                    
                }
            } else if (state === 'ERROR'){
                console.log('Mailchimp Login Failed: ERROR');
            }
        });
        $A.enqueueAction(action);
    }
    
})

When Connect to Mailchimp button is clicked we will create a URL in the apex class and send it back to the javascript controller, you can make the client id and client secret dynamic by fetching it from Custom Settings or Metadata.

When user login on the Mailchimp after clicking on Connect to Mailchimp button, the user will be redirected back to the component with the CODE parameter in the URL. We will then send the CODE value to the apex class and using HttpRequest we fetch the Access Token.

You can further store this Access Token and can do Httprequest to the Mailchimp endpoints.

Apex Controller:
public class oAuthConnection {
    public static String clientId = <YOUR CLIENT ID>;
    public static String clientSecret = <>;   
    @AuraEnabled
    public static Map<String, String> connectToMailchimp () {
        Map<String, String> returnMap = new Map<String, String>();
        try{
            
            String redirectURI = '<YOUR LIGHTNING URL>/lightning/cmp/c__oAuthComponent';
            String url= 'https://login.mailchimp.com/oauth2/authorize';
            url+='?response_type=code&client_id='+clientId+'&redirect_uri='+ EncodingUtil.urlEncode(redirectURI, 'UTF-8');
            returnMap.put('url',url);
        } catch(Exception ex) {
            system.debug('Exception Error');
            system.debug(ex.getLineNumber()+':'+ex.getMessage()+':'+ex.getCause());
            returnMap.put('Error','Exception error while generating url'+'Line:'+ex.getLineNumber()+':Message '+ex.getMessage()+': Cause '+ex.getCause());
        }
        return returnMap;
    }   
    @AuraEnabled
    public static String doFetchAccessToken(String code, String redirectUri){
               
        String getTokenEndpoint = 'https://login.mailchimp.com/oauth2/token';
        String oAuthCode = code;
        String requestBody = 'grant_type=authorization_code&client_id='+clientId+'&client_secret='+clientSecret+'&redirect_uri='+EncodingUtil.urlEncode(redirectUri, 'UTF-8')+'&code='+code;
        String errorMessage ='';
        HttpRequest httpReq = new HttpRequest();
        HttpResponse httpRes = new HttpResponse();
        Http http = new Http();
        httpReq.setMethod('POST');
        httpReq.setEndPoint(getTokenEndpoint);
        httpReq.setBody(requestBody);
        
        try{
            httpRes = http.send(httpReq);
            
            if(httpRes.getStatusCode() == 200){
                Map<String, Object> response_Map = (Map<String, Object>)JSON.deserializeUntyped(httpRes.getBody());
                system.debug('response: '+httpRes.getBody());
                return String.valueOf(response_Map.get('access_token'));
            }else{
                system.debug('Unexpected Error with Mailchimp API'+
                             'Status '+httpRes.getStatus()+' and Status Code '+httpRes.getStatuscode());
            }
        }catch(System.Exception e){
            if(String.valueOf(e.getMessage()).startsWith('Unauthorized endpoint')){
                errorMessage = 'Unauthorize endpoint'
                    +'Goto Remote Site Setting and add '+' '+ getTokenEndpoint +' Endpoint';
                system.debug( errorMessage);
                //return null;
            }else{
                errorMessage = 'Unexpected Error'
                    +'Status '+httpRes.getStatus()+' and Status Code '+httpRes.getStatuscode();
                system.debug(errorMessage);
                //return null;
            }
        }
        return httpRes.getBody();
    }
}

Now, Remember to add remote site https://login.mailchimp.com/oauth2/token in the Remote Site Settings.

If you have any issue integrating Mailchimp or you want to extend this integration further Chat with me, I will be more than happy to assist you.

Support: For any kind of further Salesforce support, Chat with us we will be happy to assist you.

Popular Post:

Reference: Mailchimp oAuth2.0

Getting Started with the Mailchimp API

You may also like...

Want to know more about Salesforce Devlopments?

We keep your data private and share your data only with third parties that make this service possible. Read our Privacy Policy.

Holler Box