Mailchimp CURL PHP Integration: A PHP Integration Using The Mailchimp API & CURL

In this example, I’m going to show you how to integrate your PHP website with Mailchimp. Specifically, how to create an HTML form that accepts a person’s information, automatically sends it to Mailchimp, and adds a subscriber to your email list. Let’s get started.

How The Integration Example Flows

At Menyu (our startup), our actual Mailchimp integration flows as follows:

  1. The user enters their information into an HTML form and clicks Join.
  2. A JavaScript function sends off the form data to a PHP script via AJAX.
  3. The PHP script:
    1. Checks for errors, including empty fields.
    2. Stores the information in an email subscriber table in our MySql database.
    3. Builds a JSON string using the fields from our form.
    4. Uses CURL to connect and send our data (as JSON) to Mailchimp’s API endpoint.
    5. Sends a welcome email to our newest newsletter subscriber.

Our Integration Example

Above is how the Mailchimp API integration flows on our site. However, so we can focus on the Mailchimp integration piece, we’ve removed some of these steps. Notably, steps 3.1 and 3.2 above have been removed.

Additionally, I assume you already have a Mailchimp account. If you don’t, swing over to https://mailchimp.com and signup for one. At the time of this article, your first 2,000 email subscribers are free, so no reason not to.

Get Your Mailchimp API Key

  1. Login to your Mailchimp account.
  2. Click on your Account name in the top right corner.
  3. From the dropdown, select Profile.

    In Mailchimp, Click Your Account Name and Then Select Profile
  4. From your Profile page, select Extras -> Api Keys.

    Select Extras, API Keys to View Your API Keys or Create New API Keys
  5. Click the Create a Key button.

    Click Create a Key Button to Create Mailchimp API Key for use in PHP
  6. A new API key will be generated. The value itself will be in the API Key column.
  7. Copy this key, as it is the key we’ll use in our PHP script.

Get Your Mailchimp List ID

  1. Once logged in to your Mailchimp account, click on the Audience link at the top middle of your screen.
  2. On the far-right, select from the Mange Audience dropdown the Settings option.

    In Mailchimp, Select Audience, Manage Audience, Settings
  3. Scroll to the bottom of your screen. You will see the Unique ID for your list. This is your List ID.

    List ID in Mail Chimp
  4. Copy this ID as we will use it in our PHP script.

That’s It From Mailchimp

Those are the only two pieces of information we need from Mailchimp. With our API Key and List ID, we’re now ready to put on our coding hats and dig into the integration code. Let’s get started with our simple HTML form to capture the user’s information, including email.

PHP Curl Request to MailChimp API Endpoint to Add Subscribers

The HTML


<form id='joinList'>
	<input type='text' maxlength='30' name='name' placeholder='first & last name' />
	<input type='text' maxlength='30' name='street' placeholder='street' />
	<input type='text' maxlength='30' name='city' placeholder='city' />

	<select name='state'>
		<option value='XX'>--select state--</option>
                <?php
		$cFilter = DB::getConnection();
		$sFilter = "SELECT stAbbr FROM states ORDER BY stAbbr";
		if ($rFilter = mysqli_prepare($cFilter,$sFilter)) {	
			mysqli_stmt_execute($rFilter); 
			mysqli_stmt_bind_result($rFilter,$fState);
			while (mysqli_stmt_fetch($rFilter)) {
				echo "<option value='$fState'>".getStateName($fState)."</option>";
			}
		}
		$cFilter->close();
		?>
	</select>

	<input type='text' maxlength='5' name='zip' placeholder='5 digit zip' />
	<input type='text' maxlength='50' name='email' placeholder='email' />
	<button type='button' name='join' id='join' onclick='joinList();'>Join</button>	
												

Nothing earth shattering here. We have a simple HTML form. When the form’s button is clicked, we call a JavaScript function named joinList(). We’ll explain the joinList() function in a minute.

You’ll notice in the HTML some PHP and MySQLi to loop through a database table that holds state abbreviations. As it loops through the table, it calls a function to get the state name. This is how we populate our “state” select control. It really has nothing to do with the Mailchimp API, so if its confusing, just ignore it.

The JavaScript

Below is the JavaScript to handle our form submission. It uses jQuery and AJAX. Remember, this function gets executed when someone clicks the Join button.

<script>
	function joinList(){
		
		$('#join').prop('disabled', true); // disable the join button
		
		var myform = $("#joinList")[0];
		var fd = new FormData(myform);
						
		$.ajax({
			data: fd,
			cache: false,
			processData: false,
			contentType: false,
			url: "ajax/ajaxJoinList.php",
			type: "post",
			success: function(data){
				// show form error or success
				$('#join').prop('disabled', false); // enable the join button
			}
		});
	}
</script>

It begins by disabling the form’s button so a user can’t click it multiple times. It then collects the data entered into the form and sends it off via the POST method to a PHP script in the ajax directory named ajaxJoinList.php. On successful return from the PHP script, we reenable the form’s button.

