cancel
Showing results for 
Search instead for 
Did you mean: 

Need help modifying this PHP Class for adding a contact

SOLVED
Advisor

Need help modifying this PHP Class for adding a contact

I found this bit of code online, and it works fine for addinga contact to my list. However, there are a couple of things I need this to do:

1) If the contact exists in the Do Not Mail or Removed categories, I need to be able to add them back.

2) How can I modify this to alo insert additional fields? (name, zip, custom1, etc)

Any help is appreciated.

------------------------------------------
The code on my insert page:
------------------------------------------

$myKey    = '######';
$myUn     = '######';
$myPW     = '######';
$addToCC  = $_POST['addToCC'];

if($addToCC  == 1) {
#add user to mailing list
$cc = new ConstantContact( $myKey, $myUN, $myPW );
$result = $cc->addContactToMailingList($email, "https://api.constantcontact.com/ws/customers/######/lists/10");
}


----------------------------------

The PHP class:

----------------------------------

 

class ConstantContact{

private $api_key;
private $user_name;
private $user_pass;
private $auth_pass;

public function __construct($apikey, $username, $userpassword){

$this->api_key = $api_key;
$this->user_name = $username;
$this->user_password = $userpassword;
$this->auth_pass = $apikey . "%" . $username . ":" . $userpassword;

}

public function __destruct(){

}

public function addContactToMailingList($emailAddressOfUser, $contactList){

$contactURL = "https://api.constantcontact.com/ws/customers/{$this->user_name}/contacts";

$contactListToAddTo = $contactList;

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

$rawEntry = "<entry xmlns='http://www.w3.org/2005/Atom'></entry>";
$xml_object = simplexml_load_string($rawEntry);
$title_node = $xml_object->addChild("title", htmlspecialchars("TitleNode"));
$updated_node = $xml_object->addChild("updated", htmlspecialchars($update_date));
$author_node = $xml_object->addChild("author");
$author_name = $author_node->addChild("name", htmlspecialchars($this->user_name));
$id_node = $xml_object->addChild("id", "data:,none");
$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($emailAddressOfUser)));
$optin_node = $contact_node->addChild("OptInSource", htmlspecialchars('ACTION_BY_CUSTOMER'));
$contactlists_node = $contact_node->addChild("ContactLists");
$contactlist_node = $contactlists_node->addChild("ContactList");
$contactlist_node->addAttribute("id", urldecode(htmlspecialchars($contactListToAddTo)));

$entry = $xml_object->asXML();

$curl_conn = curl_init($contactURL);
// Set up Basic authentication - username and password.
curl_setopt($curl_conn, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl_conn, CURLOPT_USERPWD, $this->auth_pass);
curl_setopt($curl_conn, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($curl_conn, CURLOPT_POST, 1);
curl_setopt($curl_conn, CURLOPT_POSTFIELDS , $entry);
curl_setopt($curl_conn, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
curl_setopt($curl_conn, CURLOPT_HEADER, 0); // Do not return headers
curl_setopt($curl_conn, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_conn, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curl_conn);
curl_close($curl_conn);
echo $response;

//return true;

}

}

21 REPLIES 21
CTCT Employee

Re: Need help modifying this PHP Class for adding a contact

Hello,

I would definitely like to help you with your PHP integration.  We actually have a new library that takes care a lot of the code for you.  You can download the library here, and there is also a wiki for it that explains how to use it here.
Here is an example of how to add or update a contact with the library:

<?php  
    include_once('ConstantContact.php');
    $ConstantContact = new ConstantContact('basic', "APIKEY", "USERNAME", "PASSWORD");

    // Search for a contact by Email Address
    $search = $ConstantContact->searchContactsByEmail('example@example.com');


   

    if (!$search) {
        // Get details for the Contact
        $Contact = $ConstantContact->getContactDetails($search[0]);

        $lists = $ConstantContact->getLists();

        $contactObj = new Contact();
        $contactObj->lists = array($lists['lists'][0]->id, $lists['lists'][1]->id);
        $contactObj->emailAddress = 'example@example.com';
        $contactObj->firstName = 'John';
        $contactObj->lastName = 'Doe';

        // Create the contact
        $Contact = $ConstantContact->addContact($contactObj);
    }

    else {

        // modify Contact properties
        $Contact->firstName = "John";
        $Contact->lastName = "Doe";

        //update the contact
        $Contact = $ConstantContact->updateContact($Contact);

    }
?>

If you have any questions about this, or run into any other difficulties, please let me know and we can work from there!

Regards,
Benjamin Soder
NOC Analyst
Constant Contact
Advisor

Re: Need help modifying this PHP Class for adding a contact

I'm getting the following error:

 

Catchable fatal error: Argument 1 passed to ConstantContact::updateContact() must be an instance of Contact, instance of stdClass given, called in /home/mysite/public_html/constantcontact/apitest.php on line 39 and defined in /home/mysite/public_html/constantcontact/ConstantContact.php on line 204

