cancel
Showing results for 
Search instead for 
Did you mean: 

add contact to multiple lists

New Member

add contact to multiple lists

Hi I have modified the Sample script to my liking, and have it successfully adding a contact to a specific list.

I have now duplicated the script and changed the list variable to another list. I get the error email address is already a contact.

I would like to use constant contact to sign up the same person, in multiple areas of my website (each with a different list) ....

How do I go about doing this?

Thanks in advance.
6 REPLIES 6
New Member

Hello again

How can I modify the addcontact.php script to add an contact (email) to an additional list?
New Member

I am at the exact same point

I am at the exact same point as you are. Need to be able to added to multiple lists or different lists depending on what the users selects at the form. If you figure it out could you let me know.

Thanks.
Solution Provider

RE: add contact to multiple lists

The PHP example you are using does not check if a contact is already in your account and it also does not update contacts. It only adds new contacts to your account. Once a contact is in your account you no longer can do a HTTP POST request to update the contact. You will need to do HTTP PUT request to update the contact.

You would have to add the following logic to the PHP Example.
First check to see if the contact is already on your list by querying the contacts collection
http://developer.constantcontact.com/doc/contactsCollection#Querying

If the contact exists then you would have to do HTTP Put command to update the contact.
http://developer.constantcontact.com/samples/putSubscriber

Else you would do a HTTP Post command which the example you are using is doing.

Mike C Support Engineer, Constant Contact

Solution Provider

RE: I am at the exact same point

I made some changes to the PHP example for my own website that allows new contacts to join multiple lists. Please feel free to take this code and improve on it. If you are able to make this code better I only ask that you post your own changes so that every one can benefit.



**************Contact_Form.php Starts********************

<!--

