Adding a Contact that already exists to an new list

dbsupply
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
bsoder
Employee

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
dbsupply
Occasional Participant

Ben,


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


A.

dbsupply
Occasional Participant

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;

            }

        }

David_J
Employee

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

tremors
Occasional Participant

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!

bsoder
Employee

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
tremors
Occasional Participant

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

kleankan
Regular Participant

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


 

laurent
Regular Participant

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>

 

David_J
Employee

Hi Zach,


 


The addOrUpdate() function that I wrote will write the XML for you, as the createContactXml() function needs to be passed the contact id of a contact that is being update, whereas a brand new contact would not have an id. You would need to add the addOrUpdate() function to the CC_Contact class, and then implement it into the add_contact.php by replacing the call to the createContactXML function below:


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

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

            $error = true;

        } else {

            $error = false;

            $_POST = array();

        }


with the addOrUpdate() function:


$response = $ccContactOBJ->addOrUpdate($postFields);


Hope this was helpful. Please let me know if you're running into any further issues with this. Thanks!

David J

David_J
Employee

If a contact already exists in your account, you would need to perform an http put to update that contact, as creating a new contact would result in the error you are seeing 'Contact Already Exists'. You can find more information about this in Updating Contact Information.


 


The best method to do this would be to obtain that contacts information, and then modify the elements in the <ContactLists> node to reflect which lists you wish for them to be subscribed to, then perform an http put to that contacts url (ie: https://api.constantcontact.com/ws/customers/{user-name}/contacts/{contact-id}). This way you can make sure that no other pieces of contact information are inadvertently altered, as well as making sure the XML remains in the correct format to avoid any 400 errors.


 


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


 

David J

iamkeir
Occasional Participant

$this->lastError = 'An Error Occurred' seems to have snuck into the current PHP API class... and is the most unhelpful error output imaginable! Does anybody know how to obtain more info about the 'error' that has occurred?

kleankan
Regular Participant

Thanks David. I tried what you suggested, but still having problems...

Fatal error: Call to a member function addOrUpdate() on a non-object on line 32


I added this to the cc_class.php:


        public function addOrUpdate($postFields) {

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

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

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

                return $postReturn;

            } else {

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

                $postFields = $currentDetails;

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

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

                return $putReturn;

                }

        }


And this is the code I have on the add_contact.php form page:


<?php

include_once('cc_class.php');

$ccOBJ = new ConstantContact();

//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;

        // 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 = array();

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

           

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

                $postFields = $val;

            }



        }

       $response = $ccContactOBJ->addOrUpdate($postFields);

    }

    if(!$_POST){

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

    }

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

    $allLists = $ccOBJ->getLists();

    //get all available states

    $allStates = $ccOBJ->getStates();

    //get all available countries

    $allCountries = $ccOBJ->getCountries();

    ?>


Any other suggestions?!! Thanks so much...


Zach

David_J
Employee

It looks like you are missing the form elements on this page, as well as trying to call the CC_List and CC_Contact classes from $ccOBJ. If you have made modifications to cc_class, this would certianly effect how this solution will work. With that being said, you are really just looking to pass all the entire postFields array (once you have added your values from whatever form you are using) to the addOrUpdate function.


 


I have taken the add_contact page from its original state, and added this functionality in. I hope this helps. Let me know if this works for you?


<?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;

            }



        }



        $response = $ccContactOBJ->addOrUpdate($postFields);



    }





    //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();

    ?>

<?php  include_once('header.php'); ?>

<div align="center" style="width: 900px;">

<h2>Add a new Subscriber - Full form</h2>

<?php

    //

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

    //

   

    if (isset($error)) {

       

        if ($error === true) {

            $class = "error";

            $message = $ccContactOBJ->lastError;

        } else {

            $class = "success";

            $message = "Contact ".htmlspecialchars($postFields, ENT_QUOTES, 'UTF-8')." Added.";

        }



        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 {

?>



<div style="float: right; text-align: left; overflow: auto; height: 640px; width:250px;">

    <fieldset>

        <legend> Interests list </legend>

    <?php

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

        $checked = '';



        if($_POST){   

            if (in_array($item,$_POST)) {

                $checked = ' checked ';

            }

        }

       

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

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

        }

        else {   

            echo '<input type="checkbox" '.$checked . $disabled .' class="checkbox" name="lists[]" value="'.$item.'" id="chk_'.$k.'" /> <label for="chk_'.$k.'">'.$item.'</label><br/>';

        }



    }

    ?>       

    </fieldset>

