Subscribe users to MailChimp List using PHP

Instead of using form provided by MailChimp, we can integrate MailChimp subscription to our website using API. Subscribing users to MailChimp List is quite simple using MailChimp API v3. All you need is a MailChimp Account and a MailChimp List. Here’s the step by step guide to add subscriber with PHP and cURL.

1. Getting MailChimp API Key

First of all you need to log into MailChimp Account. If you haven’t created account yet, it is pretty straight forward to create and get started with MailChimp. Once logged in, click your profile name >> Choose Account >> Extras drop-down >> API key. You will see something like the following screenshot.

mailchimp-api-key
MailChimp API key page

If you already have a API key, it will be shown at ‘Your API keys’ section. You can simply note it. If not then click the ‘Create A Key’ button to create new API Key.

2. Creating MailChimp List

Next we need MailChimp List to which we are going to add subscribers using API. If you haven’t created List yet, just click the “Lists” in the navigation menu. Then fill the ‘Create List’ form properly. Now that you have created MailChimp List, it’s time to find the List ID.

To get the List ID, navigate to the Lists page, click the drop-down menu next to the list you want to work with, and then choose Settings. Scroll to find the unique List ID field. The string of letters and numbers is the list ID.

MailChimp List

3. Integrating MailChimp API

So far we have gathered MailChimp API key and List ID. Now it’s time to make our hand dirty with coding. Here’s the PHP snippet.

$api_key = 'your-api-key';
$list_id = 'your-list-id';

// Getting params from URL
$fname = isset($_GET['fname']) ? $_GET['fname'] : '';
$lname = isset($_GET['lname']) ? $_GET['lname'] : '';
$email = isset($_GET['email']) ? $_GET['email'] : '';

/**
*  Possible Values for Status:
*  subscribed, unsubscribed, cleaned, pending, transactional
**/
$status = 'subscribed'; 

if($email) {
    $data = array(
      'apikey'        => $api_key,
      'email_address' => $email,
      'status' 		=> $status,
      'merge_fields'  => array(
            'FNAME' => $fname,
            'LNAME' => $lname
          )
    );
    
  // URL to request
  $API_URL = 	'https://' . substr($api_key,strpos($api_key,'-') + 1 ) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($data['email_address']));
  
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $API_URL);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '.base64_encode( 'user:'.$api_key )));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data) ); 
  $result = curl_exec($ch);	
  curl_close($ch);
  
  $response = json_decode($result);

  
  if( $response->status == 400 ){
    foreach( $response->errors as $error ) {
      echo 'Error: ' . $error->message . '<br>';
    }
  } elseif( $response->status == 'subscribed' ){
    echo 'Thank you. You have already subscribed.';
  }elseif( $response->status == 'pending' ){
    echo 'You subscription is Pending. Please check your email.';
  }
}



I have used $_GET request as demo to fetch firstname, lastname and email. Instead you can use $_POST or data from database to add subscriber to you newsletter list. And then run this script, check your list. You will find the subscriber add to your list.

In this way, we can add subscriber to MailChimp list. Furthermore, we can dynamically create campaign, add content to the campaign and send newsletter using API. Check this post for more details: Dynamically send MailChimp newsletter via PHP.

Happy Coding!

3 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.