/*

* Copyright 2008, Constant Contact

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">

<head>

<title>Add Contact Sample Script</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body class="sidebar-right">

<form action="AddAContact.php" method="post">

<input type="hidden" name="required_params" value="email_address" />

<!--<input type="hidden" name="Landing_Page_URL" value="http://www.google.com" />-->

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

<tr>

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

<td align="left"><input type="text" name="email_address" maxLength="100" /></td>

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

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

<td rowspan="12" align="left" valign="top"><p>Please select the areas of interest for which you would like to receive occasional email from us.</p>

<p><br />

<?php

require "Contact.php";





$xml = executeRequest('http://api.constantcontact.com/ws/customers/' . CC_USERNAME . '/lists');

echo $xml;


if (isset($xml)){

$data = simplexml_load_string($xml);


// Load $Data in to Array so we can sort it

foreach ($data->entry AS $item){

$name = $item->content->ContactList->SortOrder;

$Test = $item->id ;

$Test = $item->content->ContactList->Name;


}


ksort($Test); // sort by sort order


foreach ($Test as $K){




if ( $K == "Active" || $K == "Do Not Mail" || $K == "Removed"){}

else

{



?>

<input type='checkbox' name='lists[]' value='<?php echo $K



?>'>



<?php







echo $K;





?>

</br>





</p>

<?php

}

}

}


?></td>

</tr>

<tr>

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

<td align="left"><input type="text" name="first_name" maxLength="100" /></td>

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

<td align="left"><input type="text" name="last_name" maxLength="100" /></td>

</tr>

<tr>

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

<td align="left"><input type="text" name="middle_name" maxLength="100" /></td>

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

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

</tr>

<tr>

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

<td align="left"><input type="text" name="company_name" maxLength="100" /></td>

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

<td align="left"><input type="text" name="job_title" maxLength="100" /></td>

</tr>

<tr>

<td align="left">Custom Field1:</td>

<td align="left"><input type="text" name="custom_field_1" maxLength="100" /></td>

<td align="left">Custom Field2:</td>

<td align="left"><input type="text" name="custom_field_2" maxLength="100" /></td>

</tr>

<tr>

<td align="left">Custom Field3:</td>

<td align="left"><input type="text" name="custom_field_3" maxLength="100" /></td>

<td align="left">Custom Field4:</td>

<td align="left"><input type="text" name="custom_field_4" maxLength="100" /></td>

</tr>

<tr>

<td align="left">Custom Field5:</td>

<td align="left"><input type="text" name="custom_field_5" maxLength="100" /></td>

<td align="left">Custom Field6:</td>

<td align="left"><input type="text" name="custom_field_6" maxLength="100" /></td>

</tr>

<tr>

<td align="left">Custom Field7:</td>

<td align="left"><input type="text" name="custom_field_7" maxLength="100" /></td>

<td align="left">Custom Field8:</td>

<td align="left"><input type="text" name="custom_field_8" maxLength="100" /></td>

</tr>

<tr>

<td align="left">Custom Field9:</td>

<td align="left"><input type="text" name="custom_field_9" maxLength="100" /></td>

<td align="left">Custom Field10:</td>

<td align="left"><input type="text" name="custom_field_10" maxLength="100" /></td>

</tr>

<tr>

<td align="left">Custom Field11:</td>

<td align="left"><input type="text" name="custom_field_11" maxLength="100" /></td>

<td align="left">Custom Field12:</td>

<td align="left"><input type="text" name="custom_field_12" maxLength="100" /></td>

</tr>

<tr>

<td align="left">Custom Field13:</td>

<td align="left"><input type="text" name="custom_field_13" maxLength="100" /></td>

<td align="left">Custom Field14:</td>

<td align="left"><input type="text" name="custom_field_14" maxLength="100" /></td>

</tr>

<tr>

<td align="left">Custom Field15:</td>

<td align="left"><input type="text" name="custom_field_15" maxLength="100" /></td>

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

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

</tr>

<tr>

<td align="left" colspan="5"><p>&nbsp;</p>



<p>

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

</p>

<p>&nbsp; </p></td>

</tr>

</table>

</form>

</body>

</html>


******************AddAContact.php******************

<?php

/*

* Copyright 2008, Constant Contact

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/





require "Contact.php";



session_start();

$required_params = $_REQUEST;

$errmsg = '';

$required_fields = explode(',', $required_params);

foreach($required_fields as $field) {

if (empty($_POST)) {

// field doesn't exist or is empty - add error message

$errmsg .= '<br />Missing field: ' . (substr($field, 0, 6) == 'Custom' ? $_POST : $field);

echo $errmsg;

}

}

$ct = new Contact(CC_USERNAME,CC_PASSWORD,CC_APIKEY,LOGFILE);

$email = strip_tags($_REQUEST);

$first_name = urlencode(strip_tags($_REQUEST));

$last_name= urlencode(strip_tags($_REQUEST));

$middle_name= urlencode(strip_tags($_REQUEST));

$company_name = urlencode(strip_tags($_REQUEST));

$job_title= urlencode(strip_tags($_REQUEST));



//$list_name = urlencode(strip_tags($_REQUEST));



//if(LIST_NAME != '') $list_name = LIST_NAME;

$cf_array = array();

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

if (strncmp($k, CUSTOM_FIELD_PREFIX, strlen(CUSTOM_FIELD_PREFIX)) === 0) {

$cf_array = $_REQUEST;

}

}


$ct->SetPrimaryInfo($email, $list_name, $first_name, $last_name, $middle_name, $company_name, $job_title);

$ct->SetCustomFields($cf_array);

$entry = $ct->MaketEntry();

$errmsg .= $ct->GetErrorMessage();



//proceed if there are no errors

//print($errmsg);

if (empty($errmsg)) {

$output='';

if (LOGFILE && LOG_LEVEL == 2) error_log(date('Y-m-d H:i:s') .

' Request data: ' . $entry .

"\n", 3, LOGFILE);


//$list_resp = $ct->FindContactList("Friends");

$request = "http://api.constantcontact.com/ws/customers/".CC_USERNAME."/contacts";

$session = curl_init($request);

// Set up Digest authentication - username and password.

$userNamePassword = CC_APIKEY."%".CC_USERNAME.":".CC_PASSWORD;

curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);

curl_setopt($session, CURLOPT_USERPWD, $userNamePassword);

curl_setopt($session, CURLOPT_FOLLOWLOCATION ,1);

curl_setopt($session, CURLOPT_POST, 1);

curl_setopt($session, CURLOPT_POSTFIELDS , $entry);

curl_setopt($session, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));

curl_setopt($session, CURLOPT_HEADER, 0); // Do not return headers

curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($session);

curl_close($session);

if (!$response) {

// curl failed, create error message

$output .= "

<h1>Error Encountered!</h1>

<p>There was an error trying to connect to the server. <br />

Please go <strong><a href=\"#\" onClick=\"history.go(-1)\">BACK</a></strong> and try again later.</p>

";


// write error to logfile

if (LOGFILE && LOG_LEVEL) error_log(date('Y-m-d H:i:s') .

' Error attempting to connect via curl to ' . $request .

"\n", 3, LOGFILE);



} else {

if (!($xml = strstr($response, '<?xml'))) {

$xml = null;

if (DISPLAY_ERRORS) {

// write error to browser output

$output .= "

<h1>System Error Encountered!</h1>

<p>Error {$details}: {$details}</p>" . $response; // echo response, it may contain an error message

}

} else {

$data = simplexml_load_string($response);

$code = $data->code;

if (!empty($code) && intval($code) >= 400) {

$output .= "

<h1>System Error Encountered!</h1>

<p>Error {$details}: {$details}</p>" . $data->message;

} else {

if (LOGFILE && LOG_LEVEL) error_log(date('Y-m-d H:i:s') .

' Successfully added ' . $_REQUEST .

' (IP Address: ' . $_SERVER . ') to list \'' . $_REQUEST . '\'' .

"\n", 3, LOGFILE);



// redirect to landing page if specified

if (!empty($_REQUEST)) {

if (LOGFILE && LOG_LEVEL == 2) error_log(date('Y-m-d H:i:s') .

' Redirecting subscriber to ' . $_REQUEST .

"\n", 3, LOGFILE);

// save $_POST to session var for accessibility after the jump

$_SESSION = $_POST;

//$data = simplexml_load_string($xml);

//$location = $data->id; // URL to the newly created Contact object

//echo $data->id;

header('Location: ' . $_POST);

exit;

} else {

$output .= "

<h1>You have been added to our list.</h1>

<p>Thank you for subscribing.</p>

<p>Please <a href=\"" . SITE_HOME . "\">CLICK HERE</a> to return to our main page.</p>";

}

}

}

}

} else {

$output .= "

<h1>System Error Encountered!</h1>

<p>Error</p>" . $errmsg;

}

echo $output;

// display output either to default view or to template if specified

if (OUTPUT_TEMPLATE) {

if (LOGFILE && LOG_LEVEL == 2) error_log(date('Y-m-d H:i:s') .

' Displaying output using template ' . OUTPUT_TEMPLATE .

"\n", 3, LOGFILE);



include(OUTPUT_TEMPLATE);

exit;

}

?>




***********************Contact.php*********************



<?php

/*

* Copyright 2008, Constant Contact

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

@define('CC_USERNAME','Username'); // Constant Contact username (API enabled) and need to be changed before using the script

@define('CC_PASSWORD','Password'); // Constant Concact password (API enabled) and need to be changed before using the script

@define('CC_APIKEY','APIKeY');

@define('LIST_NAME','General Interest');

@define('SITE_HOME','http://localhost'); // Site home page URL

@define('OUTPUT_TEMPLATE', ''); // Optional output template to use for customizing standard display

@define('USE_SSL', false); // Use SSL connection to access API

@define('DISPLAY_ERRORS', true); // Display verbose errors to screen (not recommended in production)

@define('LOGFILE','ccsub.log'); // Log file to save messages to

@define('LOG_LEVEL', 1); // level of detail to put in logfile (0 = no logging, 1 = basic info, 2 = debug info)

@define('CUSTOM_FIELD_PREFIX', 'custom_field_');



function executeRequest($webServiceUrl){

$request = $webServiceUrl;


// Initialize the session

$session = curl_init($request);


// Set up Digest authentication - username and password.

$userNamePassword = CC_APIKEY . '%' . CC_USERNAME . ':' . CC_PASSWORD;


curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);

curl_setopt($session, CURLOPT_USERPWD, $userNamePassword);


// The following option tells Curl to not send the result of the execution to the browser

// This must be set to 1 or true in order to process the resulting xml programatically.

curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);


// Make the request

$response = curl_exec($session);


// Get the XML from the response, bypassing the header

if (!($xml = strstr($response, '<?xml'))) {

$xml = null;

echo $response;

// XML is Null!!! Must display an error.

}


// Close the curl session

curl_close($session);


return $xml;

}


class Contact {

// Constructor VARIABLES

var $user_name;

var $password;

var $api_key;

var $log_file_name = "ccsub.log";

// contact vars

var $email_address='';

var $list_url;

var $first_name;

var $last_name;

var $middle_name;

var $company_name;

var $job_title;

var $work_phone;

var $home_phone;

var $update_date;

var $list_name;

var $err_message;

var $custom_fields = array();

var $nritems;

// FUNCTIONS

// constructor

public function __construct($user,$pw,$key, $log_file) {

$this->user_name=$user;

$this->password=$pw;

$this->api_key=$key;

if ($log_file) $this->log_file_name=$log_file;

}

// set contact vars

function SetPrimaryInfo($email, $list, $first, $last, $middle, $company, $job) {

//if ((!empty($email)) && (eregi('^+@+\.({2,4})$', $email))) {

// $this->err_message .= '<br />Missing or invalid email address.';

//}

$this->email_address=$email;

$this->first_name=$first;

$this->last_name=$last;

$this->middle_name=$middle;

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

$this->company_name=$company;

$this->job_title=$job;

$this->list_name=$list;

$this->list_url=$this->FindContactList($list);

}


public function SetContactInfo($home_num, $home_num, $addr_1, $addr_2, $addr_3, $city, $state, $country, $postal_code, $sub_postal) {

$this->home_number=$home_num;

$this->home_number=$home_num;

$this->address_line_1=$addr_1;

$this->address_line_2=$addr_2;

$this->address_line_3=$addr_3;

$this->city_name=$city;

$this->state_code=$state;

$this->country_code=$country;

$this->zip_code=$postal_code;

$this->sub_zip_code=$sub_postal;

}


public function SetCustomFields($cf_array) {

$this->custom_fields = $cf_array;

}


private function FindContactList($list_name) {

$request = "http://api.constantcontact.com/ws/customers/".$this->user_name."/lists";

$session = curl_init($request);

// Set up Digest authentication - username and password.

$userNamePassword = $this->api_key."%".$this->user_name.":".$this->password;

if (empty($this->api_key) || empty($this->user_name) || empty($this->password)) {

$this->err_message .= '<br />Missing or invalid user name or password or api key.';

error_log(date('Y-m-d H:i:s') .

' Error invlid user name or password or api key '.

"\n", 3, $this->log_file_name);

}

curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);

curl_setopt($session, CURLOPT_USERPWD, $userNamePassword);

curl_setopt($session, CURLOPT_FOLLOWLOCATION ,1);

curl_setopt($session, CURLOPT_GET, 1);

curl_setopt($session, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));

curl_setopt($session, CURLOPT_HEADER, 0); // Do not return headers

//don't send the response to browser

curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($session);

curl_close($session);

//error handling and write to log file

if (!$response) {

$list_id = -1;

if ($this->log_file_name) error_log(date('Y-m-d H:i:s') .

' Error attempting to connect via curl to ' . $request .

"\n", 3, $this->log_file_name);

} else {

$data = simplexml_load_string($response);



echo $data->entry ;

foreach($data->entry as $data_entry) {

$entry_name = urlencode($data_entry->content->ContactList->Name);

echo $entry_name ." List name: ". $list_name ."<br>" ;

if ($entry_name == $list_name) {

$list_id=$data_entry->content->ContactList;

}

}

}

return $list_id;

}


public function GetErrorMessage() {

return $this->err_message;

}

// output feed

public function MaketEntry() {

if ($_POST== null){

$this->err_message .= '<br />Please Select a list ';

error_log(date('Y-m-d H:i:s') .

' Error could not find valid list with list name ' . $this->list_name .

"\n", 3, $this->log_file_name);



}

/*

if ($this->list_url == -1 || empty($this->list_url) || $this->list_url == ""){

$this->err_message .= '<br />could not find valid list with the name '. $this->list_name;

error_log(date('Y-m-d H:i:s') .

' Error could not find valid list with list name ' . $this->list_name .

"\n", 3, $this->log_file_name);

}*/

