Popular Categories

How to subscribe user details using mailchimp API?

Recently a problem came in, where i had to send the details to mailchimp. I didn’t want to use bulk of the code provided via the libraries as my major aim of the problem was to just send the email and a bit of additional data.

To solve this, here is the piece of the code:

$data = [
’email’ => ‘[email protected]’,
‘status’ => ‘subscribed’,
‘firstname’ => ‘John Doe’,
‘answers’ => ‘Answer List Here, You can change this field’,


function syncMailchimp($data) {
$apiKey = ‘YOUR API KEY’;
$listId = ‘YOUR 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’],
‘ANSWERS’ => $data[‘answers’]

$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_POSTFIELDS, $json);

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

Reference Docs: