fbpx

Connect WooCommerce checkout with MailChimp list without a 3rd party plugin (via API and MailChimp PHP library)

Unlike my last article, where we connected our WooCommerce checkout to Sendinblue directly via an endpoint, this time we’re going to connect to MailChimp API, but by using their own PHP library.

By using their PHP library, we can simplify things a bit, use some built in functions to interact with their API and get things done just a bit quicker.

Things you’ll need:

  1. MailChimp account (free)
  2. MailChimp API key (free)
  3. Make a note of the MailChimp server you’re on (more on that later)
  4. Some knowledge of PHP and HTML
  5. Composer installed on your machine

Let’s dive right in.

Installing and including MailChimp PHP library

First things first, we need to install the MailChimp PHP library in your WordPress theme or plugin. For the sake of this article, we’re going to assume we’re using a WordPress theme. We’re going to be using Composer. First, in the root of your theme, create a file called ‘composer.json’ (if you don’t already have it). Add the following code to the composer.json:


    {
  "require": {
    "mailchimp/marketing": "*"
  }
}

Once you’re done, navigate your terminal to your theme’s root directory and install all composer dependencies by using the following command:


    composer install

Once completed, you’ll need to include ‘vendor/autoload.php’ in your project file. I recommend you create a new PHP file in your theme for this entire project, and include it through your theme’s functions.php. This way, you can organize things a little better, instead of having bloated code inside functions.php.

How you’re going to actually include autoload.php depends on your theme’s structure. But, let’s assume you’ve installed your composer dependencies in your theme’s root directory, just to make things a bit clearer. The way you would then include autoload.php file is:


    require_once(get_template_directory() . '/vendor/autoload.php');

You’ll notice I’m using ‘require_once‘ and I’m pointing it to my theme’s root path by using the function ‘get_template_directory()‘. After this, you simply include the composer’s autoload.php file (located in /vendor/ folder), and that’s it. When using get_template_directory_(), make sure you’re putting ‘/’ at the end of the function and before any folder or file path, since it does not include it in its own output.

Once you’ve included autoload.php, you’ve basically loaded MailChimp’s PHP library into your project, which means we can start using it immediately!

Hook and render the opt-in field

Just like in my previous article, we need to render our newsletter opt-in field on our WooCommerce checkout to allow our customers to choose whether they want to be added to our newsletter list.

So, we’ll hook this field to an appropriate WooCommerce action hook and render the field on the checkout. The hook we are using here is:


    'woocommerce_checkout_before_order_review_heading'

Here’s how that’s done:


    add_action('woocommerce_checkout_before_order_review_heading', __NAMESPACE__ . '\\codeart_add_newsletter_optin');
function codeart_add_newsletter_optin() {
    $html = "<div class='form-row codeartNewsletter'>";
    $html .= '<div class="innerWrap">';
    $html .= '<span class="woocommerce-input-wrapper">';
    $html .= '<input type="checkbox" name="codeartNewsletter" />';
    $html .= '<label for="codeartNewsletter">';
    $html .= 'Subscribe to our newsletter and get our discount coupon!';
    $html .= '</label>';
    $html .= '</span>';
    $html .= '</div><!--/.innerWrap-->';
    $html .= '</div><!--/.form-row-->';
    echo $html;
}
Rendering the opt-in field on the checkout

With a working opt-in field on our checkout page, we are now ready to do the heavy lifting and actually send our customer’s information to our MailChimp list (with our customer’s permission, of course).

Our value’s name is ‘codeartNewsletter‘, so when our customer posts the checkout form, we’re going to be checking for this value to see whether the checkbox field for the opt-in has been checked. In other words, this is how we’re going to check whether our customer wishes to be added to our newsletter:


    if($_POST['codeartNewsletter']
Checking whether a customer wants to sign up for our newsletter

Hook into the checkout process and connect to MailChimp API

Now, to actually be able to do all this, we need to hook into the exact moment our customer is sending the order from the checkout page, or, more simply put, the exact moment our customer hits the “Send order” button. Thankfully, WooCommerce has a hook just for this:


    'woocommerce_checkout_process'

So, I’m going to break this process down into couple of steps so you can better understand what’s going on:


    add_action('woocommerce_checkout_process', __NAMESPACE__ . '\\codeart_add_new_subscriber_to_list');
function codeart_add_new_subscriber_to_list() {
if($_POST['codeartNewsletter']) : 
require_once(get_template_directory() . '/vendor/autoload.php');
    $list_id = 'yourlistid';
    $firstname= $_POST['billing_first_name'];
    $lastname = $_POST['billing_last_name'];
    $email = $_POST['billing_email'];
    $client = new \MailchimpMarketing\ApiClient();
	$client->setConfig([
		'apiKey' => 'yourapikeygoeshere',
		'server' => 'us7',
	]);

You’ll notice I’m including the MailChimp PHP library only if our customer has checked the opt-in field. No need to load it otherwise, right?

Also, make sure you replace ‘yourlistid‘ and ‘yourapikeygoeshere‘ with your, well, list id and api key from MailChimp. Duh.

So, a couple of things are going on here:

  1. we must check whether our customer has checked the opt-in box (line 3)
  2. include our MailChimp PHP library (line 4)
  3. write down our MailChimp list id (line 5)
  4. prepare our customer’s contact information (lines 6 – 8)
  5. initialize MailChimp API client – we are doing this via ApiClient() function (line 9)
  6. configure our API call via setConfig() (line 10 – 13). This is where we enter our API key, and write down our server prefix. When you’re logged into your MailChimp account, in the browser address you’ll see something like ‘https://us19.admin.mailchimp.com/‘, so us19 would be your server prefix.

Once we’ve configured the API call, it’s time to put the pedal to the metal, so to speak, and process the call.

Process the API call and store customer information

We are going to process the API call by using try catch. The reason we need to use try catch, is to be able to deal with errors (exceptions) in a way that will not interrupt with the checkout process.

This is how this works:


    try {
	$response = $client->lists->addListMemberWithHttpInfo($list_id, [
		"email_address" => $email,
		"status" => "pending",
		"merge_fields"	=> array(
				"FNAME" => $firstname,
				"LNAME" => $lastname,
		),
    ]);

} catch (\GuzzleHttp\Exception\ClientException $e) {
    return;
}

MailChimp PHP library uses Guzzle to handle exceptions, so we’re catching our exception with ClientException, and basically doing nothing with it, because I do now want to disturb the checkout process. In my mind, it’s much more important for the customer to send the order, than to handle any type of error MailChimp API might face at any point.

Also, if you wish to use the double – opt in functionality and actually have the customer receive an opt-in confirmation e-mail from MailChimp, make sure to set the ‘status‘ to ‘pending‘, otherwise this just won’t happen. Believe me, I’ve learned this the hard way.

Once all this is done, you should have a working checkout opt-in newsletter that will store your customer’s information into your MailChimp list. Let’s put this all together.

Putting it all together


    add_action('woocommerce_checkout_before_order_review_heading', __NAMESPACE__ . '\\codeart_add_newsletter_optin');
function codeart_add_newsletter_optin() {
    $html = "<div class='form-row codeartNewsletter'>";
    $html .= '<div class="innerWrap">';
    $html .= '<span class="woocommerce-input-wrapper">';
    $html .= '<input type="checkbox" name="codeartNewsletter" />';
    $html .= '<label for="codeartNewsletter">';
    $html .= 'Subscribe to our newsletter and get our discount coupon!';
    $html .= '</label>';
    $html .= '</span>';
    $html .= '</div><!--/.innerWrap-->';
    $html .= '</div><!--/.form-row-->';
    echo $html;
}

add_action('woocommerce_checkout_process', __NAMESPACE__ . '\\codeart_add_new_subscriber_to_list');
function codeart_add_new_subscriber_to_list() {
if($_POST['codeartNewsletter']) : 
require_once(get_template_directory() . '/vendor/autoload.php');
    $list_id = 'yourlistid';
    $firstname= $_POST['billing_first_name'];
    $lastname = $_POST['billing_last_name'];
    $email = $_POST['billing_email'];
    $client = new \MailchimpMarketing\ApiClient();
	$client->setConfig([
		'apiKey' => 'yourapikeygoeshere',
		'server' => 'us7',
	]);
	
	try {
	$response = $client->lists->addListMemberWithHttpInfo($list_id, [
		"email_address" => $email,
		"status" => "pending",
		"merge_fields"	=> array(
				"FNAME" => $firstname,
				"LNAME" => $lastname,
		),
    ]);

} catch (\GuzzleHttp\Exception\ClientException $e) {
    return;
}
}

And there you have it, a working example on how to connect your WooCommerce checkout to a MailChimp list to store customer’s e-mail addresses (with their consent) without using a 3rd party plugin.

Hire your Codeartist

Looking for a development of your own project?

Is your agency looking for a partner?