Search code examples
phpgetmailchimpmailchimp-api-v3.0

Check whether email is subscribed to list in MailChimp API 3.0 using PHP


I've just read the following on the MailChimp website:

MailChimp API v3.0 is now live! Prior versions will no longer be supported after 2016, so all API users should begin transitioning to v3.0.

As a result, I would like to move to v3.0 of the API. Please could I have a function, in PHP, that returns a boolean, that will check whether an email address is subscribed to a specific MailChimp list. I do not want to subscribe that user, but merely check whether they are subscribed or not.


Solution

  • UPDATE: I answered another question with a more elaborate tutorial of how to do this with jQuery .ajax(): Adding subscribers to a list using Mailchimp's API v3

    Looking at the Mailchimp documentation and assuming you have a given list in mind, it looks like you would call this endpoint with a GET: /lists/{list_id}/members/{subscriber_hash}

    To do this in PHP, I found a nice script sitting on github. Their last function would probably do the trick for you:

    function mc_checklist($email, $debug, $apikey, $listid, $server) {
        $userid = md5($email);
        $auth = base64_encode( 'user:'. $apikey );
        $data = array(
            'apikey'        => $apikey,
            'email_address' => $email
            );
        $json_data = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'.api.mailchimp.com/3.0/lists/'.$listid.'/members/' . $userid);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic '. $auth));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        $result = curl_exec($ch);
        if ($debug) {
            var_dump($result);
        }
        $json = json_decode($result);
        echo $json->{'status'};
    }
    

    If that function doesn't work, the only wrapper I could find for the v3 library works in conjunction with Laravel - Mailchimp v3 API PHP wrapper.