$xml_sttring = "<entry xmlns='http://www.w3.org/2005/Atom'></entry>";



$xml_object = simplexml_load_string($xml_sttring);


$title_node = $xml_object->addChild("title", htmlspecialchars("Hmmm this is ignored right now"));

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

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

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

$id_node = $xml_object->addChild("id", "urn:uuid:E8553C09F4xcvxCCC53F481214230867087");


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

$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"));

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

$email_node = $contact_node->addChild("EmailAddress", urldecode(htmlspecialchars($this->email_address)));

$fname_node = $contact_node->addChild("FirstName", urldecode(htmlspecialchars($this->first_name)));

$lname_node = $contact_node->addChild("LastName", urldecode(htmlspecialchars($this->last_name)));

$lname_node = $contact_node->addChild("MiddleName", urldecode(htmlspecialchars($this->middle_name)));

$lname_node = $contact_node->addChild("CompanyName", urldecode(htmlspecialchars($this->company_name)));

$lname_node = $contact_node->addChild("JobTitle", urldecode(htmlspecialchars($this->job_title)));

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

if (!empty($this->home_number))

$hn_node = $contact_node->addChild("HomePhone", htmlspecialchars($this->home_number));

if (!empty($this->work_number))

$wn_node = $contact_node->addChild("WorkPhone", htmlspecialchars($this->work_number));

if (!empty($this->address_line_1))

$ad1_node = $contact_node->addChild("Addr1", htmlspecialchars($this->address_line_1));

if (!empty($this->address_line_2))

$ad2_node = $contact_node->addChild("Addr2", htmlspecialchars($this->address_line_2));

if (!empty($this->address_line_3))

$ad3_node = $contact_node->addChild("Addr3", htmlspecialchars($this->address_line_3));

if (!empty($this->city_name))

$city_node = $contact_node->addChild("City", htmlspecialchars($this->city_name));

if (!empty($this->state_code))

$state_node = $contact_node->addChild("StateCode", htmlspecialchars($this->state_code));

if (!empty($this->country_code))

$ctry_node = $contact_node->addChild("CountryCode", htmlspecialchars($this->country_code));

if (!empty($this->zip_code))

$zip_node = $contact_node->addChild("PostalCode", htmlspecialchars($this->zip_code));

if (!empty($this->sub_zip_code))

$subzip_node = $contact_node->addChild("SubPostalCode", htmlspecialchars($this->sub_zip_code));

if (!empty($this->custom_fields)) {

foreach($this->custom_fields as $k=>$v) {

if (!empty($v))

$contact_node->addChild("CustomField".$k, htmlspecialchars($v));

}

}

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



foreach ($_POST as $tmp)

