Add Subscriber to List using MailChimp API and PHP


MailChimp is an email marketing service, helps to manage the subscribers of your website. MailChimp provides an easy way to integrate email signup form in your website and send the email newsletter to the subscriber. Beside the premium plan MailChimp also has a forever free plan. Using the free plan, you can add up to 2,000 subscribers to MailChimp and send 12,000 emails per month to the subscriber.
In this tutorial, we’ll show you how to integrate newsletter subscription form in your website and add subscriber to list with MailChimp using PHP. We’ll use MailChimp API 3.0 and PHP to add subscriber to list without confirmation email.
To integrate MailChimp API in PHP you need a MailChimp API Key and List ID where you want to add members. Before you begin, sign up for a MailChimp account and follow the below steps to get API Key and List ID.

Creating API Key and List ID

Get API Key:

  • Login to your MailChimp account.
  • Under the user menu dropdown at the top left side, click on Account link.
    custom-subscription-form-mailchimp-api-php-user-account-codexworld
  • Go to the Extras » API Keys from the top navigation menu.
    custom-subscription-form-mailchimp-api-php-extras-api-keys-codexworld

  • Under the Your API keys section, create an API Key by clicking on Create A Key button. Once generated, copy API key for later use in PHP script.
    add-subscriber-to-list-mailchimp-api-key-codexworld

Get List ID:

  • Choose a list in which all the subscriber’s information would be stored. In that case, you need to create a list in the Lists page.
    newsletter-subscription-form-integration-php-mailchimp-list-codexworld
  • Enter into your created list and navigate to Settings » List name and campaign defaults.
    add-subscriber-to-list-mailchimp-api-php-settings-codexworld
  • Under the List ID label you will find the List ID. Copy List ID for later use in PHP script.
    add-subscriber-to-list-mailchimp-api-php-list-id-codexworld

In our example script, a simple newsletter subscription form will be implemented. Once the user submits the subscription form along with the details (First Name, Last Name, and Email), respective details would be added to the list of MailChimp account using MailChimp API and PHP. Also, the subscriber would be able to receive the newsletter of your website via MailChimp.

Subscription Form (index.php)

The index.php file contains the custom subscription form HTML. The subscriber needs to enter their First Name, Last Name, and Email. By clicking on SUBSCRIBE button, the form will submit to the action.php file for adding the subscriber to the MailChimp subscriber list.

<?php session_start(); // place it on the top of the script ?>
<?php
    $statusMsg 
= !empty($_SESSION['msg'])?$_SESSION['msg']:'';
    unset(
$_SESSION['msg']);
    echo 
$statusMsg;
?> <form method="post" action="action.php"> <p><label>First Name: </label><input type="text" name="fname" /></p> <p><label>Last Name: </label><input type="text" name="lname" /></p> <p><label>Email: </label><input type="text" name="email" /></p> <p><input type="submit" name="submit" value="SUBSCRIBE"/></p> </form>

Add subscriber to MailChimp List (action.php)

In the action.php file, subscription form data is received and send the subscriber details to the MailChimp using MailChimp API and PHP. To Use MailChimp API, you need to mention API Key and List ID. Insert the API Key and List ID which you’ve got in the previous step.
Here cURL is used to send an HTTP POST request to the List Members endpoint with member information. After adding the subscriber to MailChimp list, the call returns a response. Based on the response ($httpCode), the status message would be shown to the subscriber.
To add a subscriber, you must include the subscriber’s status in your JSON object. If you include the subscriber’s status subscribed, subscriber email address would be added right away without sending a confirmation email. Use pending status to send a confirmation email to subscriber.

<?php
session_start
();
if(isset(
$_POST['submit'])){
    
$fname $_POST['fname'];
    
$lname $_POST['lname'];
    
$email $_POST['email'];
    if(!empty(
$email) && !filter_var($emailFILTER_VALIDATE_EMAIL) === false){
        
// MailChimp API credentials
        
$apiKey 'InsertMailChimpAPIKey';
        
$listID 'InsertMailChimpListID';
        
        
// MailChimp API URL
        
$memberID md5(strtolower($email));
        
$dataCenter substr($apiKey,strpos($apiKey,'-')+1);
        
$url 'https://' $dataCenter '.api.mailchimp.com/3.0/lists/' $listID '/members/' $memberID;
        
        
// member information
        
$json json_encode([
            
'email_address' => $email,
            
'status'        => 'subscribed',
            
'merge_fields'  => [
                
'FNAME'     => $fname,
                
'LNAME'     => $lname
            
]
        ]);
        
        
// send a HTTP POST request with curl
        
$ch curl_init($url);
        
curl_setopt($chCURLOPT_USERPWD'user:' $apiKey);
        
curl_setopt($chCURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
        
curl_setopt($chCURLOPT_TIMEOUT10);
        
curl_setopt($chCURLOPT_CUSTOMREQUEST'PUT');
        
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
        
curl_setopt($chCURLOPT_POSTFIELDS$json);
        
$result curl_exec($ch);
        
$httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
        
curl_close($ch);
        
        
// store the status message based on response code
        
if ($httpCode == 200) {
            
$_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to CodexWorld.</p>';
        } else {
            switch (
$httpCode) {
                case 
214:
                    
$msg 'You are already subscribed.';
                    break;
                default:
                    
$msg 'Some problem occurred, please try again.';
                    break;
            }
            
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
        }
    }else{
        
$_SESSION['msg'] = '<p style="color: #EA4335">Please enter valid email address.</p>';
    }
}
// redirect to homepage
header('location:index.php');

Conclusion

This example code helps to add subscribers to mailChimp list from the website through custom subscription form. You can see the added subscriber’s list from MilChimp account. Login to your MailChimp account and go to the subscriber’s list, you’ll see the newly added subscribers in the list.

3 Comments

  1. Ramesh Said...
  2. Bruno Said...
  3. Jairon Said...

Leave a reply

Connect With CodexWorld