Add a New Subscriber to Your MailChimp List with API

In order to create a functionality that allow us to automatically add a subscriber to a list on MailChimp Email and Marketing platform, we can use MailChimp’s API. This example is written in PHP. Make sure that you have an API key and list id from your MailChimp account.

The following code adds a subscriber to the list:

<?php
$message = subscribe($email, $fname, $lname);

The function code is below:

<?php
function subscribe($email, $fname, $lname) {
  $apiKey = 'some-ip-key-dda80b';
  $list = '0123abc';
  $member = md5(strtolower($email));
  $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
  $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $list . '/members/' . $member;        
  $json = json_encode([
    'email_address' => $email,
    'status'        => 'subscribed',
    'merge_fields'  => [ 'FNAME' => $fname, 'LNAME' => $lname ]
  ]); 
       
  // send a HTTP POST request with curl
  $c = curl_init($url);
  curl_setopt($c, CURLOPT_USERPWD, 'user:' . $apiKey);
  curl_setopt($c, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($c, CURLOPT_TIMEOUT, 10);
  curl_setopt($c, CURLOPT_CUSTOMREQUEST, 'PUT');
  curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($c, CURLOPT_POSTFIELDS, $json);
  $result = curl_exec($c);
  $httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE);
  curl_close($c);

  // get message based on response code
  if ($httpCode == 200) {
    $message = 'Subscribed.';
  } else {
    switch ($httpCode) {
        case 214:
	$message = 'Already subscribed.';
        break;
        default:
        $message = 'Some problem occurred.';
        break;
    }
    $message = 'Some problem occurred.';
  }
  return $message;
}

To unsubscribe an existing subscriber use PATCH request. The following code makes a subscriber to unsubscribe:

<?php
function unsubscribe($email) {
  $apiKey = 'some-ip-key-dda80b';
  $list = '0123abc';        
  $member = md5(strtolower($email));
  $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
  $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $list . '/members/' . $member;        
  $json = json_encode(['status' => 'unsubscribed']);
        
  // send a HTTP POST request with curl
  $c = curl_init($url);
  curl_setopt($c, CURLOPT_USERPWD, 'user:' . $apiKey);
  curl_setopt($c, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($c, CURLOPT_TIMEOUT, 10);
  curl_setopt($c, CURLOPT_CUSTOMREQUEST, 'PATCH');
  curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($c, CURLOPT_POSTFIELDS, $json);
  $result = curl_exec($c);
  $httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE);
  curl_close($c);

  $message = ($result) ? 'Unsubscribed.' : 'Some problem occurred.';
  return $message;
}