Mailchimp - saving subscriber data using it's API

Posted by Damodar Bashyal on October 03, 2012

 

Today's task for me was to connect existing site's newsletter subscription to mailchimp using mailchimp's API. So, after going through some API docs on mailchimp, this is what worked for me. So, this is my log for short and direct steps and links for next time when i have to work with mailchimp again. Hopefully it will help someone else too.

  1. Add API key here - https://us1.admin.mailchimp.com/account/api/
  2. Create folder /lib/mailchimp
  3. Download mailchimp api class and config file (http://apidocs.mailchimp.com/api/downloads/mailchimp-api-class.zip) from - http://apidocs.mailchimp.com/api/downloads/
  4. Extract zip and copy MCAPI.class.php and config.inc.php to /lib/mailchimp
  5. Update config.inc.php with your credentials. i.e. API key and List ID
    // Content of config.inc.php
    
    //API Key - see http://admin.mailchimp.com/account/api
    $apikey = '1231452987526545ee4b96468cf6aaaa-us5';
    
    // A List Id to run examples against. use lists() to view all
    // Also, login to MC account, go to List, then List Tools, and look for the List ID entry
    $listId_Subscribers = '6a76e1bdb3';
    
    // A Campaign Id to run examples against. use campaigns() to view all
    $campaignId = 'YOUR MAILCHIMP CAMPAIGN ID - see campaigns() method';
    
    //some email addresses used in the examples:
    $my_email = [email protected]';
    $boss_man_email = [email protected]';
    
    //just used in xml-rpc examples
    $apiUrl = 'http://api.mailchimp.com/1.3/';
    
  6. Then wherever your visitors subscribe form is submitted and processed add this function:
    function listSubscribe($email_address,$firstname,$lastname)
    {
        $result = array('msg' => 'Subscription successfull!');
        
    	require_once('lib/mailchimp/config.inc.php');
    	require_once('lib/mailchimp/MCAPI.class.php');
        
    	/*
    	* Samples
    	* $apikey = '1231452987526545ee4b96468cf6aaaa-us5';
    	* $listId_Subscribers = '6a76e1bdb3';
    	*
        */
    	$api = new MCAPI($apikey);
    	$listId = $listId_Subscribers;
    	$merge_vars = array(
    		"FNAME" => $firstname,
    		"LNAME" => $lastname,
    		"MMERGE3" => 'HTML',
    		"MMERGE4" => 'Confirmed',
    		"MMERGE5" => date("m/d/Y",time()),
    	);
    	$retval = $api->listSubscribe( $listId, $email_address, $merge_vars );
    	
    	if ($api->errorCode){
    		$result = array(
    			'code'  => $api->errorCode,
    			'msg'   => $api->errorMessage
    		);
    	}
    
        return $result;
    }
    
  7. Then call this function like this:
    if($_REQUEST['newsletter'] == "yes") {
    	/*add subscriber data to mailchimp.*/
    	$subscription_result = listSubscribe($_SESSION['login']['user'],$_REQUEST["name"],$_REQUEST['last_name']);
    }
  8. TEST >> you should be good to go.
 
not published on website


QR Code: Mailchimp - saving subscriber data using it's API