</div>

<?php } ?>



<div>

    <h3>Contact information</h3>   

    <table width="580" border="0" cellpadding="2" cellspacing="0">

        <tr>

            <td align="left">Email Address:</td>

            <td align="left"><input type="text" name="email_address" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" maxLength="80" /></td>

            <td align="left">&nbsp;</td>

              <td align="left">&nbsp;</td>

      </tr>

        <tr>

            <td align="left">First Name:</td>

            <td align="left"><input type="text" name="first_name" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Last Name:</td>

            <td align="left"><input type="text" name="last_name" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Middle Name:</td>

            <td align="left"><input type="text" name="middle_name" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Home phone:</td>

            <td align="left"><input type="text" name="home_num" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left" valign="top">Address:</td>

            <td align="left" colspan="3">

                <input type="text" name="adr_1" maxLength="50" style="width: 440px"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /><br/>

                <input type="text" name="adr_2" maxLength="50" style="width: 440px" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /><br/>

                <input type="text" name="adr_3" maxLength="50" style="width: 440px" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /><br/>

            </td>

        </tr>

        <tr>

            <td align="left">City:</td>

            <td align="left"><input type="text" name="city" maxLength="50  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">State:</td>

            <td align="left">

                <select name="state">

                <option value="">&nbsp;</option>

                <?php

    foreach ($allStates as $stateCode=>$stateName) {

        $selected = '';

       

        if ($stateCode == $_POST) {

            $selected = ' selected ';

        }



        echo '<option value="'.$stateCode.'" '.$selected.'>'.$stateName.'</option>';

    }



    ?>

                </select>

            </td>

        </tr>

        <tr>

            <td align="left">Zip:</td>

            <td align="left"><input type="text" name="postal_code" maxLength="25" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>"/></td>

            <td align="left">State (Other):</td>

            <td align="left"><input type="text" name="state_name" maxLength="50" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>"/></td>

        </tr>

        <tr>

            <td align="left">Sub-zip:</td>

            <td align="left"><input type="text" name="sub_postal" maxLength="25" value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>"/></td>

            <td align="left">Country:</td>

            <td align="left">

            <select name="country" maxLength="50">

                <option value="">&nbsp;</option>

            <?php

    foreach ($allCountries as $countryCode=>$countryName) {

        $selected = '';

       

        if ($countryCode == $_POST) {

            $selected = ' selected ';

        }



        echo '<option value="'.$countryCode.'" '.$selected.'>'.$countryName.'</option>';

    }



    ?>

            </select>

            </td>

            <td colspan="2"></td>

        </tr>

        <tr>

            <td align="left">E-Mail Type:</td>

            <td align="left" colspan="3">

                <input type="radio" class="checkbox" name="mail_type" id="mt1" value="HTML" <?php

    echo ($_POST=='HTML' || empty($_POST))?' checked ':

    '';

    ?> />

                <label for="mt1">HTML</label>

                &nbsp;or&nbsp;

                <input type="radio" class="checkbox" name="mail_type" id="mt2" value="Text" <?php

    echo ($_POST=='Text')?' checked ':

    '';

    ?> />

                <label for="mt2">Text</label>

            </td>           

        </tr>

    </table>

    <h3>Work details</h3>

    <table width="580" border="0" cellpadding="2" cellspacing="0">

        <tr>

            <td align="left">Company Name:</td>

            <td align="left"><input type="text" name="company_name" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Job Title:</td>

            <td align="left"><input type="text" name="job_title" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Work phone:</td>

            <td align="left"><input type="text" name="wrk_num" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td colspan="2"></td>

        </tr>

    </table>

    <h3>Custom Fields &amp; Notes</h3>

    <table width="580" border="0" cellpadding="2" cellspacing="0">

        <tr>

            <td align="left">Custom Field 1:</td>

            <td align="left"><input type="text" name="custom_field_1" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Custom Field 2:</td>

            <td align="left"><input type="text" name="custom_field_2" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Custom Field 3:</td>

            <td align="left"><input type="text" name="custom_field_3" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Custom Field 4:</td>

            <td align="left"><input type="text" name="custom_field_4" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Custom Field 5:</td>

            <td align="left"><input type="text" name="custom_field_5" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Custom Field 6:</td>

            <td align="left"><input type="text" name="custom_field_6" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Custom Field 7:</td>

            <td align="left"><input type="text" name="custom_field_7" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Custom Field 8:</td>

            <td align="left"><input type="text" name="custom_field_8" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Custom Field 9:</td>

            <td align="left"><input type="text" name="custom_field_9" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Custom Field 10:</td>

            <td align="left"><input type="text" name="custom_field_10" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Custom Field 11:</td>

            <td align="left"><input type="text" name="custom_field_11" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Custom Field 12:</td>

            <td align="left"><input type="text" name="custom_field_12" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Custom Field 13:</td>

            <td align="left"><input type="text" name="custom_field_13" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left">Custom Field 14:</td>

            <td align="left"><input type="text" name="custom_field_14" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

        </tr>

        <tr>

            <td align="left">Custom Field 15:</td>

            <td align="left"><input type="text" name="custom_field_15" maxLength="50"  value="<?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?>" /></td>

            <td align="left"></td>

            <td align="left"></td>

        </tr>

        <tr>

            <td align="left">Notes:</td>

            <td align="left" colspan="3">

            <textarea rows="10" cols="50" name="notes"><?php  echo htmlspecialchars($_POST, ENT_QUOTES, 'UTF-8') ?></textarea>

            </td>

        </tr>

        <tr>

            <td align="center" colspan="4">                 

                <input type="submit" name="submit" value="Add Contact" />

            </td>

        </tr>

    </table>

