5

I have tried and tried to send data to MailChimp using curl but cannot get the data to save in MailChimp. Any help with this would be greatly appreciated!

Here is my code:

$mailChimpUrl = "http://us2.api.mailchimp.com/1.3/?method=listSubscribe";
$merges = array(
    'FNAME'=>'Dave', 
    'LNAME'=>'Gilmour',
    'BUILDING'=>'Central High School',
    'MMERGE17' => '35904',
    'MMERGE12'=>'Yes'
);

$apikey="myrealapiishere-us2";
$listId="myrealformidishere";
$email="[email protected]";
$double_optin=true;
$update_existing=false;
$replace_interests=true;
$send_welcome=false;
$email_type = 'html';            
$data = array(
    'email_address'=>$email,
    'apikey'=>$apikey,
    'merge_vars' => $merges,
    'id' => $listId,
    'double_optin' => $double_optin,
    'update_existing' => $update_existing,
    'replace_interests' => $replace_interests,
    'send_welcome' => $send_welcome,
    'email_type' => $email_type
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $mailChimpUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));      
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
3
  • what does mailchimp return?
    – user557846
    Aug 29, 2014 at 2:46
  • First off, I would recommend you use the latest 2.0 API... Sort of the same structure, but they simplify a few things.
    – Oberst
    Aug 29, 2014 at 3:03
  • Second, never use unencrypted connections for any API integrations.
    – Mike Doe
    Jun 9, 2019 at 10:51

4 Answers 4

10
+250

Here is working simple MailChimp PHP API 3.0 Curl example code snippet

<?PHP

// put your api key here  note the ending text past the - this is your datacenter 
// the datacenter needs to be added into to the url in the curlopt_url (see below)
$apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us11"; // my datacenter was "us11"


// listid goes here - to find this... log into mail chimp go to Lists menu , 
// look to far right of list name for a drop down arrow, select the "Settings" dropdown,
// scroll to bottom and look  for  "Unique id for list"
$list_id = "xxxxxxxxxx"; // web site list


// the data I used to register (there may be others you can use, check API docs)
$email = "<<email_address_to_register>>";
$fname = "<<first_name>>";
$lname = "<<last_name>>";


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


// Notice the value of 'status' is 'pending'  
// I found this via a google search indicating a double opt in subscription process 

$data = array(
'apikey'        => $apikey,
'email_address' => $email,
'status'        => 'pending',
'merge_fields'  => array(
'FNAME' => $fname,
'LNAME' => $lname,
)
);
$json_data = json_encode($data);

$ch = curl_init();

// notice datacenter  "us11" comes after the // - make sure you update this to your datacenter (e.g. us2, us7 etc) or you'll get the "wrong datacenter" error.
$curlopt_url = "https://us11.api.mailchimp.com/3.0/lists/$list_id/members/";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
    'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.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);
/*
// some debug statements 
var_dump($result);
print_r ($result);
*/


// here is simple way to determine status of a subscription
// $result is in JSON format
// this following loop is a simple JSON decode loop I found via google


 $status = "undefined";
    $msg = "unknown error occurred";
$myArray = json_decode($result, true);

foreach($myArray as $key => $value)
{

    // debug key<<< = >>>$value<<< <br>";

    if( $key == "status" )
    {
        $status=$value;
        //debug                 echo" status found $status<Br>";
    }
    else if ($key == "title")
    {
        $msg=$value;
        //debug                 echo" title found $msg<Br>";
    }


}

// create the output that gets displayed or returned if invoked by AJAX method
if( $status == "pending" )
{
    $msg = "Success! <br>$email has been subscribed <Br>check your inbox for the confirmation email to complete your subscription";
}
else
{
    $msg = "Sorry can not subscribe email $email <br>$msg <Br>";
}


echo "$msg <br>";


die(' '); // frees up mem etc..

