As I begin this tutorial, it’s an early Saturday morning, and I mean early… like 4:12 A.M!

For whatever the reason, the good Lord saw to it that I should arise this day, and I’m grateful for that.

It’s not often that I’m up this early on a Saturday morning.

But hey, since I’m up, bright eyed and bushy tailed, I might as well crank out a tutorial, right?

Today’s tutorial is likely to make many of you quite happy.

There have been many requests over the last couple of years for tutorials about how to sync CCB profiles to newsletter services such as Constant Contact, Aweber, iContact and Mailchimp.

I’ve hesitated on whether or not to move down this path, because doing so can open a can of worms at times.

More specifically, email integration efforts can be stalled due to lack of or too complex API documentation, and lack of easily implemented workflows.

But on two separate phone calls this week, I had potential customers inquire about integrating their CCB account with Mailchimp.

And so it goes, the integrating CCB and Mailchimp tutorial has leap frogged quite a few other tutorials to make its debut here today. Let’s get started!

Mailchimp Account, List Id and API Credentials

Be sure to create a Mailchimp account if you haven’t already done so. If you have a Mailchimp account, then simply login.

There are a two items you’ll need for this tutorial, and they are as follows:

I’m choosing to use the Mailchimp API 3.0 although I will provide a completely different tutorial using the now deprecated versions 1.X and 2.X for those still successfully using previous versions.

But that’ll be a different day. For now, let’s move forward with Mailchimp API 3.0.

Once you have all of the items listed above, then crack open your text editor of choice.  It’s time to start coding.

With your list id and api key, create the following variables respectively: mcApikey and mcSubscriberList.

<?PHP
/*
	SYNCING CCB PROFILE DATA TO MAILCHIMP
	Simple tutorial to add and sync CCB profiles to a Mailchimp newsletter
*/

// Mailchimp Credentials
// set the Mailchimp API key - read About API Keys: http://kb.mailchimp.com/integrations/api-integrations/about-api-keys
$mcApiKey = 'enter api key';

// set the id of desired newsletter list 
$mcSubscriberList = 'enter list id';

?>

Next, identify the datacenter your Mailchimp account uses. The good news is that this info is the last part of the api key immediately following the hyphen or dash.

To retrieve the datacenter from the api key, create a mcDataCenter variable and set it to use PHP’s built-in explode method, passing it the hyphen or dash as the first argument and the mcApiKey variable as the second argument.

We’ve instructed the api key to be split or exploded into an array using the hyphen or dash.

Now follow up with another mcDataCenter variable and set it equal to to array indice numeral one: $mcDataCenter[1].

Last but not least, we’re now ready to prepare the Mailchimp API url (see below), appending the mcDataCenter variable.

<?PHP

// set the datacenter using the mcApiKey variable
$mcDataCenter = explode('-', $mcApiKey);
$mcDataCenter = $mcDataCenter[1];

// set the base API URL
$mcBaseAPIUrl = 'https://'.$mcDataCenter.'.api.mailchimp.com/3.0/';

?>

Time for CCB Profile Data

Now here’s where things get somewhat tricky.

I won’t go into the details of retrieving CCB profile data. Why? You already know… there’s a tutorial for it that exists. And if you didn’t know, now you know! 🙂

Should you use the tutorial above, it’s highly recommended that you figure out your CCB account’s daily API limit.

Integrating this tutorial with Mailchimp could cause your CCB account to max out API calls in a given day. But no worries, you can contact CCB directly to have it increased.

For automated or continuous syncing, I recommend using a cache or copy CCB profile data via database. It’s more efficient to use a database than accessing CCB directly, to say the least.

But moving on…

For this tutorial, I opted to hardcode user data to simplify the code a bit.

To subscribe a user to Mailchimp list, the bare minimum data needed is a person’s first name, last name and email address.  Create variables for each as shown below:

<?PHP

// set your CCB profile data to add person to newsletter list
$personEmail = 'test@ccbtutorials.com';
$personFName = 'Alvin';
$personLName = 'Brown';

?>

Does subscriber exist in Mailchimp list?

Now this is where the fun begins. One of the first items needed to make a Mailchimp API call is the targetUrl variable to check to see if a subscriber exists for the defined list.

It’s always a good habit to check this before blindly adding persons to a list. To do so, add the following line of code:

<?PHP

// let's check to see if person is subscribed
// person's email must be hashed via md5
$targetUrl = $mcBaseAPIUrl."lists/$mcSubscriberList/members/".md5($personEmail);

?>

Next, create a subscriberStatus variable and set it equal to Mailchimp function (to soon be discussed), passing get as the first argument and targetUrl as the second argument.

Like the ccbDetails function in previous tutorials, the Mailchimp function is a user-defined function created to act as a reusable wrapper to make GET, POST, PUT, and DELETE curl calls.

<?PHP

// make curl GET call using targetUrl
$subscriberStatus = Mailchimp('get', $targetUrl);

?>

Now that the Mailchimp API call was executed to check the status of the submitted subscriber, it’s time to decode and parse the response.

Define a responseData variable and set it use PHP’s built-in json_decode method, passing it subscriberStatus variable as first argument and true as second argument.

Next, set the addSubscriber variable to be equal to false. Do this because we’ll later check, using an if statement, to verify the variable exists before executing a few more lines of code.

After setting up addSubscriber, you’re now ready to use an if statement to verify whether or not the decoded json object contains a 404 status.

When checking whether or not a subscriber exists, a 404 status is returned when a record doesn’t exist for subscriber.

This is the status that will allow us to know the user needs to be added from CCB to Mailchimp list.

If a true response to the if statement status equals 404 status, then we’ll set addSubscriber variable to true.

<?PHP

// decode Mailchimp's json response object
$responseData = json_decode($subscriberStatus, true);

// ALWAYS start addSubscriber variable as false - no need to change
// check to see if the response data status is 404 (indicating person IS NOT subscribed).  
// if 404, then we want to subscribe the person by changing addSubscriber variable to true
$addSubscriber = false;

if($responseData['status'] == 404)
	$addSubscriber = true;

?>

Time to add subscribers to Mailchimp list

To begin with, set a subscriptionStatus variable to be the following:

<?PHP

$subscriptionStatus = $personFName.' '.$personLName.' was not added to list id: '.$mcSubscriberList.'.';

?>

Initially, it is assumed that a person will not be added to the mailing list. But don’t worry, because we’ll use and set the same variable later should a user be successfully added to list.

Next, create an if statement and pass it the addSubscriber variable.

This allows a subscriber to be added only if the addSubscriber variable exists with a value of true and not false.

<?PHP

// if addSubscriber is truen, then time to prep data for new subscription
if($addSubscriber){

}

?>

The subscriber data is now ready for json_encoding preparation. To do so, create a personData variable and set it equal to a multi-dimensional array containing first name, last name, email address and status (see below):

<?PHP

// if addSubscriber is truen, then time to prep data for new subscription
if($addSubscriber){

// time to prep an array for forced JSON object encoding
$personData = array (
    "email_address" => "$personEmail",
    "status" => "subscribed",
    "merge_fields" => array(
    	"FNAME" => "$personFName",
    	"LNAME" => "$personLName")
);

}

?>

Next, encode the person variable array as a json object, creating a subscriberData variable as shown below:

<?PHP

// if addSubscriber is truen, then time to prep data for new subscription
if($addSubscriber){

// time to prep an array for forced JSON object encoding
$personData = array (
    "email_address" => "$personEmail",
    "status" => "subscribed",
    "merge_fields" => array(
    	"FNAME" => "$personFName",
    	"LNAME" => "$personLName")
);

$subscriberData = json_encode($personData, JSON_FORCE_OBJECT);

?>

Now, just as we did in the previous section when checking whether or not a subscriber exists, create a targetUrl variable containing the Mailchimp API url to add the person as a member or subscriber to the Mailchimp list.

<?PHP

// if addSubscriber is truen, then time to prep data for new subscription
if($addSubscriber){

// time to prep an array for forced JSON object encoding
$personData = array (
    "email_address" => "$personEmail",
    "status" => "subscribed",
    "merge_fields" => array(
    	"FNAME" => "$personFName",
    	"LNAME" => "$personLName")
);

$subscriberData = json_encode($personData, JSON_FORCE_OBJECT);

// url for adding new member subscription
$targetUrl = $mcBaseAPIUrl."lists/$mcSubscriberList/members/";

?>

Set a responseData variable equal to the Mailchimp function, ensuring to pass post as the first argument, targetUrl as second argument, and subscriberData as the final argument.

<?PHP

// if addSubscriber is truen, then time to prep data for new subscription
if($addSubscriber){

// time to prep an array for forced JSON object encoding
$personData = array (
    "email_address" => "$personEmail",
    "status" => "subscribed",
    "merge_fields" => array(
    	"FNAME" => "$personFName",
    	"LNAME" => "$personLName")
);

$subscriberData = json_encode($personData, JSON_FORCE_OBJECT);

// url for adding new member subscription
$targetUrl = $mcBaseAPIUrl."lists/$mcSubscriberList/members/";

// make curl POST call passing targetUrl and json encoded object containing subscription data
$responseData = Mailchimp('post', $targetUrl, $subscriberData);

?>

Next, we’ll need to understand if the person was added to the list. To do so, set responseData variable equal to json_decode method, passing it responseData variable as first argument and true as second argument.

// if addSubscriber is truen, then time to prep data for new subscription
if($addSubscriber){

// time to prep an array for forced JSON object encoding
$personData = array (
    "email_address" => "$personEmail",
    "status" => "subscribed",
    "merge_fields" => array(
    	"FNAME" => "$personFName",
    	"LNAME" => "$personLName")
);

$subscriberData = json_encode($personData, JSON_FORCE_OBJECT);

// url for adding new member subscription
$targetUrl = $mcBaseAPIUrl."lists/$mcSubscriberList/members/";

// make curl POST call passing targetUrl and json encoded object containing subscription data
$responseData = Mailchimp('post', $targetUrl, $subscriberData);

// decode Mailchimp's json response object
$responseData = json_decode($responseData, true);

?>

Just we did with checking the subscriber status, set an if statement to verify the status. Only this time, instead of verifying equal to 404, your code needs to be NOT equal to 404 status.

Within the if statement verification, set the subscriptionStatus to be the following:

<?PHP

// if addSubscriber is truen, then time to prep data for new subscription
if($addSubscriber){

// time to prep an array for forced JSON object encoding
$personData = array (
    "email_address" => "$personEmail",
    "status" => "subscribed",
    "merge_fields" => array(
    	"FNAME" => "$personFName",
    	"LNAME" => "$personLName")
);

$subscriberData = json_encode($personData, JSON_FORCE_OBJECT);

// url for adding new member subscription
$targetUrl = $mcBaseAPIUrl."lists/$mcSubscriberList/members/";

// make curl POST call passing targetUrl and json encoded object containing subscription data
$responseData = Mailchimp('post', $targetUrl, $subscriberData);

// decode Mailchimp's json response object
$responseData = json_decode($responseData, true);

if($responseData['status'] != 404)
	$subscriptionStatus = $personFName.' '.$personLName.' was added to list id: '.$mcSubscriberList.'.';

}

echo $subscriptionStatus;

?>

Now close the addSubscriber if statement, echo the subscriptionStatus variable, and it’s time to test your technical prowess. 🙂

Time to put everything together and test

Okay, so here’s what everything looks like together.

<?PHP
/*
	SYNCING CCB PROFILE DATA TO MAILCHIMP
	Simple tutorial to add and sync CCB profiles to a Mailchimp newsletter
*/

// Mailchimp Credentials
// set the Mailchimp API key - read About API Keys: http://kb.mailchimp.com/integrations/api-integrations/about-api-keys
$mcApiKey = 'enter api key';

// set the id of desired newsletter list 
$mcSubscriberList = 'enter list id';

// set the datacenter using the mcApiKey variable
$mcDataCenter = explode('-', $mcApiKey);
$mcDataCenter = $mcDataCenter[1];

// set the base API URL
$mcBaseAPIUrl = 'https://'.$mcDataCenter.'.api.mailchimp.com/3.0/';

// set your CCB profile data to add person to newsletter list
$personEmail = 'test@ccbtutorials.com';
$personFName = 'Alvin';
$personLName = 'Brown';

// let's check to see if person is subscribed
// person's email must be hashed via md5
$targetUrl = $mcBaseAPIUrl."lists/$mcSubscriberList/members/".md5($personEmail);

// make curl GET call using targetUrl
$subscriberStatus = Mailchimp('get', $targetUrl);

// decode Mailchimp's json response object
$responseData = json_decode($subscriberStatus, true);

// ALWAYS start addSubscriber variable as false - no need to change
// check to see if the response data status is 404 (indicating person IS NOT subscribed).  
// if 404, then we want to subscribe the person by changing addSubscriber variable to true
$addSubscriber = false;

if($responseData['status'] == 404)
	$addSubscriber = true;

$subscriptionStatus = $personFName.' '.$personLName.' was not added to list id: '.$mcSubscriberList.'.';

// if addSubscriber is truen, then time to prep data for new subscription
if($addSubscriber){

// time to prep an array for forced JSON object encoding
$personData = array (
    "email_address" => "$personEmail",
    "status" => "subscribed",
    "merge_fields" => array(
    	"FNAME" => "$personFName",
    	"LNAME" => "$personLName")
);

$subscriberData = json_encode($personData, JSON_FORCE_OBJECT);

// url for adding new member subscription
$targetUrl = $mcBaseAPIUrl."lists/$mcSubscriberList/members/";

// make curl POST call passing targetUrl and json encoded object containing subscription data
$responseData = Mailchimp('post', $targetUrl, $subscriberData);

// decode Mailchimp's json response object
$responseData = json_decode($responseData, true);

if($responseData['status'] != 404)
	$subscriptionStatus = $personFName.' '.$personLName.' was added to list id: '.$mcSubscriberList.'.';

}

echo $subscriptionStatus;

?>

Save and name your php file, fire up a web browser, and execute your php file.

Don’t forget to login to your Mailchimp account to verify the list.

Also, I didn’t include the Mailchimp function in the code below only because it should be included in the general.php file developed in previous tutorials.

Oh yeah, and with a bit of reading and elbow grease using previous tutorials, you could very well reverse the process and go from retrieving Mailchimp list subscribers and creating/update CCB profiles. Just a thought to round out this process… 😉

Enjoy and let me know if you have questions. See you around…

Mailchimp Function

Include this function inside the general.php file developed and discussed in previous tutorials.  Also, don’t forget to include the general.php file within your code above should you include this function.

<?PHP

/**************************************************************
** FUNCTIONS
**************************************************************/

function Mailchimp($type,$targetUrl,$personData=NULL){

// set global variables
global $mcApiKey, $mcBaseAPIUrl;

// set error checking of global variables. if any are empty, die on the spot and display error message to web browser
if (!$mcApiKey || !$mcBaseAPIUrl) die('Error: Mailchimp API details missing.');

$apiUrl = $targetUrl;
 
$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "username:$mcApiKey");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2); 
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

if($type == 'post'){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $personData);
}

if($type == 'put'){
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($personData)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $personData);
}

$contents = curl_exec($ch);

if(!$contents){
	$contents =  'Error: '.curl_error($ch);
}
 
curl_close($ch);
 
return $contents;

}

?>

 

Related Posts

Subscribe and receive the following...

  • Inside CCB tips and tricks
  • Instant CCB tutorial alerts and updates
  • CCB How To's, Videos, Webinars and more...