</div>

</form>

</div>

<?php include_once('footer.php'); ?>

David J

kleankan
Regular Participant

Ahh.. I see the problem finally.


I was not missing forms or fields, just didn't include them in my original post.


But I think I had an older version of the cc_class.php file, downloaded 4-6 months ago, didn't realize it had changed.So I just got the recent one, and will fix the classes and code on my site. I see the $ccContactOBJ and $ccListOBJ


How often does the cc_class change? I have it used in several places on our web site, and several web forms that utilize it.




Thanks!




Zach

David_J
Employee

We try not to change the sample forms often, only if we need to fix a bug or add some increased functionality. One of our support engineers is actually working on a more comprehensive PHP wrapper library that will include all of our API's functionality, and this will be where we make all future modifications to our sample code. You can be pretty confident that unless we needed to fix an unknown bug that we won't be modifying the sample forms further. Any update that we do make will be documented on the Sample Codes page.


 


I'm glad that you got things working as you wanted. If you do have any other questions regarding our API, please feel free to post on these forums. Thanks!

David J

kleankan
Regular Participant

David:


 


Thanks for the info. Good to know. Will keep an eye out for that.


 


I did have ONE more issue. I got the addOrUpdate function working correctly with my form and cc_class. I can successfully add a new susbcriber or update an existing one to a new list (if they already exist).


 


Only problem is I can't get the "success" message to show with that function. Like on the other addSubscriber and editSubscriber functions, there is the


 @return TRUE in case of success or FALSE otherwise.


 


Is there something similar for this function? I tried changing this code:


 


return $postReturn;


 


 to this:


return true;


 


But has no affect. The form submits and data is updated in CC, but just comes back to the form, doesn't show success message.




Thanks!

 


 

David_J
Employee

At this point that function does not return much in the way of error messaging. I kind of wrote this function on the fly just to display how this could operate for a specific customer who was attempting to build this function, and did not pay much attention to error messaging. As it appears this function may be more useful that originally anticipated,  I do believe that I can build this into the addOrUpdate() function, but It will take me a little bit of time. I will see how quickly I can build this and I will update this thread when I've got that complete. If you have any questions please let me know. Thanks!

David J

David

 

I have tried to implement this but the Update portion is not working.  Using AddorUpdate adds the new user, but does not update existing users.  There is nothing in the error logs and no message is returned.  Any ideas where to look?

Developer Portal

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

Visit Page