{



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

$contactlist_node->addAttribute("id", 'http://api.constantcontact.com/ws/customers/' . CC_USERNAME . '/lists/'.$tmp);

}

$entry = $xml_object->asXML();

return $entry;

}

};

?>

Mike C Support Engineer, Constant Contact

Occasional Participant

email already exists, then same email is not adding another list

Hello Mike,


I used your code which I get from the same site for single email adding in multiple lists. But if the user add an email in the already which is already existed in anyother list then it will not add the email in to the list in which I am adding.

If I add an email at once (which is not present in the CC ) from the API call into multiple list then only it is adding. I tried it adding the same email in multiple lists one by one. But after adding it into list one the email is not added to list second.

Please provide some way for it.

Thanks in advance.


Thanks
Veerpartap singh
Participant

PUT just a new list details

Does that mean that if I only use a PUT with just the details of the new list like:

$entry = '<ContactList id="http://api.constantcontact.com/ws/customers/' . CC_USERNAME . '/lists/8">

    <link xmlns="http://www.w3.org/2005/Atom" href="http://api.constantcontact.com/ws/customers/' . CC_USERNAME . '/lists/8" rel="self" />

    <OptInSource>ACTION_BY_CUSTOMER</OptInSource>

    <OptInTime>' . date('Y-m-d\TH:i:s\Z') . '</OptInTime>

</ContactList>';

Would that keep all the current details (previously entered by the contact) and just add this list to it.

I just trying to find a way to just add a list to an xml and not have to get all the details & re PUT them.

Cheers