Integrate the Constant Contact API with your PHP application

Constant Contact
Constant Contact

WHAT IS CONSTANT CONTACT?

Constant Contact is an online service for creating social and email campaigns which is widely used by a lot of websites. It provides a developer API which handles subscription lists and create/send newsletters.

In this article we will focus on the basics of creating contact lists and creating email campaigns. We will not go into Event Marketing and Bulk Imports/Exports. This article serves as a quick and simple way of integrating the Constant Contact AppConnect API with your PHP application.

FIRST STEP

The first step requires you to have an API Key.  The API key is a unique identifier for a Developer, not a customer, and they recommend having one API Key for each integration that you build.  So if you have two software platforms and you integrate both, you should create two API keys.

To create an API Key,  you need  a Constant Contact account and fill out their API Key request form.

The Constant Contact APIs allow you to manage contacts in your account in various ways.  By utilizing contacts collection and resource, you can add, edit, unsubscribe contacts as well as modify their contact list memberships. The Constant Contact REST API contains several useful methods to enable developers to easily manage contacts.

To see their complete API docs, click here.

Before you can start writing code, you need the PHP wrapper classes for this API available on Sourceforge: http://sourceforge.net/projects/ctctphplib/

Include the classes from this in all your code.

ADDING/UPDATING A CONTACT

$apikey = 'YOUR CONSTANT CONTACT APIKEY';
$cc_username =  'YOUR CONSTANT CONTACT USERNAME;
$cc_password =   'YOUR CONSTANT CONTACT PASSWORD;

//constructor for constant contact class
$Datastore = new CTCTDataStore();

$ConstantContact = new ConstantContact('basic', $apikey, $cc_username,$cc_password);
$lists = $ConstantContact->getLists();

$nextLists = "";
do {
if ($nextLists != "") 
{
		$Lists = $nextLists;
		$nextLists = $ConstantContact->getLists( $Lists ['nextLink'] );
	} 
	else if ($nextLists == "") 
	{
		$nextLists = $ConstantContact->getLists ();	
		$Lists = $nextLists;
	}
		
	foreach ( $Lists ['lists'] as $list ) 
	{
		if($list->name == 'YOUR LIST NAME')
		$cc_daily_deals_list_id = $list->id;						}
} while ( $Lists ['nextLink'] != false );

$search = $ConstantContact->searchContactsByEmail($emailId);
if($search == false)
{
// adding contact in constant contact in both the list
	$Contact = new Contact();
	$Contact->emailAddress ='EMAIL ID TO SUBSCRIBE';
	$Contact->City = 'CITY';
	$Contact->lists = array($cc_daily_deals_list_id);				
$Contact->CountryCode = 'COUNTRY_CODE';
$NewContact = $ConstantContact->addContact($Contact);			
}
else
{	
$Contact = $ConstantContact->getContactDetails($search[0]);
if($Contact->status != "Do Not Mail")	
{
$Contact->City = 'CITY';
$Contact->CountryCode = 'COUNTRY_CODE';
		if(!in_array($cc_daily_deals_list_id,$Contact->lists))
			array_push($Contact->lists,$cc_daily_deals_list_id);										
		if($Contact->status == "Removed")								if(!in_array($cc_daily_deals_list_id,$Contact->lists))
			$Contact->lists = array($cc_daily_deals_list_id);			
if(!in_array($cc_daily_deals_list_id,$Contact->lists))
			array_push($Contact->lists, $cc_daily_deals_list_id);
										
		// Update the contact and DONE
		$NewContact = $ConstantContact->updateContact($Contact);		  }
  }			

CREATE AN EMAIL  CAMPAIGN

1)	Create Campaign
$Datastore = new CTCTDataStore ();
$ConstantContact = new ConstantContact('basic', $apikey, $cc_username,$cc_password);

$lists = $ConstantContact->getLists();	
			
// Get all verified email addresses
$VerifiedEmailAddresses = $ConstantContact->getVerifiedAddresses ();

// getting the list id to send campaign to
$nextLists = "";
do 	{
	if ($nextLists != "") 
	{
		$Lists = $nextLists;									$nextLists = $ConstantContact->getLists( $Lists ['nextLink'] );
	} 
	else if ($nextLists == "") 
	{
		$nextLists = $ConstantContact->getLists ();						$Lists = $nextLists;
	}
	foreach ( $Lists ['lists'] as $list ) 
{
		//exit(var_dump($list));
		if($list->name == $cc_list_name)
			$cc_daily_deals_list_id = $list->id;				
		}
				
 } while ( $Lists ['nextLink'] != false );