Moderator

Re: Need help modifying this PHP Class for adding a contact

The problem appears to be in your Else block.  While you do create a Contact object in the If block, the Else block creates a generic object called $Contact instead of creating a new Contact() object first and assigning it to $Contact.  For this reason, the correct error is being thrown.  You will need to create a new Contact() object for your Else loop to correctly handle the case that the Contact is found by your search. 

 

In looking at your code closely, it appears that you have all the right code written, just your organization of it is not quite right.  I believe the correct code for what you're looking to do is:

 

 

<?php  
     include_once('ConstantContact.php');
     $ConstantContact = new ConstantContact('basic', "APIKEY", "USERNAME", "PASSWORD");

    // Search for a contact by Email Address
     $search = $ConstantContact->searchContactsByEmail('example@example.com');
 

   

    if (!$search) {
 
        $lists = $ConstantContact->getLists();
 
         $contactObj = new Contact();
         $contactObj->lists = array($lists['lists'][0]->id, $lists['lists'][1]->id);
         $contactObj->emailAddress = 'example@example.com';
         $contactObj->firstName = 'John';
         $contactObj->lastName = 'Doe';
 
        // Create the contact
         $Contact = $ConstantContact->addContact($contactObj);
     }
 
    else {
         // Get details for the Contact
         $Contact = $ConstantContact->getContactDetails($search[0]);
 
        // modify Contact properties
         $Contact->firstName = "John";
         $Contact->lastName = "Doe";
 
        //update the contact
         $Contact = $ConstantContact->updateContact($Contact);
 
    }
 ?>
Dave Berard
Senior Product Manager, Constant Contact
Advisor

Re: Need help modifying this PHP Class for adding a contact

After using your solution, I was able to add the contact successfully, however, if I t mark the contact as removed and then try to re-add the same contact I get the following error:

 

Fatal error: Wrong parameters for Exception([string $exception [, long $code ]]) in /home/mnysite/public_html/constantcontact/Components.php on line 1434

 

Also, how is it determining which list to add the contact? It actually added it to the correct list, but I don't see how this is possible considering I have not defined the listid anywhere. I'm confused.

Moderator

Re: Need help modifying this PHP Class for adding a contact

This code sample makes some assumptions on which lists to add a newly created contact to.  The line that chooses them is:

 

$contactObj->lists = array($lists['lists'][0]->id, $lists['lists'][1]->id);

 

If you want to pick specific lists, you'll need to find the correct lis in the returned $lists array and either hard code the ID (which never changes for a list) or put logic in to make sure the right list(s) are always selected.  Right now, it's just selecting hte first two lists that it finds in the $lists array, which could change depending on how you change the lists in your account by adding and deleting lists.

 

I'm going to make sure Ben gets involved again, I'm not as familiar with the PHP component as he is and am not sure why you are receiving an error when updating. 

Dave Berard
Senior Product Manager, Constant Contact
Highlighted
CTCT Employee

Re: Need help modifying this PHP Class for adding a contact

Regarding the error you are seeing:

Fatal error: Wrong parameters for Exception([string $exception [, long $code ]]) in /home/mnysite/public_html/constantcontact/Components.php on line 1434

 

This is because PHP 5.3 added an optional 3rd parameter to the Exception class, and since we're supplying one, this error is thrown in all versions of PHP prior to 5.3. I have since update the GitHub repository to remove this 3rd argument, so this should now function properly in all versions of PHP 5.1.3+.

 

You can either redownload the library from https://github.com/ctctsupport/ctct_php_library. Or you can change Components.php line 1434 from:

parent::__construct($message, $code, $previous);

 

To:

 

parent::__construct($message, $code);

 

I hope this helps. Please let us know if you have any other questions or concerns. Thanks!

David J

Advisor

Re: Need help modifying this PHP Class for adding a contact

Ok, I can add a contact, but if i mark it as removed and then try to re-add it, I get this:

 

Constant Contact Contact Error: 'lists' was required but not supplied
Constant Contact Contact Error: 'lists' was required but not supplied

Advisor

Re: Need help modifying this PHP Class for adding a contact

Well, I fixed the error by changing the Else statemnt to the following, but the contact is not being added back to the list.

 

 else {

    $lists = $ConstantContact->getLists();
         // Get details for the Contact
         $Contact = $ConstantContact->getContactDetails($search[0]);
 
        // modify Contact properties
     $Contact->lists = array($lists['lists'][0]->id, $lists['lists'][1]->id);
         $Contact->firstName = $firstname;
         $Contact->lastName = $lastname;
 
        //update the contact
         $Contact = $ConstantContact->updateContact($Contact);
 
    }

 

 

Advisor

Re: Need help modifying this PHP Class for adding a contact

Ok, this is interesting. If I add a test email using the code, it gets added. If I then "remove" the address within CC and re-add it, it shows in the list but the status says REMOVED.