How to delete Mailchimp list members using API v3

One of our team members needed to delete Mailchimp list members signed to the list before given date.

It is not possible to do it in Mailchimp user interface, therefore we had to write short PHP script, which calls the Mailchimp API and deletes all list members subscribed into list before defined date.

 

Here is the example:

 

<?php

date_default_timezone_set('UTC');



function mailchimpRequest($type, $target, $data = false) {

    $api = array(
            'login' => 'anyuser',
            'key' => '27fd0105d2d0f76aa68405e4daecc028-us3',   //here should be your API KEY
            'url' => 'https://us3.api.mailchimp.com/3.0/'
    );
    $ch = curl_init($api['url'] . $target);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Authorization: ' . $api['login'] . ' ' . $api['key']
        ));

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'YOUR-USER-AGENT');

    if ($data)
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $response = curl_exec($ch);

    if ($response === false) {
        echo curl_error($ch);
        die();
    }
    curl_close($ch);
    return json_decode($response, true);
}


function getMembersToDelete($listId, $breakingDate) {
    $offset = 0;
    $toDelete = array();
    while (true) {
        $subscribers = mailchimpRequest('GET', '/lists/' . $listId . '/members?count=100&offset=' . $offset);
        foreach ($subscribers['members'] as $member) {
            if (strtotime($member['timestamp_opt']) < strtotime($breakingDate)) {
                echo 'Schedule to DELETE: ' . $member['email_address'] . "\n";
                $toDelete[] = $member['id'];
            } else {
                return $toDelete;
            }
        }
        if (count($subscribers['members']) == 0) {
            return $toDelete;
        }
        $offset += 100;
    }
    return $toDelete;
}


//THIS IS THE LIST ID YOU WANT TO CLENUP
$listId = 'cd17909729';


//MODIFY THE DATE
foreach (getMembersToDelete($listId, '2015-01-01') as $id) {
    mailchimpRequest('DELETE', '/lists/' . $listId . '/members/' . $id);
    echo 'Deleted ' . $id . "\n";
}

 

×