Mailchimp is a Email marketing service, that allows you to manage subscribers in your website. Mailchimp provides integrated tools to manage your subscribers in an easy way. Basically Mailchimp is not a free tool, but they have a free option with limited subscribers. With this free forever plan you can have a list of 2000 subscribers and 12000 email dispatches.
This free plan is very suitable for startups and those who running personal non-profit blogs etc.
Mailchimp has options to bulk import the contacts to your lists through CSV. Today’s tutorial we demonstrates, how to integrate MailChimp API in PHP to subscribe emails programatically. Before that you have to get the API key and list ID . We just made it the entire steps simple, follow the steps to create MailChimp API Key and list ID.
Creating API Key and get List ID
API Key
1). Login to your MailChimp account.
2) Under the user menu on the top right corner, select Accounts option.
3) Go to Extras -> API keys from the sub navigation menu
4) So this is your API keys, you can use an existing one or you can create new one by clicking on the Create A Key bitton
Get List Id:
1) Go to the list which you are planning to subscribe all your users. Click on the Lists option on the top menu
2) Enter into your created list and navigate to Settings -> List Name and campaign defaults.
3) You will find the List ID under the List ID label.
So we got all the necessary details to work with the MailChimp subscriber API. Now we will move to our example scripts. There are two pages, one is collecting the user detail and other is sending the payload to MailChimp API
Subscription form(form.php)
The form.php contains the subscriber form with elements like First Name, Last Name, Email. By clicking on the subscriber button all the form details will be posted to page mpost.php
<!doctype html> <html lang="en"> <head> <title>Mailchimp subscribe form</title> </head> <body> <form method="post" action="mpost.php"> <div> <label>First Name</label> <input type="text" name="firstname"> </div> <div> <label>Last Name</label> <input type="text" name="lastname"> </div> <div> <label>Email</label> <input type="text" name="email"> </div> <div> <button type="submit" name="subscribe">Subscribe</button> </div> </form> </body> </html>
Adding subscriber to mailchimp list(mpost.php)
In the mpost.php file, subscription form data received and send to MailChimp API. At the first lines of script we have wrote the API Key and List ID.
Next step, we validate the email id is present or not as the email is mandatory in MailChimp API. Curl is used to transfer all the details to MailChimp API Endpoint. You have to write the status as subscribed in order to get the email id subscribed. This will add a customer to database without sending a confirmation email. If you want to send a confirmation email to customer, just add the status as pending.
<?php //API Details $apiKey = 'InsertMailChimpAPIKey'; $listId = 'InsertMailChimpListID'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $email = $_POST['email']; if($email) { //Create mailchimp API url $memberId = md5(strtolower($email)); $dataCenter = substr($apiKey,strpos($apiKey,'-')+1); print $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId; //Member info $data = array( 'email_address'=>$email, 'status' => 'subscribed', 'merge_fields' => [ 'FNAME' => $firstname, 'LNAME' => $lastname ] ); $jsonString = json_encode($data); // send a HTTP POST request with curl $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, $jsonString); $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); //Collecting the status switch ($httpCode) { case 200: $msg = 'Success, newsletter subcribed using mailchimp API'; break; case 214: $msg = 'Already Subscribed'; break; default: $msg = 'Oops, please try again.[msg_code='.$httpCode.']'; break; } } header('location:form.php?msg='.$msg); }
Conclusion
This tutorial helps to add a email to Subscribers List using MailChimp API and PHP CURL. We have created an API key for that. We captured all the details from the html form and send to PHP Curl, in order to process the subscription.
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
gud
Great!
We can also follow this: https://usingphp.com/post/add-new-subscriber-in-a-mailchimp-list-api
I’m getting the default error code ‘Opps, please try again’. Can anyone help me with this? I’m using the free MailChimp account, created the API key and used the list id as well. Thanks in advance.
I just get a blank page (it stays on the mpost.php page)? Also, should there be a place for the $msg (‘location:form.php?msg=’.$msg) to appear on the form page when it redirects back to the form page?
How to handle custom merge tags to identify which type of subscriber this is? I don’t want to have multiple lists. I would rather add merge tags (i.e newsletter, customer, etc).