Updating subscribers in a list using cURL and Mailchimp API v3
Asked Answered
M

3

9

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.

Melano answered 29/5, 2015 at 14:10 Comment(0)
M
10

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");
Melano answered 2/6, 2015 at 11:14 Comment(3)
Do note that the "subscriber ID" is really just the MD5 hash of their email address.Woodard
For anyone else looking at how to update the email of an existing subscriber - you can't do that (you need to DELETE the old email and then add the new one as a new subscriber). You cannot change information marked as "readonly" in the schema here: us9.api.mailchimp.com/schema/3.0/Lists/Members/Instance.jsonBalcony
Also note the subscriber ID is the lower case email address hashed with MD5. In PHP this means you must do md5(strtolower($email)). Here is the MailChimp documentation link on this.Cynar
W
4

You're looking for the CURLOPT_CUSTOMREQUEST option in cURL.

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

But, since this is now your second question in as many days asking how to use built-in cURL library, it might be worth using something a little better. If you're on PHP 5.4 or better, I recommend Guzzle. PHP Requests is also very good, though, and works with PHP 5.3.

Woodard answered 29/5, 2015 at 21:8 Comment(3)
This doesn't seem to work. I get the following error: "type" : "kb.mailchimp.com/api/error-docs/405-method-not-allowed", "title" : "Method Not Allowed","status":405,"detail":"The requested method and resource are not compatible. See the Allow header for this resource's available methods." The link on the page of the provided url leads to a 403 page which doesn't help me much.Melano
Also, thanks for those suggestions. I'll keep them in mind for future projects. The framework this website was developed in is pretty old and I think I'd spend more time figuring out how to integrate Guzzle than it's worth.Melano
Comment fail, the url in my original comment is kb.mailchimp.com/api/error-docs/405-method-not-allowedMelano
T
0

Try this one. It's working for me. I am using this function. Hope it should be solved your problem.

<?php
/**
 * Created by PhpStorm.
 * User: Faisal
 * Website: www.faisal-ibrahim.info
 * Date: 2/12/2016
 * Time: 10:07 AM
 */
if (isset($_POST['email'])) {
    $email = $_POST['email'];
} else {
    $email = '[email protected]';
}

$data              = [
    'email'     => $email,
    'status'    => 'subscribed',
    'firstname' => 'Faisal',
    'lastname'  => 'Ibrahim'
];
$api_response_code = listSubscribe($data);
echo $api_response_code;

/**
 * Mailchimp API- List Subscribe added function.In this method we'll look how to add a single member to a list using the lists/subscribe method.Also, We will cover the different parameters for submitting a new member as well as passing in generic merge field information.
 *
 * @param array $data Subscribe information Passed.
 *
 * @return mixed
 */
function listSubscribe(array $data)
{
    $apiKey = "cf8a1fd222a500f27f9e042449867c7c-us15";//your API key goes here
    $listId = "e8f3f5f880";// your trageted list ID

    $memberId   = md5(strtolower($data['email']));
    $dataCenter = substr($apiKey, strpos($apiKey, '-') + 1);
    $url        = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
    $json       = json_encode([
        'email_address' => $data['email'],
        'status'        => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
        'merge_fields'  => [
            'FNAME' => $data['firstname'],
            'LNAME' => $data['lastname']
        ]
    ]);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

    $result   = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode;
}
Trait answered 16/2, 2017 at 19:28 Comment(2)
Did you notice that you set PUT then overwrote with PATCH before executing? Bad copy-paste?Slipper
Did you need to check my linkedin before deciding to respond?Slipper

© 2022 - 2024 — McMap. All rights reserved.