I’ve been doing a lot of work with the MailChimp API V. 3.0 over the past year while developing the Cultivate CRM WordPress Plugin and I created the following helper function that has made live a lot easier for me since I have to make probably a dozen calls to the API within this one plugin.
MailChimp API 3.0 Helper Function
<?php function mailchimp_request($mcAPIkey,$url,$req_type,$json=''){ //send a HTTP POST, GET or PUT request with curl: $ch = curl_init($url); curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $mcAPIkey); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req_type);//GET, PUT, POST curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if($req_type!="GET")curl_setopt($ch, CURLOPT_POSTFIELDS, $json);//not needed for GET requests $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // echo "http code: $httpCode<br />"; $body = json_decode($result); //echo "successfully got list for Cultivate CRM!<br />result:<hr />$result<hr />"; $results['code'] = $httpCode ; $results['result'] = $result; // store the status message based on response code if ($httpCode == 200) {//if no error occurred: return $results; } else {//else an error occurred: return false; }//end else an error occurred }//end mailchimp_request PHP function by Ian L. of Jafty.com
Calling mailchimp_request Function
Here is how you use the above mailchimp_request PHP function:
<?php //Construct the MailChimp API URL: $mcAPIkey = 'YOUR-MC-API-KEY'; $mcListID = 'YOUR-MC-LIST-ID'; $email= 'MEMBER_EMAIL@EMAIL.COM'; $memberID = md5(strtolower($email)); $dataCenter = substr($mcAPIkey,strpos($mcAPIkey,'-')+1); $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $mcListID . '/merge-fields/'; //get the response: $response = mailchimp_request($mcAPIkey,$url,'GET'); $httpcode = $response['code']; $result = $response['result']; $decoded_result = json_decode($result); echo "http code: $httpcode<br>"; echo "Response data from getting address field data from MC API: "; $merged_field_obj = $decoded_result->merge_fields;//should be an array of merged fields print_r($merged_field_obj); ?>