Skip to content

Instantly share code, notes, and snippets.

@rbk
Last active August 31, 2016 20:58
Show Gist options
  • Select an option

  • Save rbk/0cc34fec06888bf49480cb86a9f40d68 to your computer and use it in GitHub Desktop.

Select an option

Save rbk/0cc34fec06888bf49480cb86a9f40d68 to your computer and use it in GitHub Desktop.
Subscript to Mailchimp list via php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MC TEST</title>
</head>
<body>
<?php
define('CLIENT_ID', '');
define('CLIENT_SECRET', '');
define('API_KEY', '');
define('LIST_ID', '');
$data = [
'email' => '',
'status' => 'subscribed',
'firstname' => '',
'lastname' => ''
];
syncMailchimp( $data );
function syncMailchimp($data) {
$errors = array();
if( ! API_KEY )
array_push($errors, 'No API key.');
if( ! LIST_ID )
array_push($errors, 'No list id.');
if( empty( $data['email'] ) ) {
array_push($errors, 'No email address');
} else {
if( ! filter_var( $data['email'], FILTER_VALIDATE_EMAIL) )
array_push($errors, 'Invalid email address');
}
if( count($errors) > 0 ) {
echo '<ol class="mc-errors-found">';
foreach( $errors as $error ) {
echo '<li>'.$error.'</li>';
}
echo '</ol>';
return;
}
$apiKey = API_KEY;
$listId = 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'],
'LNAME' => $data['lastname']
]
]);
$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);
curl_close($ch);
return $httpCode;
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment