The Community is hosting an End of Summer sweepstakes! Participants must complete tasks to earn tickets that will enter them with a chance to win a free year of Constant Contact and other great prizes!*
*No Purchase Necessary. For Official Rules, visit here. Constant Contact’s End of Summer 2020 Sweepstakes ends on October, 20, 2020 at 11:50 PM EST.

Adding a Contact that already exists to an new list

Highlighted
Occasional Participant

Adding a Contact that already exists to an new list

Greetings Constant Contact community,


We are a retailer. Some of our customers get a promotional flyer via U.S. Mail. We would like them to sign up to get the Flyer via email. Some of these customers are already members of our other email lists.


I created a web form based on the PHP simple form example, specifying the list I want to use at var $contact_lists.


But the code is checking all of my lists to determine whether or not to allow a user to sign up, thus some customers are being rejected.


 


Here is my complete code. Any suggestions would be welcome.


 


 


<?php


header('Content-Type: text/html; charset=UTF-8');


 


 


 


 


    /**


    * Class that is using REST to communicate with ConstantContact server


  * This class currently supports actions performed using the contacts, lists, and campaigns APIs


    * @author ConstantContact Dev Team


    * @version 2.0.0


    * @since 30.03.2010 


    */


    class CC_Utility {


           


        // FROM HERE YOU MAY MODIFY YOUR CREDENTIALS        


        var $login = 'XXXXXXXX'; //Username for your account


        var $password = 'XXXXXXXXX'; //Password for your account


        var $apikey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // API Key for your account.


        


       // CONTACT LIST OPTIONS


        var $contact_lists = array('Go_Green_Flyer_Migration_July_2010'); // Define which lists will be available for sign-up.


        var $force_lists = true; // Set this to true to take away the ability for users to select and de-select lists


        var $show_contact_lists = false; // Set this to false to hide the list name(s) on the sign-up form.


        // NOTE - Contact Lists will only be hidden if force_lists is set to true. This is to prevent available checkboxes form being hidden.


                


        // FORM OPT IN SOURCE - (Who is performing these actions?)


        var $actionBy = 'ACTION_BY_CUSTOMER'; // Values: ACTION_BY_CUSTOMER or ACTION_BY_CONTACT


        // ACTION_BY_CUSTOMER - Constant Contact Account holder. Used in internal applications.


        // ACTION_BY_CONTACT - Action by Site visitor. Used in web site sign-up forms.


        


        // DEBUGGING


        var $curl_debug = false; // Set this to true to see the response code returned by cURL


        


        // YOUR BASIC CHANGES SHOULD END HERE


        var $requestLogin; //this contains full authentication string.


        var $lastError = ''; // this variable will contain last error message (if any)


        var $apiPath = 'https://api.constantcontact.com/ws/customers/'; //is used for server calls.


        var $doNotIncludeLists = array('Removed', 'Do Not Mail', 'Active'); //define which lists shouldn't be returned.


 


        


        public function __construct() {


            //when the object is getting initialized, the login string must be created as API_KEY%LOGIN:PASSWORD


            $this->requestLogin = $this->apikey."%".$this->login.":".$this->password;


            $this->apiPath = $this->apiPath.$this->login;


        }         


        


         /**


         * Method that returns a list with all states found in states.txt file


         * @return array with state codes and state names


            


         public function getStates() {


            $returnArr = array();


            $lines = file("states.txt");


            foreach ($lines as $line) {


                $tmp = explode(" - ", $line);      


                if (sizeof($tmp) == 2) {


                    $returnArr)] = trim($tmp);


                }


            }


            return $returnArr;


         }


*/ 


        /**


        * Returns a list with all countries found in countries.txt file


        * @return array with country codes and country names


            


        public function getCountries() {


            $returnArr = array();


            $lines = file("countries.txt");


            foreach ($lines as $line) {


                $tmp = explode(" - ", $line);            


                if (sizeof($tmp) == 2) {


                    $returnArr)] = trim($tmp);


                }


            }


            return $returnArr;


        } 


         */               


        /**


        * Validate an email address


        * @return  TRUE if address is valid and FALSE if not.


        */    


        protected function isValidEmail($email){


             return eregi("^+(\.+)*@+(\.+)*(\.{2,3})$", $email);


        } 


        


        /**


        * Private function used to send requests to ConstantContact server


        * @param string $request - is the URL where the request will be made


        * @param string $parameter - if it is not empty then this parameter will be sent using POST method


        * @param string $type - GET/POST/PUT/DELETE


        * @return a string containing server output/response


        */    


        protected function doServerCall($request, $parameter = '', $type = "GET") {


            $ch = curl_init();


            $request = str_replace('http://', 'https://', $request);


            // Convert id URI to BASIC compliant


            curl_setopt($ch, CURLOPT_URL, $request);


            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");


            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);


            curl_setopt($ch, CURLOPT_USERPWD, $this->requestLogin);


            # curl_setopt ($ch, CURLOPT_FOLLOWLOCATION  ,1);


            curl_setopt($ch, CURLOPT_HEADER, 0);


            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


            curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml", 'Content-Length: ' . strlen($parameter)));


            curl_setopt($ch, CURLOPT_FAILONERROR, 1);


            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);


            switch ($type) {


                case 'POST':                  


                    curl_setopt($ch, CURLOPT_POST, 1);


                    curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter);


                    break;


                case 'PUT':


                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");


                    curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter);


                    break;


                case 'DELETE':


                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");


                    break;


                default:


                    curl_setopt($ch, CURLOPT_HTTPGET, 1);


                    break;


            }


 


           $emessage = curl_exec($ch);          


           if ($this->curl_debug) {   echo $error = curl_error($ch);   }


           curl_close($ch);


           


           return $emessage;


        }


         


    }


 


    /**


    * Class that is used for retrieving 


    * all the Email Lists from Constant Contact and 


    * all Registered Email Addresses 


    */


    class CC_List extends CC_Utility {


        


        /**


        * Recursive Method that retrieves all the Email Lists from ConstantContact.


        * @param string $path


        * @return array of lists


        */    


        public function getLists($path = '') {


            $mailLists = array();


            


            if ( empty($path)) {


                $call = $this->apiPath.'/lists';


            } else {


                $call = $path;


            }


 


            $return = $this->doServerCall($call);


            $parsedReturn = simplexml_load_string($return);


            $call2 = '';


            


            foreach ($parsedReturn->link as $item) {


                $tmp = $item->Attributes();


                $nextUrl = '';      


                if ((string) $tmp->rel == 'next') {


                    $nextUrl = (string) $tmp->href;


                    $arrTmp = explode($this->login, $nextUrl);


                    $nextUrl = $arrTmp;


                    $call2 = $this->apiPath.$nextUrl;


                    break;


                  }


            }


 


            foreach ($parsedReturn->entry as $item) {


                if ($this->contact_lists ){


                if (in_array((string) $item->title, $this->contact_lists)) {


                    $tmp = array();


                    $tmp = (string) $item->id;


                    $tmp = (string) $item->title;


                    $mailLists[] = $tmp;


                   }


                } else if (!in_array((string) $item->title, $this->doNotIncludeLists)) {


                    $tmp = array();


                    $tmp = (string) $item->id;


                    $tmp = (string) $item->title;


                    $mailLists[] = $tmp;


                }


            }


          


            if ( empty($call2)) {


                return $mailLists;


            } else {


                return array_merge($mailLists, $this->getLists($call2));


            }


 


        }


        


        /**


        * Method that retrieves  all Registered Email Addresses.


        * @param string $email_id


        * @return array of lists


        */           


        public function getAccountLists($email_id = '') {        


            $mailAccountList = array();


            


            if ( empty($email_id)) {


                $call = $this->apiPath.'/settings/emailaddresses';


            } else {


                $call = $this->apiPath.'/settings/emailaddresses/'.$email_id; 


            }


 


            $return = $this->doServerCall($call);


            $parsedReturn = simplexml_load_string($return);


              


            foreach ($parsedReturn->entry as $item) {               


                $nextStatus = $item->content->Email->Status;


                $nextEmail = (string) $item->title;


                $nextId = $item->id; 


                $nextAccountList = array('Email'=>$nextEmail, 'Id'=>$nextId);


                if($nextStatus == 'Verified'){  


                    $mailAccountList[] = $nextAccountList; 


                }         


            }


            return $mailAccountList;


        }   


           


    }


    


    


    /**


    * Class that is used for ConstantConact CRUD management


    */


