Mailchimp Integration On a Website Using Mailchimp API and PHP

Mailchimp is one of the popular email marketing services which manages 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. Newsletters are useful to bring the audience back to the website.

Most of the websites put a subscription form to collect the user’s email. This email will directly go to 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 Mailchimp endpoints. It requires cURL to send HTTP 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 website. 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 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’, 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. Only 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 to store extra information about users. 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. 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 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.

8 thoughts on “Mailchimp Integration On a Website Using Mailchimp API and PHP

  1. If there is an error and ‘$e->getMessage();’ is displayed it contains a string something like

    ‘Client error: `POST https://us6.api.mailchimp.com/3.0/lists/list-id/members` resulted in a `404 Not Found` response: {“type”:”https://mailchimp.com/developer/marketing/docs/errors/”,”title”:”Resource Not Found”,”status”:404,”detail”:”The (truncated…) ‘

    How do I extract the title or status values from that.

  2. Hi. My video helped me a lot. I just have one question. My site has 5 pages and all pages have email input. How do I make the page redirect dynamic?

  3. 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.

  4. 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 *