I'm trying to signup users that signed up to my WordPress website to a MailChimp mailing list. Here is the function I'm using:
function rb_signup_mailing_list($email, $username, $fname, $lname){
$api_key        =   '<my_api_key>';
$datacenter     =   '<my_data_center>';
$list_id        =   '<my_list_id>';
$auth           =   base64_encode('user:'. $api_key);
$member_id      =   md5(strtolower($email));
$status         =   'subscribed';
$merge_fields   = ['FNAME' => $fname, 'LNAME' => $lname];
$data = array(
    //'apikey'      =>  $api_key,
    'email_address' =>  $email,
    'status'        =>  $status,
    'merge_fields'  =>  $merge_fields,
);
$data_string = json_encode($data);
//$url = 'https://' . substr($api_key, strpos($api_key, '-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' .md5(strtolower($email));
//$url = 'https://' . substr($api_key, strpos($api_key, '-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/';
$url = 'https://' . $datacenter . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/';
$ch = curl_init($url);
// curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, 
    array(
        'Content-Type: application/json',
        'Authorization: Basic ' . $auth,
        //'Content-Length: '    . strlen($data_string),
    )
);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
}
I call the function like this:
rb_signup_mailing_list('[email protected]', 'my_username', 'Hans', 'Meyer');
$result contains the following after curl_exec:
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the 'errors' array.","instance":"","errors":[{"field":"","message":"Schema describes object, NULL found instead"}]}
I can see the requests showing up in MailChimp, but they don't add emails to the list. What am I doing wrong?
                        
You're declaring the variable
$data_stringto hold the subscriber data, but using$datastringin your CURL request. Try updating them both to the same name and it should work fine.