MailChimp Integration On a Website Using MailChimp API and PHP

MailChimp is one of the popular email marketing services which manage the subscribers of your website. Using MailChimp, you can send a newsletter to your subscribers. In the newsletter, you may write about your fresh content, offers, or announcements on your website. Newsletters are useful to bring the audience back to the website.

Another popular email marketing service providers are:

Most of the websites put a subscription form where they collect the user’s email. This email will directly go to the MailChimp as a subscriber.

In this article, we study how to do MailChimp integration using their APIs and PHP cURL. We are going to add an email to MailChimp. In other words, we will see how to add subscribers to MailChimp using their API.

Before proceeding make sure you have cURL enabled on the server. We are interacting with the external URL which is nothing but MailChimp endpoints. It requires cURL to send requests and receive responses.

Having said that, let’s see how one can add a subscriber to their MailChimp lists through API.

You can integrate this MailChimp integration on any PHP powered websites. For example, on websites that are built using WordPress, Laravel, etc.

Get MailChimp API Key and Audience ID

In order to interact with the MailChimp API, you need to grab the API key and Audience ID. Follow the below steps and get it.

Login to your MailChimp account. Under the user icon, select the Account.

account-link

Click on Extra->API keys.

Click API Keys

Under Your API keys section, click on Create A Key. Copy your API key which we need in a moment.

Copy API Key

Next, get an Audience ID to which you need to add your subscribers. For this, click on the Audience menu and then select the option Settings from the Manage Audience drop-down.

audience

Under the Settings click on the ‘Audience name and defaults’.

audience-name-defaults

On the next page, you will find your Audience ID.

Audience ID

Add Subscriber to MailChimp List

At this stage, you are ready with your API key and Audience id. Now, all we need to do is send an HTTP request to the MailChimp API along with the required parameters.

You can find a list of all API calls on their official documentation. For our tutorial, we need their Add a new list member API call.

This API call requires an API key with an email address and status. For status, we can pass either the ‘subscribed’ or ‘pending’ value. If a value is ‘subscribed’, then the email address gets added directly to the MailChimp list. And if a value is ‘pending’, then a confirmation email will be sent to a user. After confirmation, the user becomes a subscriber.

To integrate this API, place the below code in your PHP file. Make sure to replace the placeholders with the actual values.

<?php
$email = 'EMAIL_ADDRESS';
$list_id = 'LIST_ID';
$api_key = 'API_KEY';

$data_center = substr($api_key,strpos($api_key,'-')+1);

$url = 'https://'. $data_center .'.api.mailchimp.com/3.0/lists/'. $list_id .'/members';

$json = json_encode([
    'email_address' => $email,
    'status'        => 'subscribed', //pass 'subscribed' or 'pending'
]);

try {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    $result = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if (200 == $status_code) {
        echo "The user added successfully to the MailChimp.";
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

In the above code, on the successful execution, you will get a 200 as a response code. We also handled the error if it throws for some reason.

Mailchimp also provides the Audience fields which store extra information about users directly inside the MailChimp dashboard. Just in case, if you are looking to add Audience fields then you can do it by adding one more array element in the above POST request. Here, I am adding values for the default Audience fields FNAME and LNAME.

<?php
...
...
$json = json_encode([
    'email_address' => $email,
    'status'        => 'subscribed', //pass 'subscribed' or 'pending'
    'merge_fields'  => [
        'FNAME' => 'ENTER_FIRST_NAME',
        'LNAME' => 'ENTER_LAST_NAME'
    ]
]);

Add Tags to Subscriber

You may want to organize your MailChimp contacts with tags. For assigning tags to the subscriber you need to send a POST request to the MailChimp API. Refer to the below code that assigns tags Blogger and YouTuber to a subscriber.

<?php
$email = 'EMAIL_ADDRESS';
$list_id = 'LIST_ID';
$api_key = 'API_KEY';

$data_center = substr($api_key,strpos($api_key,'-')+1);
$subscriber_hash = md5(strtolower($email));

$url = 'https://'. $data_center .'.api.mailchimp.com/3.0/lists/'. $list_id .'/members/'. $subscriber_hash .'/tags';

$json = json_encode([
    'tags' => [
                ['name' => 'Blogger', 'status' => 'active'],
                ['name' => 'YouTuber', 'status' => 'active'],
            ]
]);

try {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    $result = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if (204 == $status_code) {
        echo "The tags added successfully to the User.";
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

The user can remove tags by providing an ‘inactive’ value for the status key.

Delete a Subscriber from MailChimp List

MailChimp API provides an API call for deleting an email address from a list. As per documentation to delete a subscriber, we need to send a DELETE request to the API. This time you have to pass the md5 hash of an email address to the API endpoint.

<?php
$email = 'EMAIL_ADDRESS';
$list_id = 'LIST_ID';
$api_key = 'API_KEY';

$data_center = substr($api_key,strpos($api_key,'-')+1);

$url = 'https://'. $data_center .'.api.mailchimp.com/3.0/lists/'. $list_id .'/members/'. md5(strtolower($email));

try {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
} catch(Exception $e) {
    echo $e->getMessage();
}

I hope you understand about MailChimp API integration on a website using PHP. Please share your thoughts and suggestions in the comment below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

5 thoughts on “MailChimp Integration On a Website Using MailChimp API and PHP

  1. hi have you got any further documentation in this or any sample files you could share.

    MailChimp Integration On A Website Using MailChimp API And PHP.

  2. I want a php script integration to list members from a “id_List” based on a query string.
    for exaple, in mailchimp API we had “curl –request GET \
    –url ‘https://usX.api.mailchimp.com/3.0/search-members?query=freddie@’ \
    –user ‘anystring:apikey’ \
    –include”

    to search members, but how can I filter this response, e show in a html table?
    I think to use php but… =/

    1. Using the above API call you will get the list of specific members. You can loop through this list and print it in HTML table.

Leave a Reply

Your email address will not be published. Required fields are marked *