// email content
$ch = curl_init();
$timeout = 400000;
curl_setopt($ch, CURLOPT_TIMEOUT, 200000);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

 // Getting binary data
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt ($ch, CURLOPT_URL, âYOUR PAGE URâ);
 $codeString = curl_exec($ch);
 curl_close($ch);
						
$codeString = str_replace("£","£",$codeString);
$codeString = str_replace("â¬","€",$codeString);
$codeString = str_replace('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 strict//EN">',"",$codeString);
//$codeString = substr($codeString,0,75732);

// creating campaign starts here	
try {
	$campaign_name = "Campaign For ".ucfirst($city_name)." on ".date('Y-m-d h:i:s');	//Build Campaign Object
	$myCampaign = new Campaign();							$myCampaign->name = $campaign_name;
	$myCampaign->subject = ucfirst($city_name).": ".$mail_subject;
	$myCampaign->fromName = $from_name;	
							
	if ($from_email != "") 
	{
		// Do while is necessary to grab the next 50 results and build
		// the next request so it keeps iterating until completion
	do {
		// Gets the next link if there are more than 50 results to
		// be returned
$moreVerifiedEmailAddresses = $ConstantContact->getVerifiedAddresses ( $VerifiedEmailAddresses ['nextLink'] );
	foreach ( $VerifiedEmailAddresses ['addresses'] as $VerifiedEmailAddress ) {
		if ($VerifiedEmailAddress->email == $from_email) {
			$myCampaign->fromAddress = $VerifiedEmailAddress;					$myCampaign->replyAddress = $VerifiedEmailAddress;					$fromAddress = $VerifiedEmailAddress;
			break; // We found our email address so we can exit our
	  // foreach
	}	
	}
	// Sets original Verified emaillAddresses to the next 50 so
	// it will replace its values
	$VerifiedEmailAddresses = $moreVerifiedEmailAddresses;
	} while ( $VerifiedEmailAddresses ['nextLink'] != false );
}

	$myCampaign->greetingName = "NONE";
	$myCampaign->greetingSalutation = "DEAR";
	$myCampaign->greetingString = "";
	$myCampaign->orgName = $orgn_name;
	$myCampaign->orgAddr1 = $address;
	$myCampaign->orgAddr2 = "";
	$myCampaign->orgAddr3 = "";
$myCampaign->orgCity = $cc_city;
	$myCampaign->orgState = $cc_state;
	
// Validates that if the user selects United states, the stateOther
// is empty
if ($cc_country == "United States") {
		$stateOther == NULL;
}
	$myCampaign->orgInternationalState = NULL;
$myCampaign->orgPostalCode = $cc_zipCode;
	$myCampaign->orgCountry = $cc_country;						$myCampaign->incForwardEmail = "NO";
	$myCampaign->incSubscribeLink = "NO";
	$myCampaign->forwardEmailLinkText = "";
	$myCampaign->subscribeLinkText = "";
	$myCampaign->emailContentFormat = "HTML";
$myCampaign->emailContent = htmlspecialchars($codeString);
	$myCampaign->textVersionContent = "<text>This is the text version</text>";
	$myCampaign->lists = array($cc_daily_deals_list_id);
	//print_r($myCampaign->emailContent);
	//exit;
$CampaignResult = $ConstantContact->addCampaign($myCampaign, $fromAddress);
	//print_r($CampaignResult);
	//exit;
	$schedule_time = date("Y-m-d")." ".$local_time;				
							$obj=new convert_timezone;
							$str=$obj->conver_to_time($country_timezone,$schedule_time,0);
							
							echo "New Campaign created for " .$city_name ." ID:".$CampaignResult->id."\n<br />";
							
							$lastCampaigns = $ConstantContact->getCampaigns();
							
							if (isset ( $CampaignResult->status )) {
								foreach ( $lastCampaigns ['campaigns'] as $recent ) {
									if ($recent->name == $CampaignResult->name) {
										$CampaignResult = $ConstantContact->getCampaignDetails ( $recent );
										
									}
								}
							}
							
							// schedule campaign here
							$schedule_flag = $ConstantContact->scheduleCampaign($CampaignResult,date('c',strtotime($str)));
							if(isset($schedule_flag) && $schedule_flag != NULL && $schedule_flag != ""){
								echo "Campaign is scheduled at ".$str."<br /><br />";

UNSUBSCRIBE CONTACT FROM A LIST

$search = $ConstantContact->searchContactsByEmail('OUR EMAIL TO UNSUBSCRIBE';
$Contact = $ConstantContact->getContactDetails($search[0]);
if(in_array($list_id, $Contact->lists))
$Contact->lists = array_values(array_diff($Contact->lists, array($list_id)));
$NewContact = $ConstantContact->updateContact($Contact);

The above are the basic operations which will be used. For more details, its best to consult the API documentation from the link given above.

2 Comments

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.