?>
3
  • it is giving me this error [type] => developer.mailchimp.com/documentation/mailchimp/guides/… [title] => JSON Parse Error [status] => 400 [detail] => We encountered an unspecified JSON parsing error.
    – saadk
    May 10, 2016 at 7:08
  • This should now be the accepted answer as version 2 of the MailChimp API is being discontinued. Aug 30, 2016 at 10:18
  • 2
    Can someone explain please why the mailchimp developers did not provided such an easy to use example? I guess it would be to easy then...
    – Black
    Sep 28, 2016 at 14:16
5

As I mentioned in my comment, you should consider the latest 2.0 API. Aside from that, this is code I am using in a production environment.

Albeit messy, it is functional. Just replace the merge_vars and variables with what yours are All the $lead variables are being pulled elsewhere in the script... Not relevant to this. You should still be able to get the idea. ;)

If something still isn't being saved, then you have a typo somewhere. Check EVERYTHING. Took me an hour once to realize I had misspelled 'merge_vars'.

$merge_vars=array(
    'OPTIN_IP'=>$ip, // Use their IP (if avail)
    'OPTIN-TIME'=>"now", // Must be something readable by strtotime...
    'FNAME'=>ucwords(strtolower(trim($lead['first_name']))),
    'LNAME'=>ucwords(strtolower(trim($lead['last_name']))),
    'COMPANY'=>ucwords(strtolower(trim($lead['company']))),
    'ORGTYPE'=>ucwords(strtolower(trim($lead['company_type']))),
    'PLANNING'=>strtolower(trim(empty($lead['planning_stage'])?"Unknown":$lead['planning_stage'])),
    );

$send_data=array(
    'email'=>array('email'=>$lead['email']),
    'apikey'=>"", // Your Key
    'id'=>"", // Your proper List ID
    'merge_vars'=>$merge_vars,
    'double_optin'=>false,
    'update_existing'=>true,
    'replace_interests'=>false,
    'send_welcome'=>false,
    'email_type'=>"html",
);

$payload=json_encode($send_data);
$submit_url="https://us4.api.mailchimp.com/2.0/lists/subscribe.json";
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$submit_url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);
$result=curl_exec($ch);
curl_close($ch);
$mcdata=json_decode($result);

if (!empty($mcdata->error)) return "Mailchimp Error: ".$mcdata->error;
return ""; // <-- This was obviously from within a function. If you made it here, it was a success
1
  • Thanks so much @Oberst! Until you mentioned it I did not run across anything regarding the 2.0 API. The one I was originally using came from here: http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php Once I converted over to that and changed email_address to email and used an array for the value it worked :) Thanks again! Aug 29, 2014 at 3:35
0

For anyone looking for an updated way to do this, there is a really good package; https://github.com/spatie/laravel-newsletter

You can install it via composer, and it is really simple to set up and use:

use Newsletter;

Newsletter::subscribe('[email protected]');
0

The previous answers didnt work and I have to adapt them, here the one working :

<?PHP
$apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx-us20";  // found in Account -> extra
$list_id = "xxxxxxxxx"; // found in Audience -> audience id

$email = $_POST["email"];

$data = array(
'apikey'        => $apikey,
'email_address' => $email,
'status'        => 'subscribed',
);

// Setup cURL
$ch = curl_init('https://us20.api.mailchimp.com/3.0/lists/'.$list_id.'/members/');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.$apikey,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($data)
));

$response = curl_exec($ch);

$status = "undefined";
$msg = "unknown error occurred";
$myArray = json_decode($response, true);

foreach($myArray as $key => $value){
    if( $key == "status" ){
        $status=$value;
    }
    else if ($key == "title"){
        $msg=$value;
    }
}

if( $status == "subscribed" ){
    $msg = "Success";
} else {
    $msg = "Sorry can not subscribe email $email <br>$msg <Br>";
}

echo "$msg";

die(' '); // frees up mem etc..
?>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.