PHP API for Mailchimp Integration

Guys these days mailchimp is the most popular online email marketing solution to send email. So here is the script how to integrate mailchimp using PHP API.

Step 1: Create a HTML Form

<div>
<h3>Subscribe to our newsletter</h3>
<form method=”post”>
<input type=”text” name=”email” placeholder=”yourname@email.com” >
<input type=”submit” value=”Send”>
</form>
<br />
<p></p>
</div>

Step 2: Submit your Form Using Ajax or You can submit with normal form submit method. Here I am going to submit with ajax.


<script type=”text/javascript”>
$(“.newsletter form”).submit(function (event) {
event.preventDefault();
var loc2 = window.location;
var currentURL = loc2.protocol + ‘//’ + loc2.host;
var HTTP_PATH = currentURL;
var postData = $(this).serialize();
var status = $(“.newsletter p”);
status.removeClass(‘shake’);
$.ajax({
type: “POST”,
url: HTTP_PATH+”subscription.php”,
data: postData,
success: function(data) {
if (data == “success”)
status.html(“Thanks for your interest! We will let you know.”).slideDown();

else if (data == “subscribed”)
status.toggleClass(‘shake’).html(“This email is already subscribed.”).slideDown();

else if (data == “invalid”)
status.toggleClass(‘shake’).html(“This email is invalid.”).slideDown();

else
status.toggleClass(‘shake’).html(“Oups, something went wrong!”).slideDown();

},
error: function () {
status.toggleClass(‘shake’).html(“Oups, something went wrong!”).slideDown();
}
});
});
</script>

step 3: Create A Subscription.php file

require_once(‘MCAPI.class.php’);
extract($_POST);

$api_key = ‘YOUR MC API KEY’;
$listid = ‘YOUR MC LIST ID’;
// Get your API key from http://admin.mailchimp.com/account/api/

define(‘MC_API_KEY’, $api_key);

// Get your list unique id from http://admin.mailchimp.com/lists/
// under settings at the bottom of the page, look for unique id
define(‘MC_LIST_ID’, $listid);
$email = $_POST['email'];
// check if email is valid
if ( isset($email) && validEmail($email) ) {

$api = new MCAPI(MC_API_KEY);
$listID = MC_LIST_ID;

if($api->listSubscribe($listID, $email, ”) === true) {
echo ‘success’;
}else{
echo ‘subscribed’;
}

} else {
echo ‘invalid’;
}

function validEmail($email=NULL)
{
return preg_match( “/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/ix”, $email );
}