Introduction
If you're looking to add users to a list in Mailchimp but are struggling to find clear examples, this guide will help you navigate the Mailchimp API v3. It's important to note that earlier versions of the API are deprecated, and you should use v3 for all new integrations.
Prerequisites
Before you start, ensure you have:
- A Mailchimp account
- An API key from your Mailchimp account
- The List ID of the audience you want to add subscribers to
Authentication
Mailchimp API v3 requires basic authentication. You will need to encode your API key in the request header. Here’s how you can do it using PHP and cURL:
Code Example
<?php
// Define your API key and List ID
$apiKey = '<your_api_key>';
$listId = '<your_list_id>';
// Prepare subscriber data
$email = 'subscriber@example.com';
$name = 'John';
$data = [
'email_address' => $email,
'status' => 'subscribed', // Options: subscribed, unsubscribed, cleaned, pending
'merge_fields' => [
'FNAME' => $name
]
];
// Create a unique member ID based on the email address
$memberId = md5(strtolower($email));
$dataCenter = substr($apiKey, strpos($apiKey, '-') + 1);
// Construct the API endpoint URL
$url = "https://$dataCenter.api.mailchimp.com/3.0/lists/$listId/members/$memberId";
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
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_encode($data));
// Execute the request and capture the response
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Output the result
if ($httpCode == 200) {
echo 'Subscriber added successfully!';
} else {
echo 'Error adding subscriber: ' . $result;
}
?>
Explanation
- API Key: Replace
<your_api_key>with your actual Mailchimp API key. - List ID: Replace
<your_list_id>with the ID of the list you want to add subscribers to. - Email and Name: Modify the
$emailand$namevariables to the subscriber's email and first name. - Member ID: The member ID is generated using the MD5 hash of the email address, ensuring uniqueness.
- cURL Options: The cURL options set the request method to
PUT, which is used to add or update a subscriber. TheContent-Typeis set toapplication/jsonto indicate the format of the data being sent.
Conclusion
By following this guide, you should be able to successfully add subscribers to your Mailchimp list using the API v3. Make sure to handle any errors appropriately and test your implementation thoroughly.