Adding a subscriber to MailChimp list using Unirest

Below is the Php code that can be used to add a subscriber to MailChimp.

Composer dependency:

"mashape/unirest-php": "dev-master"
private function addSubscriberToMailChimpList($member) {
  try { 
	$listid = '434115151251'; // list id from MailChimp
	$authKey = '1243124124144124'; // authentication API key
	// api uri
	$api = 'https://us12.api.mailchimp.com/3.0/lists/'.$listid.'/members';
	$headers = array('Content-Type' => 'application/json');
	// setup Unirest request
	Unirest\Request::auth('user', $authKey);
	Unirest\Request::verifyPeer(false);
	 // setup Unirest data
	$mergeFields = array('FNAME' => $member->FirstName, 'LNAME'=> $member->Surname);
	$data = array('email_address' => $member->Email, 'status' => 'subscribed', 'merge_fields' => $mergeFields);
	$body = Unirest\Request\Body::json($data);
	// post request, receive $response
	$response = Unirest\Request::post($api, $headers, $body);
		
   } catch (Exception $e) {

   }
}

Hope this is helpful!

Add a Comment

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image