class CC_Contact extends CC_Utility {


 


    /**


     * Method that checks if a subscriber already exist


     * @param string $email


     * @return subscriber`s id if it exists or false if it doesn't


     */ 


public function subscriberExists($email = '') {


// $call = $this->apiPath.'/contacts?email='.$email;


// $return = $this->doServerCall($call);


// $xml = simplexml_load_string($return);


// $id = $xml->entry->id;


// if($id){ return $id; }


// else { return false; }


return false;


}


     


/**


     * Method that retrieves from Constant Contact a collection with all the Subscribers


     * If email parameter is mentioned then only mentioned contact is retrieved.


     * @param string $email


     * @return Bi-Dimenstional array with information about contacts.


     */    


public function getSubscribers($email = '', $page = '') {


$contacts = array();


$contacts = array();



if (! empty($email)) {


$call = $this->apiPath.'/contacts?email='.$email;


} else {


if (! empty($page)) {


$call = $this->apiPath.$page;


} else {


$call = $this->apiPath.'/contacts';


}


}


 


$return = $this->doServerCall($call);


$parsedReturn = simplexml_load_string($return);


// We parse here the link array to establish which are the next page and previous page


foreach ($parsedReturn->link as $item) {


$attributes = $item->Attributes();



if (! empty($attributes) && $attributes == 'next') {


$tmp = explode($this->login, $attributes);


$contacts = $tmp;


}


if (! empty($attributes) && $attributes == 'first') {


$tmp = explode($this->login, $attributes);


$contacts = $tmp;


}


if (! empty($attributes) && $attributes == 'current') {


$tmp = explode($this->login, $attributes);


$contacts = $tmp;


}


}


 


foreach ($parsedReturn->entry as $item) {


$tmp = array();


$tmp = (string) $item->id;


$tmp = (string) $item->title;


$tmp = (string) $item->content->Contact->Status;


$tmp = (string) $item->content->Contact->EmailAddress;


$tmp = (string) $item->content->Contact->EmailType;


$tmp = (string) $item->content->Contact->Name;


$contacts[] = $tmp;


}



return $contacts;


}


 


/**


     * Retrieves all the details for a specific contact identified by $email.


     * @param string $email


     * @return array with all information about the contact.


     */    


public function getSubscriberDetails($email) {


$contact = $this->getSubscribers($email);


$fullContact = array();


$call = str_replace('http://', 'https://', $contact);


// Convert id URI to BASIC compliant


$return = $this->doServerCall($call);


$parsedReturn = simplexml_load_string($return);


$fullContact = $parsedReturn->id;


$fullContact = $parsedReturn->content->Contact->EmailAddress;


$fullContact = $parsedReturn->content->Contact->FirstName;


$fullContact = $parsedReturn->content->Contact->LastName;


$fullContact = $parsedReturn->content->Contact->MiddleName;


$fullContact = $parsedReturn->content->Contact->CompanyName;


$fullContact = $parsedReturn->content->Contact->JobTitle;


$fullContact = $parsedReturn->content->Contact->HomePhone;


$fullContact = $parsedReturn->content->Contact->WorkPhone;


$fullContact = $parsedReturn->content->Contact->Addr1;


$fullContact = $parsedReturn->content->Contact->Addr2;


$fullContact = $parsedReturn->content->Contact->Addr3;


$fullContact = (string) $parsedReturn->content->Contact->City;


$fullContact = (string) $parsedReturn->content->Contact->StateCode;


$fullContact = (string) $parsedReturn->content->Contact->StateName;


$fullContact = $parsedReturn->content->Contact->CountryCode;


$fullContact = $parsedReturn->content->Contact->PostalCode;


$fullContact = $parsedReturn->content->Contact->SubPostalCode;


$fullContact = $parsedReturn->content->Contact->CustomField1;


$fullContact = $parsedReturn->content->Contact->CustomField2;


$fullContact = $parsedReturn->content->Contact->CustomField3;


$fullContact = $parsedReturn->content->Contact->CustomField4;


$fullContact = $parsedReturn->content->Contact->CustomField5;


$fullContact = $parsedReturn->content->Contact->CustomField6;


$fullContact = $parsedReturn->content->Contact->CustomField7;


$fullContact = $parsedReturn->content->Contact->CustomField8;


$fullContact = $parsedReturn->content->Contact->CustomField9;


$fullContact = $parsedReturn->content->Contact->CustomField10;


$fullContact = $parsedReturn->content->Contact->CustomField11;


$fullContact = $parsedReturn->content->Contact->CustomField12;


$fullContact = $parsedReturn->content->Contact->CustomField13;


$fullContact = $parsedReturn->content->Contact->CustomField14;


$fullContact = $parsedReturn->content->Contact->CustomField15;


$fullContact = $parsedReturn->content->Contact->Note;


$fullContact = $parsedReturn->content->Contact->EmailType;


$fullContact = $parsedReturn->content->Contact->Status;


$fullContact = array();



if ($parsedReturn->content->Contact->ContactLists->ContactList) {


foreach ($parsedReturn->content->Contact->ContactLists->ContactList as $item) {


$fullContact[] = trim((string) $item->Attributes());


}


}


 


return $fullContact;


}


 


/**


     * Method that modifies a contact State to DO NOT MAIL


     * @param string $email - contact email address


     * @return TRUE in case of success or FALSE otherwise


     */    


public function deleteSubscriber($email) {


if ( empty($email)) {  return false;   }


$contact = $this->getSubscribers($email);


$id = $contact;


$return = $this->doServerCall($id, '', 'DELETE');


if (! empty($return)) {  return false;  }


return true;


}


 


/**


     * Method that modifies a contact State to REMOVED


     * @param string $email - contact email address


     * @return TRUE in case of success or FALSE otherwise


     */    


public function removeSubscriber($email) {


$contact = $this->getSubscriberDetails($email);


$contact = array();


$xml = $this->createContactXML($contact, $contact);



if ($this->editSubscriber($contact, $xml)) {


return true;


} else {


return false;


}


}


 


/**


     * Upload a new contact to Constant Contact server


     * @param strong $contactXML - formatted XML with contact information


     * @return TRUE in case of success or FALSE otherwise


     */    


public function addSubscriber($contactXML) {


$call = $this->apiPath.'/contacts';


$return = $this->doServerCall($call, $contactXML, 'POST');


$parsedReturn = simplexml_load_string($return);


            


if ($return) {


return true;


} else {


$xml = simplexml_load_string($contactXML);


$emailAddress = $xml->content->Contact->EmailAddress;


if ($this->subscriberExists($emailAddress)){ 


$this->lastError = 'This contact already exists. <a href="edit_contact.php?email='.$emailAddress.'">Click here</a> to edit the contact details.'; 


} else { $this->lastError = 'An Error Occurred'; }


return false;


}


}


 


/**


     * Modifies a contact


     * @param string $contactUrl - identifies the url for the modified contact


     * @param string $contactXML - formed XML with contact information


     * @return TRUE in case of success or FALSE otherwise


     */    


public function editSubscriber($contactUrl, $contactXML) {


$return = $this->doServerCall($contactUrl, $contactXML, 'PUT');



if (! empty($return)) {      


if (strpos($return, '<') !== false) {                


$parsedReturn = simplexml_load_string($return);          


if (! empty($parsedReturn->message)) {


$this->lastError = $parsedReturn->message;


}  


} else {


$this->lastError = $parsedReturn->message;


}     


return false;


}      


return true;


}


 


/**


     * Method that compose the needed XML format for a contact


     * @param string $id


     * @param array $params


     * @return Formed XML


     */    


public function createContactXML($id, $params = array()) {


if ( empty($id)) {


$id = "urn:uuid:E8553C09F4xcvxCCC53F481214230867087";


}


 


$update_date = date("Y-m-d").'T'.date("H:i:s").'+01:00';


$xml_string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns='http://www.w3.org/2005/Atom'></entry>";


$xml_object = simplexml_load_string($xml_string);


$title_node = $xml_object->addChild("title", htmlspecialchars(("TitleNode"), ENT_QUOTES, 'UTF-8'));


$updated_node = $xml_object->addChild("updated", htmlspecialchars(($update_date), ENT_QUOTES, 'UTF-8'));


$author_node = $xml_object->addChild("author");


$author_name = $author_node->addChild("name", ("CTCT Samples"));


$id_node = $xml_object->addChild("id", htmlspecialchars(($id),ENT_QUOTES, 'UTF-8'));


$summary_node = $xml_object->addChild("summary", htmlspecialchars(("Customer document"),ENT_QUOTES, 'UTF-8'));


$summary_node->addAttribute("type", "text");


$content_node = $xml_object->addChild("content");


$content_node->addAttribute("type", "application/vnd.ctct+xml");


$contact_node = $content_node->addChild("Contact", htmlspecialchars(("Customer document"), ENT_QUOTES, 'UTF-8'));


$contact_node->addAttribute("xmlns", "http://ws.constantcontact.com/ns/1.0/");


$email_node = $contact_node->addChild("EmailAddress", htmlspecialchars(($params), ENT_QUOTES, 'UTF-8'));


$fname_node = $contact_node->addChild("FirstName", urldecode(htmlspecialchars(($params), ENT_QUOTES, 'UTF-8')));


$lname_node = $contact_node->addChild("LastName", urldecode(htmlspecialchars(($params), ENT_QUOTES, 'UTF-8')));


$lname_node = $contact_node->addChild("MiddleName", urldecode(htmlspecialchars(($params), ENT_QUOTES, 'UTF-8')));


$lname_node = $contact_node->addChild("CompanyName", urldecode(htmlspecialchars(($params), ENT_QUOTES, 'UTF-8')));


$lname_node = $contact_node->addChild("JobTitle", urldecode(htmlspecialchars(($params), ENT_QUOTES, 'UTF-8')));



if ($params == 'Do Not Mail') {


$this->actionBy = 'ACTION_BY_CONTACT';


}


 


$optin_node = $contact_node->addChild("OptInSource", htmlspecialchars($this->actionBy));


$hn_node = $contact_node->addChild("HomePhone", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$wn_node = $contact_node->addChild("WorkPhone", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$ad1_node = $contact_node->addChild("Addr1", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$ad2_node = $contact_node->addChild("Addr2", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$ad3_node = $contact_node->addChild("Addr3", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$city_node = $contact_node->addChild("City", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$state_node = $contact_node->addChild("StateCode", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$state_name = $contact_node->addChild("StateName", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$ctry_node = $contact_node->addChild("CountryCode", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$zip_node = $contact_node->addChild("PostalCode", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$subzip_node = $contact_node->addChild("SubPostalCode", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$note_node = $contact_node->addChild("Note", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


$emailtype_node = $contact_node->addChild("EmailType", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));



if (! empty($params)) {


foreach ($params as $k=>$v) {


$contact_node->addChild("CustomField".$k, htmlspecialchars(($v), ENT_QUOTES, 'UTF-8'));


}


}


 


$contactlists_node = $contact_node->addChild("ContactLists");


if ($params) {


foreach ($params as $tmp) {


$contactlist_node = $contactlists_node->addChild("ContactList");


$contactlist_node->addAttribute("id", $tmp);


}


}


 


$entry = $xml_object->asXML();


return $entry;


}


 


    }


 


 


   /**


    * Class that is used for ConstantCampaign CRUD management  


   */


    class CC_Campaign extends CC_Utility {  


    


       // set this to true to see the xml sent and the output received 


       var $sent_recived_debug = false;      


       var $usStates = array("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY");


       var $caStates = array("AB", "BC", "MB", "NB", "NL", "NT", "NS", "NU", "ON", "PE", "QC", "SK", "YT");


       var $armedForces = array("AA", "AE", "AP");     


       


       /**


       * Method that returns a html sample for email campaign


       * @param string $sample : EmailContent, EmailTextContent or  


       * PermissionReminder


       * @param string $type : html or text


       * @return a default content for email content or permission reminder


       */    


       public function getEmailIntro($sample = 'EmailContent', $type = 'html') {          


          switch($sample){


               case 'EmailContent':


                        $file = 'EmailContent.txt';


                        break;


               case 'EmailTextContent':


                        $file = 'EmailContent.txt';


                        $type = 'text';


                        break;


               case 'PermissionReminder':


                        $file = 'PermissionReminder.txt';


                        break;


               default:


                        $file = 'EmailContent.txt';


          } 


           


            $handle = fopen("txt/$file", "rb");


            $contents = '';


                while (!feof($handle)) {


                        $contents .= fread($handle, 8192);


                }           


            $contents = ($type == 'html') ? ($contents) : (trim(strip_tags($contents)));


            fclose($handle);


            return $contents;


       }    


        


     


        


     


     /**


     * Method that retrieves campaingn collections from ConstantCampaign


     * If campaign_id is mentioned then only mentioned campaign is retrieved.


     * If campaign_id represents a status


     * only the campaigns with that status will be retrieved


     * @param string $campaign_id  


     * @return Bi-Dimenstional array with information about campaigns.


     */    


     public function getCampaigns($campaign_id = '', $page = '') {         


            $campaigns = array();


            $campaigns = array();


            


            switch($campaign_id){


                  case 'SENT':


                  case 'DRAFT':


                  case 'RUNNING':


                  case 'SCHEDULED':


                       $call = $this->apiPath.'/campaigns?status='.$campaign_id;


                       break;


                  case 'ALL':


                       $call = (!empty($page)) ? ($this->apiPath.$page) : ($this->apiPath.'/campaigns');


                       break;


                  default:


                       $call = $this->apiPath.'/campaigns/'.$campaign_id;


            }


                       


            $return = $this->doServerCall($call);


            $parsedReturn = simplexml_load_string($return);


            //we parse here the link array to establish which are the next page and previous page


            if($parsedReturn != false){


                


            foreach ($parsedReturn->link as $item) {


                $attributes = $item->Attributes();


                if (! empty($attributes) && $attributes == 'next') {


                    $tmp = explode($this->login, $attributes);


                    $campaigns = $tmp;


                }              


                if (! empty($attributes) && $attributes == 'first') {


                    $tmp = explode($this->login, $attributes);


                    $campaigns = $tmp;


                }          


                if (! empty($attributes) && $attributes == 'current') {


                    $tmp = explode($this->login, $attributes);


                    $campaigns = $tmp;


                }


            }


                       


            foreach ($parsedReturn->entry as $item) {


                $tmp = array();


                $tmp = (string) $item->id;


                $tmp = (string) $item->title;


                $tmp = (string) $item->content->Campaign->Name;  


                $tmp = (string) $item->content->Campaign->Status;


                $timestamp = strtotime($item->content->Campaign->Date);


                $campaig_date = date("F j, Y, g:i a", $timestamp);


                $tmp = (string) $campaig_date;       


                $campaigns[] = $tmp;


              } 


                         


            }


            return $campaigns;


        }


      


 


     /**


     * Retrieves all the details for a specific campaign identified by $id.


     * @param string $id


     * @return array with all information about the campaign.


     */    


     public function getCampaignDetails($id) {       


     if (!empty($id)){      


            $fullContact = array();


            $call = str_replace('http://', 'https://', $id);


            // Convert id URI to BASIC compliant


            $return = $this->doServerCall($call);


            $parsedReturn = simplexml_load_string($return);


            $fullCampaign = $parsedReturn->id;


            $cmp_vars = get_object_vars($parsedReturn->content->Campaign);


            


            foreach ($cmp_vars as $var_name=>$cmp_item){


               $fullCampaign = $cmp_item;


            }


            


            $cmp_from_email = $parsedReturn->content->Campaign->FromEmail->EmailAddress;


            $fullCampaign = (string) $cmp_from_email; 


            $cmp_reply_email = $parsedReturn->content->Campaign->ReplyToEmail->EmailAddress;


            $fullCampaign = (string) $cmp_reply_email;   


            $fullCampaign = array();


           


            if ($parsedReturn->content->Campaign->ContactLists->ContactList) {


                foreach ($parsedReturn->content->Campaign->ContactLists->ContactList as $item) {


                    $fullCampaign[] = trim((string) $item->Attributes());


                }


            }               


              return $fullCampaign;


          }  else {


              return false;


          }


        }


        


     /**


     * Check if a specific campaign exist already


     * @param string $id


     * @param string $new_name


     * @return a boolean value.


     */      


     public function campaignExists($id = '', $new_name) {         


         if(!empty($id)) {


         $call = $this->apiPath.'/campaigns/'.$id;


         $return = $this->doServerCall($call);


         $xml = simplexml_load_string($return);


         if ($xml !== false) {


               $id = $xml->content->Campaign->Attributes(); 


               $id = $id;


               $name = $xml->content->Campaign->Name;  


            } else {


                $id = null;


                $name = null; 


            }


           $all_campaigns = $this->getCampaigns('ALL');


           $all_campaigns = $all_campaigns;


           foreach ($all_campaigns as $key=>$item) {


               if ($item == $new_name)  { 


                     return 1;  // 1 - the new campaign has a similar name with an old one


                     break;


               }


           }


           /**


            * 2 - this campaign already exist


            * 0 - this is a new campaign


           */


           return ($id != null) ? (2) : (0);


         }


 


     }        


        


 


     /**


     * Method that delete a camaign; this will exclude 


     * the removed campaign from overall statistics


     * @param string $id - campaign id


     * @return TRUE in case of success or FALSE otherwise


     */    


     public function deleteCampaign($id) {           


            if ( empty($id)) {  return false;  }


            $return = $this->doServerCall($id, '', 'DELETE');


            if (! empty($return) || $return === false) {  return false;  }


            return true;


        }


 


     /**


     * Upload a new campaign to ConstantContact server


     * @param string $campaignXML - formatted XML with campaign information


     * @return TRUE in case of success or FALSE otherwise


     */    


     public function addCampaign($campaignXML) {        


            $call = $this->apiPath.'/campaigns';


            $return = $this->doServerCall($call, $campaignXML, 'POST'); 


            $parsedReturn = simplexml_load_string($return);     


            if ($return) {


                return true;


            } else {


                $xml = simplexml_load_string($campaignXML);


                $cmp_id = $xml->content->Campaign->Attributes();


                $cmp_id = $cmp_id; 


                $cmp_name = $xml->content->Campaign->Name; 


             if(!empty($cmp_id)) {   


                 $search_status = $this->campaignExists($cmp_id, $cmp_name);           


                 switch($search_status){


                     case 0: 


                        $error = 'An Error Occurred. The campaign could not be added.';


                        break;


                     case 1:


                        $error = 'The name of the campaign already exist. Each campaign must have a distinct name.';


                        break;


                     case 2:


                        $error = 'This campaign already exists.';


                        break;


                     default:


                        $error = 'An Error Occurred. The campaign could not be added.';


                 }


                $this->lastError = $error;                         


              }  else {


                $this->lastError = 'An Error Occurred. The campaign could not be added.';  


              }


              return false; 


            }


 


        }


 


     /**


     * Modifies a campaign


     * @param string $campaignId - identifies the id for the modified campaign


     * @param string $campaignXML - formed XML with campaign information


     * @return TRUE in case of success or FALSE otherwise


     */    


     public function editCampaign($campaignId, $campaignXML) {


            $return = $this->doServerCall($campaignId, $campaignXML, 'PUT');        


            if ($return === false) {


                $this->lastError = 'An Error Occurred. The campaign could not be edited.'; 


                return false;


            } else {


            if (! empty($return)) {                


                if (strpos($return, '<') !== false) {


                    $parsedReturn = simplexml_load_string($return);                    


                    if (! empty($parsedReturn->message)) {


                        $this->lastError = $parsedReturn->message;


                    }


                } else {


                    $this->lastError = $parsedReturn->message;


                }


                return false;


            }


            return true;


         }


     }


     


     /**


     * Method that validate the current campaign before sending it to server


     * @param string $id


     * @param array $params


     * @return an error message or true


     */ 


     public function validateCampaign( $id, $params = array() ) {


         if( trim($params)== '' ) {


             $this->lastError = '<i>Campaign Name</i> is mandatory.'; 


             return true;


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>Subject</i> is mandatory.'; 


             return true;


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>From Name</i> is mandatory.'; 


             return true; 


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>From Email Address</i> is mandatory.'; 


             return true; 


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>Reply Email Address</i> is mandatory.'; 


             return true;


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>Greeting Name</i> is mandatory.'; 


             return true;                                  


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>Organization Name</i> is mandatory.'; 


             return true;


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>Address 1</i> is mandatory.'; 


             return true;


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>City</i> is mandatory.'; 


             return true;     


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>Zip/Postal Code</i> is mandatory.'; 


             return true; 


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>Country</i> is mandatory.'; 


             return true;                  


          } elseif( trim($params)== '' ) {


             $this->lastError = '<i>HTML Body</i> is mandatory.'; 


             return true; 


          } elseif ( $params == NULL ) {


             $this->lastError = 'Choose at least <i>one Campaign</i> from the list.'; 


             return true;                                                                   


          } else {


              if( trim($params)== 'YES') {


                    $reminder_text =  $params;


                    if(trim($reminder_text)== ''){  


                            $this->lastError = '<i>Permission Reminder</i> is required.'; 


                            return true;   


                    }


              } 


              if(trim($params) != '') {


                    if( trim($params)== 'us' ) {


                            if(trim($params) == '' ){


                                $this->lastError = '<i>State</i> is mandatory.'; 


                                return true;    


                            } 


                            if ( in_array($params, $this->caStates) ) {


                                $this->lastError = '<i>US State</i> is required.'; 


                                return true; 


                            }


                    } elseif( trim($params)== 'ca' ) {


                            if(trim($params) == '' ){


                                $this->lastError = '<i>State</i> is mandatory.'; 


                                return true;    


                            } 


                            if ( in_array($params, $this->usStates) ) {


                                $this->lastError = '<i>CA State</i> is required.'; 


                                return true; 


                            }


                    } 


              }


              if( trim($params)== 'YES' ) {


                    if(trim($params)== ''){


                            $this->lastError = '<i>Webpage Text</i> is required.'; 


                            return true;   


                    }  


                    if(trim($params)== ''){


                            $this->lastError = '<i>Webpage Link Text</i> is required.'; 


                            return true;   


                    }


              }


              if( trim($params)== 'YES') {


                    $fwd_email =  $params;


                    if(trim($params)== ''){  


                            $this->lastError = '<i>Forward email</i> is required.'; 


                            return true;   


                    }


              }      


              if( trim($params)== 'YES') {


                    if(trim($params)== ''){


                            $this->lastError = '<i>Subscribe me</i> is required.'; 


                            return true;   


                    }            


              } 


              else {        return false;        }


          }


     }


    


     


     /**


     * Method that compose the needed XML format for a campaign


     * @param string $id


     * @param array $params


     * @return Formed XML


     */    


          public function createCampaignXML( $id, $params = array() ) {  


            if (empty($id)) {  // Add a new Campaign


                $id = str_replace('https://', 'http://', $this->apiPath."/campaigns/1100546096289");


                $standard_id = str_replace('https://', 'http://', $this->apiPath."/campaigns"); 


            } else {


                $standard_id = $id;


            }


            $href = str_replace("http://api.constantcontact.com", "", $id);            


            $standard_href = str_replace("https://api.constantcontact.com", "", $this->apiPath."/campaigns");               $update_date = date("Y-m-d").'T'.date("H:i:s").'+01:00';


            $xml_string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns='http://www.w3.org/2005/Atom'></entry>";


            $xml_object = simplexml_load_string($xml_string);


            $link_node = $xml_object->addChild("link");


            $link_node->addAttribute("href", $standard_href); // 


            $link_node->addAttribute("rel", "edit");            


            $id_node = $xml_object->addChild("id", $standard_id);  // 


            $title_node = $xml_object->addChild("title", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


            $title_node->addAttribute("type", "text"); 


            $updated_node = $xml_object->addChild("updated", htmlentities($update_date));


            $author_node = $xml_object->addChild("author");


            $author_name = $author_node->addChild("name", htmlentities("Constant Contact"));           


            $content_node = $xml_object->addChild("content");


            $content_node->addAttribute("type", "application/vnd.ctct+xml");


            $campaign_node = $content_node->addChild("Campaign");


            $campaign_node->addAttribute("xmlns", "http://ws.constantcontact.com/ns/1.0/");


            $campaign_node->addAttribute("id", $id);  //


            $name_node = $campaign_node->addChild("Name", urldecode(htmlspecialchars($params, ENT_QUOTES, 'UTF-8')));


            $campaign_status =  !empty($params) ? ($params) : ('Draft');


            $status_node = $campaign_node->addChild("Status", urldecode(htmlentities($campaign_status)));


            $campaign_date = !empty($params) ? ($params) : ($update_date);


            $date_node = $campaign_node->addChild("Date", urldecode(htmlentities($campaign_date)));


            $subj_node = $campaign_node->addChild("Subject", urldecode(htmlspecialchars($params, ENT_QUOTES, 'UTF-8')));


            $from_name_node = $campaign_node->addChild("FromName", urldecode(htmlspecialchars($params, ENT_QUOTES, 'UTF-8')));


            $view_as_webpage = (!empty($params) &&  $params == 'YES') ? ('YES') : ('NO');


            $as_webpage_node = $campaign_node->addChild("ViewAsWebpage", urldecode(htmlentities($view_as_webpage)));


            #$as_web_lnk_txt = ($view_as_webpage == 'YES') ? ($params) : ('');


            $as_web_lnk_txt = $params; 


            $as_weblink_node = $campaign_node->addChild("ViewAsWebpageLinkText", urldecode(htmlspecialchars(($as_web_lnk_txt), ENT_QUOTES, 'UTF-8')));


            #$as_web_txt = ($view_as_webpage == 'YES') ? ($params) : ('');


            $as_web_txt = $params;


            $as_webtxt_node = $campaign_node->addChild("ViewAsWebpageText", urldecode(htmlspecialchars(($as_web_txt), ENT_QUOTES, 'UTF-8')));


            $perm_reminder_node = $campaign_node->addChild("PermissionReminder", urldecode(htmlentities($params)));


            $permission_reminder_text = ($params == 'YES') ? ($params) : ('');     


            $text_reminder_node = $campaign_node->addChild("PermissionReminderText", urldecode(htmlspecialchars(($permission_reminder_text), ENT_QUOTES, 'UTF-8')));


            $grt_sal_node = $campaign_node->addChild("GreetingSalutation", htmlspecialchars(($params), ENT_QUOTES, 'UTF-8'));


            $grt_name_node = $campaign_node->addChild("GreetingName", htmlentities($params));


            $grt_str_node = $campaign_node->addChild("GreetingString", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


            $org_name_node = $campaign_node->addChild("OrganizationName", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


            $org_addr1_node = $campaign_node->addChild("OrganizationAddress1", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


            $org_addr2_node = $campaign_node->addChild("OrganizationAddress2", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


            $org_addr3_node = $campaign_node->addChild("OrganizationAddress3", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


            $org_city_node = $campaign_node->addChild("OrganizationCity", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


            switch($params){


                case 'us':


                $us_state = $params;


                break;


                case 'ca':


                $us_state = $params;  


                break;


                default:


                $us_state = '';                


            }


            $org_state_us_node = $campaign_node->addChild("OrganizationState", htmlentities($us_state));


            switch($params){


                case 'us':


                $international_state = '';


                break;


                case 'ca':


                $international_state = '';  


                break;


                default:


                $international_state = htmlspecialchars($params, ENT_QUOTES, 'UTF-8');


            }


            $org_state_name = $campaign_node->addChild("OrganizationInternationalState", htmlentities($international_state));


            $org_country_node = $campaign_node->addChild("OrganizationCountry", htmlentities($params));


            $org_zip_node = $campaign_node->addChild("OrganizationPostalCode", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));


            $include_fwd_email = (!empty($params) && $params == 'YES') ? ('YES') : ('NO');


            #$fwd_txt = ($include_fwd_email == 'YES') ? ($params) :('');


            $fwd_txt = $params;  


            $fwd_node = $campaign_node->addChild("IncludeForwardEmail", htmlentities($include_fwd_email));


            $fwd_email_node = $campaign_node->addChild("ForwardEmailLinkText", htmlspecialchars(($fwd_txt), ENT_QUOTES, 'UTF-8'));


            $include_sub_link = (!empty($params) && $params == 'YES') ? ('YES') : ('NO');                          


            $sub_node = $campaign_node->addChild("IncludeSubscribeLink", htmlentities($include_sub_link));


            #$sub_txt = ($include_sub_link == 'YES') ? ($params) : ('');


            $sub_txt = $params;


            $sub_link_node = $campaign_node->addChild("SubscribeLinkText", htmlspecialchars(($sub_txt), ENT_QUOTES, 'UTF-8'));


            $email_format_node = $campaign_node->addChild("EmailContentFormat", $params);      


            if($params != 'STOCK'){


            $html_body_node = $campaign_node->addChild("EmailContent", htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));     


            $text_body_node = $campaign_node->addChild("EmailTextContent", "<Text>".htmlspecialchars(strip_tags($params), ENT_QUOTES, 'UTF-8')."</Text>");  


            $campaign_style_sheet = ($params == 'XHTML') ? ($params) : (''); 


            $style_sheet_node = $campaign_node->addChild("StyleSheet", htmlspecialchars($campaign_style_sheet, ENT_QUOTES, 'UTF-8'));         


            }


            $campaignlists_node = $campaign_node->addChild("ContactLists"); 


                              


            if ($params) {


                foreach ($params as $list) {


                    $campaignlist_node = $campaignlists_node->addChild("ContactList");


                    $campaignlist_node->addAttribute("id", $list);


                    $campaignlink_node = $campaignlist_node->addChild("link");


                    $campaignlink_node->addAttribute("xmlns", "http://www.w3.org/2005/Atom");


                    $campaignlink_node->addAttribute("href", str_replace("http://api.constantcontact.com", "", $list)); 


                    $campaignlink_node->addAttribute("rel", "self"); 


                }


            }


            


            $cmp_from_email = explode('|',$params);


            $fromemail_node = $campaign_node->addChild("FromEmail");


            $femail_node = $fromemail_node->addChild("Email");


            $femail_node->addAttribute("id", $cmp_from_email);


            $femail_node_link = $femail_node->addChild("link");


            $femail_node_link->addAttribute("xmlns", "http://www.w3.org/2005/Atom");


            $femail_node_link->addAttribute("href", str_replace("http://api.constantcontact.com", "", $cmp_from_email)); 


            $femail_node_link->addAttribute("rel", "self");     


            $femail_addrs_node = $fromemail_node->addChild("EmailAddress", htmlentities($cmp_from_email));               $cmp_reply_email = explode('|',$params); 


            $replyemail_node = $campaign_node->addChild("ReplyToEmail"); 


            $remail_node = $replyemail_node->addChild("Email");


            $remail_node->addAttribute("id", $cmp_reply_email);


            $remail_node_link = $remail_node->addChild("link");


            $remail_node_link->addAttribute("xmlns", "http://www.w3.org/2005/Atom");


            $remail_node_link->addAttribute("href", str_replace("http://api.constantcontact.com", "", $cmp_reply_email));


            $remail_node_link->addAttribute("rel", "self");        


            $remail_addrs_node = $replyemail_node->addChild("EmailAddress", htmlentities($cmp_reply_email));             $source_node = $xml_object->addChild("source");  


            $sourceid_node = $source_node->addChild("id", $standard_id);  //


            $sourcetitle_node = $source_node->addChild("title", "Campaigns for customer: ".$this->login);


            $sourcetitle_node->addAttribute("type", "text");


            $sourcelink1_node = $source_node->addChild("link");


            $sourcelink1_node->addAttribute("href", "campaigns");  //


            $sourcelink2_node = $source_node->addChild("link");


            $sourcelink2_node->addAttribute("href", "campaigns");  //


            $sourcelink2_node->addAttribute("rel", "self"); 


            $sourceauthor_node = $source_node->addChild("author"); 


            $sauthor_name = $sourceauthor_node->addChild("name", $this->login);


            $sourceupdate_node = $source_node->addChild("updated", htmlentities($update_date));  


            


            $entry = $xml_object->asXML();


            $search  = array('&gt;', '\"', ' ', ' ', '"/>', '&', '&amp;lt;', '?', '?');


            $replace = array('>', '"', '', '', '" />', '&amp;', '&lt;', '&amp;Yuml;', '&amp;yuml;');


            $entry = str_replace($search, $replace, $entry);


            


            if( $this->sent_recived_debug ) {


                echo "<div><p style=\"color: blue\">We sent the following XML:</p>  $entry  </div><hr/>";


            }


            


            return $entry;


        }


 


}


 


 


 


$ccContactOBJ = new CC_Contact();


$ccListOBJ = new CC_List(); 


//if we have post fields means that the form have been submitted.



if (!empty($_POST)) {


///


///


$postFields = array();


$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


//$postFields = $_POST;


//$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


// The Code is looking for a State Code For Example TX instead of Texas


$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


$postFields = $_POST;


$contactXML = $ccContactOBJ->createContactXML(null,$postFields);


 


if (!$ccContactOBJ->addSubscriber($contactXML)) {


$error = true;


} else {


$error = false;


$_POST = array();


}



 


 


}


 



if(!$_POST){


$_POST = urldecode(trim($_GET));


}


 


//get all available lists for the current CC account.


$allLists = $ccListOBJ->getLists();


//get all available states


//$allStates = $ccContactOBJ->getStates();


//get all available countries


//$allCountries = $ccContactOBJ->getCountries();


?>


 


<div>


 


<?php 


//


// Here we add an area where messages  are displayed (error or success messages).


//



if (isset($error)) {



if ($error === true) {


$class = "go-green-error";


$message = $ccContactOBJ->lastError;


} else {


$class = "success";


$message = "<div id='go-green-success'><h4>Success. Your email address ".htmlspecialchars($postFields, ENT_QUOTES, 'UTF-8')." has been added.</h4><p><a href=''>Download your coupon.</a><p/> ";


}


 


echo '<div class="'.$class.'">';


echo $message;


echo '</div>';


}


 


?>


<form action="" method="post">


 



<?php 


if($ccContactOBJ->contact_lists && !$ccContactOBJ->show_contact_lists && $ccContactOBJ->force_lists){


foreach ($allLists as $k=>$item) {


echo '<input type="hidden" name="lists[]" value="'.$item.'" id="chk_'.$k.'" />';


}


} else {


?>


 


 


<?php } ?>


 


 


 


 


<div id="go-green">


<fieldset>


<legend>Your Contact Details</legend>


<ul>


<li>


<label for="go-green-email">Email:</label>


<input type="text" id ="go-green-email" name="email_address" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" />


</li>


<li>


<label for="go-green-fn">First Name:</label>


<input type="text" id="go-green-fn" name="first_name" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" />


</li>


<li>


<label for="go-green-fn">Last Name:</label>


<input type="text" id="go-green-ln" name="last_name"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" />


</li>


</ul>


</fieldset>


<fieldset>


<legend>Your Mailing Address</legend>


<ul>


<li>


<label for="ard1">Address:</label>


<input type="text" id="adr1" name="adr_1" class="go-green-adr" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" />


</li>


<li>


 


<li>


<label for="go-green-city">City:</label>


<input type="text" id ="go-green-city" name="city" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" />


</li>


<li>


<label for="go-green-state">State:</label>


<input type="text" id="go-green-state" name="state_name" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>"/>


</li>


<li>


<label for="go-green-zip">Zip Code:</label>


<input type="text" id="go-green-zip" name="postal_code" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>"/>


<li>


</ul>


</fieldset>


<!--<input type="submit" id="go-green-submit" name="submit" value="GO GREEN" /> -->


<input type="image" id="go-green-submit" name="submit" src="http://www.mydbsupply.com/userfiles/image/go-green-btn-080310.png" alt="Go Green, Submit Button">


 


 


</div>


 


 


</form>


</div>


 


<div id="go-green-mess">


<h2>Going Green</h2>


<p>If you get our promotional flyers by mail, we'd like you to consider switching to email. We'll reward you for the move with a $10 off of a $50 purchase coupon.


</p>


<p>


Complete this form to receive your coupon.


</p>


</div>


 


 

19 REPLIES 19
Highlighted
Employee

Updating a Contact

Hello,



In order to add a contact that already exists to a new list, you would want to do a PUT call to the Contact Collection API, with the Contact XML that is updated to have the new list on it. You can find a sample of the contact XML here.



If you have any further questions please let me know.



Regards,

Benjamin Soder
NOC Analyst
Constant Contact
Highlighted
Occasional Participant

Thought I already did

Ben,


Thanks, I thought I already used a 'PUT' call in editSubscriber().


A.

Highlighted
Occasional Participant

Updated addSubscriber()

Ben,


I updated addSubscriber() as follows. Still no love. Am I on the proper track here?


 


     public    function addSubscriber($contactXML) {

            $call = $this->apiPath.'/contacts';

            $return = $this->doServerCall($call, $contactXML, 'POST');

            $parsedReturn = simplexml_load_string($return);   

               

            if ($return) {

                return true;

            } else {

                $xml = simplexml_load_string($contactXML);

                $emailAddress = $xml->content->Contact->EmailAddress;

                $cont_id = $xml->content->Contact->Id;

                if ($this->subscriberExists($emailAddress)){

                //$this->lastError = 'This contact already exists. ';

                    $put_call = $call . $cont_id;

                    $return = $this->doServerCall($put_call, $contactXML, 'PUT');

               

                } else { $this->lastError = 'An Error Occurred'; }

                return false;

            }

        }

Highlighted
Employee

Re: Updated addSubscriber()

You certainly have the right idea here. I had to make a few tweeks, but I believe I was able to get the functionality that you are looking for:


        public function addOrUpdate($contactInfo) {

            if (!$this->subscriberExists($contactInfo)) {

                $newContactXML = $this->createContactXML(null,$contactInfo);

                $postReturn = $this->addSubscriber($newContactXML);

                return $postReturn;

            } else {

                $currentDetails = $this->getSubscriberDetails($contactInfo);

                $contactInfo = $currentDetails;

                $updateXml = $this->createContactXML($contactInfo, $contactInfo);               

                $putReturn = $this->editSubscriber($contactInfo, $updateXml);

                return $putReturn;

                }

        }


This function will check to see if a subscriber exists. If it does not, it will create a new subscriber using the information in the 'ContactInfo' array argument. If the contact does exist, it will get the contacts ID, and then update the rest of their information with what you've included in that array. Please note that this function will update a contact with whatever values are in the $contactInfo array. If you have a first name "Joe" stored in Constant Contact, and you use this function and $contactInfo is not set, the contact will have their first name removed.


 


I hope this helps. Please let us know if you have any other questions.

David J

Highlighted
New Member

Add contact to a list even though they are in another list

We are trying to add a contact to a list using the API.  If the contact is in another seperate list the API returns this message:


 


"This contact already exists. Click here to edit the contact details."


 


When they click the Click Here link it brings them to a page that displays all the other lists in my account.  Is there a way to add a contact to a list even if they are in another list automatically without displaying this message and requiring the contact to click the link and manually manage their subscription.  We do not want to update the contacts existing information with blank data if nothing is provided like the sample code above does.


 


Thanks in advance!

Highlighted
Employee

re: updating a contact

Hello,



What you are looking to do is definetly possible while using our API's; however, it is currently not implented into the sample codes. The way this would work is that when someone puts their email address into your form, it would do the normal POST to your account, adding them if they are a new customer.



If they are not a new customer, our API servers respond to the script with a 409 error. In the code that you are using, this automatically triggers the script to direct them to a new page that gives them that message and allows them to update their profile.



What you would need to have changed is that instead of doing that, it would then do a PUT call to the API servers, adding them to the list.



I am not sure which scripting language you are using to program your site, such as PHP or ASP.NET, but if you are familiar with this, or have someone who is, they should be able to add this functionality. This documentation goes into it in detail.



If you do not have anyone with the ability to do this, we would recommend trying out the Constant Contact Marketplace, which is a listing of 3rd party developers and companies who have expressed interest in working with customers to better integrate with Constant Contact.



If you have any further questions regarding this please let me know and I will definetly try to help you further.



Regards,

Benjamin Soder
NOC Analyst
Constant Contact
Highlighted
New Member

Am I on the right track?

Ben,


Thanks for the fast response and information.  I know a little about PHP and have been working on this so any guidance with this I really appreciate :).


I just want to make sure I'm on the right path here.  This is some of the code (the relevant code) from the page that contains the form that submits information to an "RSVP" list that we would like to populate even though the user is in another list in the account.


 


The form contains this hidden field ({username} is replaced with the real username of the account):

<input type="hidden" name="lists[]" value="http://api.constantcontact.com/ws/customers/{username}/lists/18"/>


 


When they fill in their email address it posts to this PHP code (I know I can remove alot of the extra fields that aren't being used but I left them in there so it's one last thing to troubleshootuntil I get it to function properly):

<?php

header('Content-Type: text/html; charset=UTF-8');

include_once('cc_class.php');

$ccContactOBJ = new CC_Contact();

$ccListOBJ = new CC_List();

/**

 * If we have post fields means that the form have been submitted.

 * Therefore we start submiting inserted data to ConstantContact Server.

 */

    if (!empty($_POST)) {

        $postFields = array();

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields= $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        // The Code is looking for a State Code For Example TX instead of Texas

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = array();

        foreach($_POST as $key=>$val) {

           

            if (strncmp($key, 'custom_field_', strlen('custom_field_')) === 0) {

                $postFields = $val;

            }



        }



        $contactXML = $ccContactOBJ->createContactXML(null,$postFields);

       

        if (!$ccContactOBJ->addSubscriber($contactXML)) {

            $error = true;

        } else {

            $error = false;

            $_POST = array();

        }



    }





    //get all available lists for the current CC account.

    $allLists = $ccListOBJ->getLists();

    //get all available states

    $allStates = $ccContactOBJ->getStates();

    //get all available countries

    $allCountries = $ccContactOBJ->getCountries();

    ?>


 


Now I'm guessing that next I need to check and see if the message that comes up for the error is "This contact already exists. Click here to edit the contact details." and if it is I need to update with the PUT command?  Am I on the right track and is the code I'm using so far correct?  I'm a little unsure how to post the XML back after the error message above is confirmed.


 


Thanks again for all your help!


 


Best,

Anthony

Highlighted
Occasional Participant

addOrUpdate function - add existing subscriber to new list

David:


I found your new addOrUpdate function, but how can it be called from the basic add_contact.php sample form?


In a way similar to the addSubscriber or editSubscriber functions?  But I saw the addOrUpdate function uses the array of postfields instead of $contactXML, so I am confused...


Would something like this work? (assuming the addOrUpdate function was in the cc_class.php file, similar to the addSubscriber and editSubscriber functions)


$postFields = array();

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

        $postFields = $_POST;

...



$contactXML = $ccOBJ->createContactXML(null,$postFields);



        if (!$ccOBJ->addOrUpdate($contactXML)) {

            $error = true;

        } else {

            $error = false;

            $_POST = array();

        }


Many thanks!

- Zach

kleankanteen


 

Highlighted
Occasional Participant

updating contact - Contact Already Exists

I try to remove a contact from lists and add to another list, but I just get "Contact Already Exists".

Is something wrong with that code below:


<entry xmlns="http://www.w3.org/2005/Atom">

<id>https://api.constantcontact.com/ws/customers//contacts/101</id>

<title type="text">Contact: </title>

<updated>2010-09-15T14:57:13Z</updated>

<author></author>

<content type="application/vnd.ctct+xml">

<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="https://api.constantcontact.com/ws/customers//contacts/101">

<EmailAddress></EmailAddress>

<OptInSource>ACTION_BY_CONTACT</OptInSource>

<ContactLists>

<ContactList id="https://api.constantcontact.com/ws/customers//lists/10" />

</ContactLists>

</Contact>

</content>

</entry>

 

Developer Portal

View API documentation, code samples, get your API key.

Visit Page

Constant Contact 2020 End of Summer Community Sweepstakes!

The Constant Contact User Community is hosting a sweepstakes. The more you participate, the more chances you have to win! Read on to learn more...

Read More
Featured