Tutorials

Integrate Mailchimp Newsletter Subscriptions with PHP

  • December 20, 2016

In this tutorial, we will discuss how to integrate one of the most popular mailing list services with PHP.

Installation

As most modern Web service providers do, MailChimp offers an SDK for their API. Let’s install it through Composer:

composer require drewm/mailchimp-api

After installing the library through Composer, instantiate the class:

<?php
require("vendor/autoload.php");

use \DrewM\MailChimp\MailChimp;
$mc = new MailChimp('api_key_goes_here'); 

$mc is the object which we will use to send requests to the API.

Subscribe Users

To subscribe a user to the list, we will need a form where users enter their e-mail address:

<form id="frm-newsletter" name="newsletter" method="post" 
action="subscribe.php">
	<label>E-mail</label>
	<input type="text" name="email" class="email" />

	<button type="submit" name="submit">Submit</button>
</form>

The form can be submitted using AJAX:

<script type="text/javascript">
	$('#frm-newsletter').submit(function(e) {
		$.ajax({
		  type: "POST",
		  url: 'subscribe.php',
		  dataType: 'json',
		  data: {
		  	email: $('#frm-newsletter .email').val(),
		  },
		  success: function(response) {
		  	// User has been successfully subscribed
			// Do something here
		  },
		  error: function (jqXHR, textStatus, errorThrown) {
var response = $.parseJSON(jqXHR.responseText);

// User has not been subscribed
// Show an error or do something else here	
  }	  
		});
		e.preventDefault();
		return false;
	});
</script>

Subscribe.php validates the data, sends a request to MailChimp and returns 
the response:
<?php

$email = $_POST['email'];

$response = [];
$list_id = 'list_id_goes_here';

$resp = $mc->post("/lists/$list_id/members", [
    'email_address' => $email,
    'status' => 'subscribed'
]);

if ($mc->success()) {
    $response['message'] = 'Thank you for subscribing to the mailing list';

    // User successfully subscribed - set HTTP status code to 200
    http_response_code(200);
} else {
    $response['message'] = $mc->getLastError();

    // User not subscribed - set HTTP status code to 400
    http_response_code(400);
}

// Return json-formatted response
echo json_encode($response); 

Depending on the HTTP status code of the response, it can be handled differently when the subscription is successful that when there is an error.

Unsubscribe Users

In order to unsubscribe a user, we need to fetch his subscriber hash first:

$subscriber_hash = $mc->subscriberHash('john@doe.com'); 

Now that we have the hash, we can call the unsubscribe endpoint:

$list_id = 'list_id_goes_here';
$mc->delete("lists/$list_id/members/$subscriber_hash");

Since users can unsubscribe through interfaces other than your application, it might be convenient to monitor those events. This can be achieved with Webhooks. Webhooks are configured through the MailChimp interface to send data to a specified URL whenever an event occurs. The URL that receives a Webhook request should have the following code:

<?php
use \DrewM\MailChimp\Webhook;

Webhook::subscribe('unsubscribe', function($data){
    // User unsubscribed - do something here
    print_r($data);
});

The code from above will only handle “unsubscribe” events. If you would like to handle all Webhook events by yourself, do the following:

<?php

use \DrewM\MailChimp\Webhook;

$result = Webhook::receive();
print_r($result); 

Conclusion

This tutorial has shown how to quickly create a form where users can sign up to your MailChimp newsletter list and how to unsubscribe them, if needed. However, MailChimp offers many more integration options, such as campaigns and reporting, as well as seamless integration with other services.