Integrate your MailChimp Newsletter Subscription

MailChimp is a great mailing list provider with a great control panel and many useful features like: campaign management, statistics, responders and complete set of List management tools. They offer also an small code snippet to place a subscription form on your website. This form powered by jQuery is good enough for most common cases, but what if you like to combine your newsletter subscription with a standard function like contact or registration form?

The secret to make your list bigger is to integrate the opt-in function with often used functions like a registration or contact form.

In our tutorial we showcase how-to create a contact form application which will send a message and subscribes the user to a mailing list hosted by MailChimp.

Preparations

The contact form (html)

We need to have a simple contact form, with a field for name and e-mail address, a textarea for the message and a checkbox for the subscription. The following example is very basic for a better understanding. In real you might to use some Ajax/jQuery powered form (check the jQuery form plugin listed below).

<form action="process.php" method="post">
	<div>
		<label for="name">Name</label>
		<input type="text" value="" name="name" />
	</div>
	<div>
		<label for="email">E-mail</label>
		<input type="text" value="" name="email" />
	</div>
	<div>
		<label for="message">Message</label>
		<textarea name="message" cols="30" rows="4"></textarea>
	</div>
	<div>
		<input type="checkbox" value="yes" name="newsletter" />
		<label for="newsletter">Subscribe to newsletter</label>
	</div>
	<div>
		<input type="submit" value="Register" name="subscribe" />
	</div>
</form>

Using the MailChimp API with cURL

The MailChimp API has several modes on how-to communicate with the system. In this tutorial we use the simple HTTP GET/POST URL method. We request the data using cURL functions and we like to have a response which is a JSON array.

$apikey = 'Your API Key';
$listID = 'Your List';
$url = sprintf('http://api.mailchimp.com/1.2/?method=listSubscribe&apikey=%s&id=%s&email_address=%s&merge_vars[OPTINIP]=%s&merge_vars[MMERGE1]=webdev_tutorials&output=json', $apikey, $listID, $email, $_SERVER['REMOTE_ADDR']);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch); ID';

You can see that we created a string using the PHP function sprintf to add our variables. You need to use at least one merge variable, in this example we submit the users IP and a value for the custom field we created before. After the cURL request is done we get a response called $data, the JSON array.

This so far about the communication. Before we submit any data we need to check if the submitted email address is valid. I the email address is valid we send the message.

	if (preg_match("(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,})", $_POST['email'])) {
		$email = $_POST['email'];
		//
		// process here the contact form data like name and message
		mail('your@mail.com', 'Subject: contact form', $_POST['message']); // example
		//

Note this is just an e-mail example, nothing special because how-to create a safe contact or mail form is not part of this tutorial. We posted a few resources at the end from this article.

Putting all stuff together

After the e-mail address is validated and the message is send we check if the checkbox was checked to send the data to the MailChimp API. Here is the complete script for the file process.php.

<?php
$apikey = 'Your API Key';
$listID = 'Your List';
 
if (isset($_POST['subscribe'])) {
	if (preg_match("(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,})", $_POST['email'])) {
		$email = $_POST['email'];
		//
		// process here the contact form data like name and message
		mail('your@mail.com', 'Subject: contact form', $_POST['message']); // example
		//
		if (!empty($_POST['newsletter'])) {
			$url = sprintf('http://api.mailchimp.com/1.2/?method=listSubscribe&apikey=%s&id=%s&email_address=%s&merge_vars[OPTINIP]=%s&merge_vars[MMERGE1]=webdev_tutorials&output=json', $apikey, $listID, $email, $_SERVER['REMOTE_ADDR']);
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$data = curl_exec($ch);
			curl_close($ch);
			$arr = json_decode($data, true);
			if ($arr == 1) {
				echo 'Check now your e-mail and confirm your subsciption.';
			} else {
				switch ($arr['code']) {
					case 214:
					echo 'You are already subscribed.';
					break;
					// check the MailChimp API for more options
					default:
					echo 'Unkown error...';
					break;			
				}
			}
		}
	}
}
?>

We’re using the PHP function json_decode to convert the JSON array into a PHP array and echo different messages upon the result. We used the most common results:

Using the API this way it’s possible to have your own (translated) messages. If you like to use more different messages for different response codes, just add them into the switch statement.

Additional resources

 

Related posts

Comments

Trackback URL for this post: http://www.web-development-blog.com/archives/integrate-your-mailchimp-newsletter-subscription/trackback/

Thanks for providing this tutorial. Using your example, I created a form where people take part of some promotion.
They enter their email address and just need to check the box if they like to join our mailing list.

I created two functions:

First I added the record to my database and send an email message about the promotion. Next I send the subscription to MailChimp.

Works great, the frequency for new subscriptions went up for 600%

Sorry, the comment form is closed at this time.