1

Below is my code to create or update subscription in Mailchimp.

function mailchimp_ajax_subscription()
{
    $data = isset( $_POST['formData'] ) ? $_POST['formData'] : array();
    ob_start();
    if(count($data) > 0)
    {

        $api_key = 'XXXXXXXXXXXXXX';
        $status = 'unsubscribed'; // subscribed, unsubscribed, cleaned, pending

            $args = array(
                'method' => 'PUT',
                'headers' => array(
                    'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
                ),
                'body' => json_encode(array(
                    'email_address' => $data["email"],
                    'status'        => $status,
                    'tags'  => array($data["name"])
                ))
            );

            $response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/XXXXX/members/' . md5(strtolower($email)), $args );

            $body = json_decode( $response['body'] );

            if ( $response['response']['code'] == 200 && $body->status == $status ) {
                echo 'The user has been successfully ' . $status . '.';
            } else {
                echo '<b>' . $response['response']['code'] . $body->title . ':</b> ' . $body->detail;
            }

    }
    wp_die();  
}

Using above code, I can create subscription into Mailchimp but If I enter same email to edit the tags/status it gives me error.

Error:

400Member Exists: abc@xyz.com is already a list member. Use PUT to insert or update list members.

I already used PUT in the code so what is missing?

Prashant Patil
  • 2,463
  • 1
  • 15
  • 33

1 Answers1

1

You can use TAGS API to update the TAGS. Below is the sample code to update the TAG:

$postdata = array(
    'apikey' => $api_key,
    'email_address' => $userData["email"],
    'tags' => array(
        array(
            'name' => $userData["name"],
            'status' => 'active'
        ),
    )
);

$mch_api = curl_init(); // initialize cURL connection 
curl_setopt($mch_api, CURLOPT_URL, 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($userData['email']))."/tags"); 
curl_setopt($mch_api, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '.base64_encode( 'user:'.$api_key ))); 
curl_setopt($mch_api, CURLOPT_RETURNTRANSFER, true); // return the API response 
curl_setopt($mch_api, CURLOPT_TIMEOUT, 10); 
curl_setopt($mch_api, CURLOPT_POST, true); 
curl_setopt($mch_api, CURLOPT_POSTFIELDS, json_encode($postdata) ); // send data in json 
$result = curl_exec($mch_api); 
Tarul
  • 58
  • 5