We won’t go into detail here as the logic is straight forward. Like the HTML form above, this code doesn’t integrate with Mailchimp. Rather, it makes the call to the script that does. Without further ado, let’s dig into the meat and potatoes of our Mailchimp integration – ajaxJoinList.php.

The PHP, CURL, and Mailchimp Integration

Below is the PHP script that will integrate our custom HTML form with our Mailchimp email list that we looked at earlier (when getting our List ID).

<?php

if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) {
	die(""); // invalid email format
}

$apiKey = "api key from mailchimp"; // from mailchimp
$listID = "list id from mailchimp"; // list id from Menyu email list

/* form variables */

$name   = $_POST['name'];
$street = $_POST['street'];
$city   = $_POST['city'];
$state  = $_POST['state'];
$zip    = $_POST['zip'];
$email  = $_POST['email'];

// check post fields for errors, such as not being filled in

/***************************************************************
 * Programatically add info to our email list in mailchimp
 ***************************************************************/
 
 $names      = explode(' ', $name, 2); // i.e. Jim L Ross = [0] Jim [1] L Ross
 $memberID   = md5(strtolower($email));
 $dataCenter = substr($apiKey,strpos($apiKey,'-')+1); 
 $url        = "https://".$dataCenter.'.api.mailchimp.com/3.0/lists/'.$listID.'/members/'.$memberID; // mailchimp api endpoint

 $json = json_encode([
 	'email_address' => $email,
 	'status' => 'subscribed',
 	'merge_fields' => [
 		'EMAIL' => $email,
 		'FNAME' => $names[0],
 		'LNAME' => $names[1],
 		'STREET' => $street,
 		'CITY' => $city,
 		'STATE' => $state,
 		'ZIP' => $zip
 	]
 ]);

 $ch = curl_init($url);

 curl_setopt($ch, CURLOPT_USERPWD, 'user:'.$apiKey);
 curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

 $cresult = curl_exec($ch);

/************************************
 * welcome the new member
 *************************************/

$to      = "$email";
$subject = 'Email Title';
$message = "Email body / subject";
$headers = 'From: info@yoursite.com'."\r\n"."X-Mailer: PHP/".phpversion();
	
mail($to, $subject, $message, $headers); // send the welcome email
										
?>

Lines 3 – 5

Checking for a valid email format.

Line 7

Where we need to paste our Mailchimp API Key that we copied above.

Line 8

Our List ID that we copied above.

Lines 12 – 17

Assigning our form values to variables.

Line 25

Exploding the name field from the form into first name and last name. This is because our list in Mailchimp as them separate. We simply assume if a space is in the field, the user entered a first and last name.

Line 26

Sets the member ID to the entered email address. This will be the unique ID in Mailchimp for that list entry / row. This will prevent duplicate emails from being on our email list.

Line 27

Mailchimp requires the datacenter when calling their API. The datacenter is appended to the end of our API Key in the format xxxx-xx where -xx is the data center (key and datacenter is longer in reality). This line simply splices off the datacenter from the end of the API Key.

Line 28

Here, we assemble the correct Mailchimp API endpoint (URL) to later connect to using CURL. As you can see, we include the datacenter, List ID, and Member ID.

Lines 30 – 42

If we only wanted email address for each entry in our email list, we could simply use CURL to connect to the API endpoint above and it would work. However, we want each entry to have First Name, Last Name, Email, Street, City, State, and Zip Code. Because of this, we need to find a way to pass all this information to the URL above.

That’s what these lines do. They build a JSON string by assembling a PHP array with our data. The lines then pass the array into the json_encode function which translates the PHP arrays into a valid JSON string. In the JSON, we assign email_address, status, and merge_fields.

Notice the merge_fields – these are fields setup in Mailchimp to allow passing data into your list. Mailchimp comes with many fields already setup. If you need to add fields or view your existing ones, login to your Mailchimp account, navigate to your List (Audience), and go to Settings -> Audience Fields and *|MERGE|* tags. You can see ours below.

Mailchimp Merge Fields are used for passing data into your subscriber list

Lines 44 – 54

In these lines, we use CURL to connect to the Mailchimp API, pass our data to it, and actually add a subscriber to our email list. I won’t explain each line, rather point out some key takeaways. We use CURL to set our Content-Type header to JSON. We set our POST fields for the CURL request to the JSON data we built earlier from our form fields. We use the PUT method to push our data to Mailchimp. On line 54 we execute the CURL request and add the subscriber to our list.

Lines 60 – 65

These lines simply send an email to the newly subscribed member.

Conclusion

Using the code above, with some minor tweaks for your environment, you can have your custom PHP website fully integrated with Mailchimp in a matter of minutes. People will be automatically subscribed to your email lists, saving you hours of manually keying in contacts. Best of all, you get all the list-management features Mailchimp has to offer. Enjoy.

100% of Email Subscribers Added From PHP Integration / API


'Mailchimp CURL PHP Integration: A PHP Integration Using The Mailchimp API & CURL' has no comments

Be the first to comment this post!

Would you like to share your thoughts?

Your email address will not be published.

Menyu LLC
© 2019 - 2020