Updating subscribers in a list using cURL and Mailchimp API v3

VenomRush picture VenomRush · May 29, 2015 · Viewed 10.4k times · Source

I have this code below that adds a user to a pre-existing list in Mailchimp.

$apikey = '<api_key>';
        $auth = base64_encode( 'user:'.$apikey );

        $data = array(
            'apikey'        => $apikey,
            'email_address' => $email,
            'status'        => 'subscribed',
            'merge_fields'  => array(
                'FNAME' => $name
            )
        );
        $json_data = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
        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_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);                                                                                                                  

        $result = curl_exec($ch);

        var_dump($result);
        die('Mailchimp executed');

This code only adds users to the list and when I try add the details of the same user twice it throws the following error on the second attempt:

[email protected] is already a list member. Use PATCH to update existing members.

How do I go about using PATCH to update user details? I'm not sure where to specify it.

Answer

VenomRush picture VenomRush · Jun 2, 2015

I figured out where I'm going wrong. When the user is initially added to the list the response provides an ID. I need to store the ID in my database with those person's details and reference the ID in the url I'm making a call to when I want to update the user's details in the Mailchimp List.

https://us2.api.mailchimp.com/3.0/lists/<list_id_goes_here>/members/<members_id_goes_here>

Thanks @TooMuchPete for the correct curl command.

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");