Error 400 from Constant Contact API Call

Highlighted
Occasional Visitor

Error 400 from Constant Contact API Call

Below is my call to the Constant Contact API. When testing the API call on my website when using a new email address in the form entry, everything works correctly. If I use my email address to test the website form and then delete my email address from that Constant Contact email list and then try and fill out the website form again using my same test email account, I receive the following Error 400. This is a problem if a customer or company admin erases a contact from a company lists and then needs to add them back or they need to add themselves back to a list using the online contact form through the site.

 

Error 400

Constant Contact HTTP ZRequest Exception: Error 400: The request contains errors in the common Atom sections, which lie outside <entry> or <Content>, such as <feed>, <id>, <author> or <updated>. <br/> {"error" :0, "message";"...

 

Code

function mod_contact_ccAPI($arrContact,$login,$pass,$key,$secret,$listID){
        global $dp;
        include_once("assets/ConstantContact.php");
            $ConstantContact = new ConstantContact('basic', $key, $login, $pass);
            $ContactLists = $ConstantContact->getLists();
            foreach($ContactLists['lists'] as $key => $list){
                if($list->name == $listID){
                    $myList = $key;
                    break;
                }
            }
            $dp = New DataTools();
            $search = $ConstantContact->searchContactsByEmail($arrContact['email']);
            if($search == false){
                if($dp->m_validEmail($arrContact['email'])){
                    $Contact = new Contact();
                    $Contact->emailAddress = $arrContact['email'];
                    $Contact->firstName = $arrContact['fname'];
                    $Contact->lastName = $arrContact['lname'];
                    $Contact->lists = array($ContactLists['lists'][$myList]->id);
                    $NewContact = $ConstantContact->addContact($Contact);
                    if($NewContact){
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
            }else{
                $ContactObj = $ConstantContact->getContactDetails($search[0]);
                if($ContactObj->status != "Removed"){
                    array_push($ContactObj->lists,$ContactLists['lists']['$myList']->id);
                    $UpdateContact = $ConstantContact->updateContact($ContactObj);
                }
                return true;
            }
    }

7 REPLIES 7
Highlighted
CTCT Employee

Re: Error 400 from Constant Contact API Call

Hey,

 

The 400 error represents that there is an error on your submission with the XML that the library is creating.  Can you do a 

var_dump(Contact);

 Before you create the contact.  This will give us an idea of what information is stored in the Contact and what is being passed into the XMl. Then we can try to troubleshoot where the 400 error is coming form.

 

 

Ryan Davis
Quality Engineer
Highlighted
Occasional Participant

Re: Error 400 from Constant Contact API Call

I'm experiencing something similar.  API calls succeed for new subscriptions.  Subscribing to a list with an existing email address produces a 400 error.

 

Here's the value of my object - thanks in advance for your guidance.

 

object(Contact)#16 (44) {
  ["link"]=>
  string(38) "/ws/customers/xxxxxx/contacts/90424"
  ["id"]=>
  string(68) "http://api.constantcontact.com/ws/customers/xxxxxxx/contacts/90424"
  ["updated"]=>
  string(24) "2013-02-26T20:36:22.213Z"
  ["status"]=>
  string(6) "Active"
  ["emailAddress"]=>
  string(18) "carlos123@test.com"
  ["emailType"]=>
  string(4) "HTML"
  ["firstName"]=>
  string(6) "Carlos"
  ["middleName"]=>
  string(0) ""
  ["lastName"]=>
  string(7) "Mossman"
  ["fullName"]=>
  string(0) ""
  ["jobTitle"]=>
  string(5) "Title"
  ["companyName"]=>
  string(7) "Company"
  ["homePhone"]=>
  string(5) "Phone"
  ["workPhone"]=>
  string(0) ""
  ["addr1"]=>
  string(15) "Company address"
  ["addr2"]=>
  string(0) ""
  ["addr3"]=>
  string(0) ""
  ["city"]=>
  string(4) "City"
  ["stateCode"]=>
  string(0) ""
  ["stateName"]=>
  string(0) ""
  ["countryCode"]=>
  string(0) ""
  ["countryName"]=>
  string(0) ""
  ["postalCode"]=>
  string(3) "Zip"
  ["subPostalCode"]=>
  string(0) ""
  ["notes"]=>
  string(0) ""
  ["customField1"]=>
  string(0) ""
  ["customField2"]=>
  string(0) ""
  ["customField3"]=>
  string(0) ""
  ["customField4"]=>
  string(0) ""
  ["customField5"]=>
  string(0) ""
  ["customField6"]=>
  string(0) ""
  ["customField7"]=>
  string(0) ""
  ["customField8"]=>
  string(0) ""
  ["customField9"]=>
  string(0) ""
  ["customField10"]=>
  string(0) ""
  ["customField11"]=>
  string(0) ""
  ["customField12"]=>
  string(0) ""
  ["customField13"]=>
  string(0) ""
  ["customField14"]=>
  string(0) ""
  ["customField15"]=>
  string(0) ""
  ["contactLists"]=>
  string(0) ""
  ["confirmed"]=>
  string(0) ""
  ["optInSource"]=>
  string(0) ""
  ["lists"]=>
  array(1) {
    [0]=>
    string(63) "http://api.constantcontact.com/ws/customers/xxxxxx/lists/503"
  }
}
Highlighted
CTCT Employee

Re: Error 400 from Constant Contact API Call

Hi,

 

In your code, if you want to update an existing email address as well as add new contacts, you would have to build in logic to search for the email address first, then add or update depending on whether it exists.  The 409 is typically given if you try to add an existing email address instead of update it, so you may have another issue with your code since you're getting a 400.  

 

To get you up and running as quickly as possible, I can give you my example script and the steps to take to put a working signup form on your webpage.

 

1.  Generate an API Key here if you haven't already: http://community.constantcontact.com/t5/Documentation/API-Keys/ba-p/25015

 

2.  Download the wrapper here: https://github.com/constantcontact/ctct_php_library   Place the files from the wrapper in the folder/path on your server where you want the signup form to be.  Normally this is the same place where your index.html file currently lives.

 

3. Replace the existing code in the index.php file included in the wrapper with the below code.  Make any desired changes, like adding a first name input or changing the listID (list number) that you want people added to in your account.

 

<html>
<body>
	<H1>Search for a contact</H1>
	<form action="index.php" method="post">
		<input type="text" name="emailAddress" maxlength="50"> 
		<input type="submit" name="submit" value="Submit" />
	</form>
</body>
</html>
	

<?php
session_start ();
require_once 'ConstantContact.php';
require_once 'config.php';
	
$ConstantContact = new ConstantContact ( "oauth2", $apikey, $username, $accessToken );
//$ConstantContact = new ConstantContact('basic', $apikey, $username, $password); //basic authentication

// Get potential contact lists
$lists = $ConstantContact->getLists();
// Lists are returned in multidimentional arrays 0 being the list, and 1 being the next50

//Map all form inputs here
$emailAddress = $_POST["emailAddress"];

// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($emailAddress);

// If the search didnt return a contact object
if($search == false)
{
	// Create a new Contact Object to store data into
	$contactObj = new Contact();
	// Adding multiple lists to this new Contact Object
	$contactObj->lists = array($lists['lists'][0]->id, $lists['lists'][1]->id);
	// Set the email address
	$contactObj->emailAddress = $emailAddress;
	//Set the opt in source
	$contactObj->optInSource = "ACTION_BY_CONTACT";
	// Create the Contact and DONE
	$Contact = $ConstantContact->addContact($contactObj);
	echo ("Contact added.");

} // Otherwise we update our existing contact
else 
{
	// Gather data from our previous search and store it into a data type
	$contactObj = $ConstantContact->getContactDetails($search[0]);

	 // We need to get the old lists and add a new list to it as
	 array_push($contactObj->lists, $lists['lists'][1]->id );
	 
	 //Set the opt in value
	 $contactObj->optInSource = "ACTION_BY_CONTACT";
	 $contactObj->firstName = 'firstname';
  	 $contactObj->lastName = 'CTCTlastname';
	// Update the contact and DONE
	$UpdateContact = $ConstantContact->updateContact($contactObj);
	
	echo ("Contact " . $emailAddress . " updated.");
}
		
?>

 

 

4.  Replace the contents of config.php with this, filling in your username, password, and API Key.

 

<?php

 

$username = "";

$password = "";  //needed for basic auth which we're deprecating

$accessToken = "";  //needed for Oauth2

$apikey = "";

 

?>

 

 

Best Regards,

Shannon W.

API Support Specialist

Highlighted
Occasional Participant

Re: Error 400 from Constant Contact API Call

Hi Shannon,

 

Thanks for your attention.

 

I do already have an API key and I'm already using the php wrapper you've specified.  Using it, I'm able to add new contacts to the system.  But, when I identify an existing user and attempt to subscribe that member to a new list, a 400 error occurs.

 

Here's my code:

 

// Connecting to your account
$ConstantContact = new ConstantContact('basic', '_API_KEY_', '_USER_', '_PASSWORD_');

// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($_POST['EmailAddress']);

// If the search didnt return a contact object
if($search == false)
{
// Create a new Contact Object to store data into
$contactObj = new Contact();
// Adding multiple lists to this new Contact Object
$contactObj->lists = array($listId);
// Set the email address
$contactObj->emailAddress = $_POST['EmailAddress'];
$contactObj->firstName = $_POST["FirstName"];
$contactObj->lastName = $_POST["LastName"];
$contactObj->companyName = $_POST["CompanyName"];
$contactObj->jobTitle= $_POST["JobTitle"];
$contactObj->homePhone = $_POST["HomePhone"];
$contactObj->addr1 = $_POST["Addr1"];
$contactObj->city = $_POST["City"];
$contactObj->stateCode = $_POST["StateCode"];
$contactObj->stateName = $allStates[$_POST["StateCode"]];
$contactObj->postalCode = $_POST["PostalCode"];
$contactObj->lists = array($listId);
$contactObj->countryCode = $_POST["CountryCode"];

if( $contactObj->stateCode == 'State' ) {
$contactObj->stateCode = '';
}

// Create the Contact and DONE
$Contact = $ConstantContact->addContact($contactObj);

echo 'created';

} // Otherwise we update our existing
else
{
// Gather data from our previous search and store it into a data type
$contactObj = $ConstantContact->getContactDetails($search[0]);
var_dump($contactObj);


$isAlreadySubscribed = false;

foreach( $contactObj->lists as $subscribedTo ) {
if( $subscribedTo == $listId ) {
$isAlreadySubscribed = true;
}
}

if( !$isAlreadySubscribed ) {
// add new list to lists collection
array_push($contactObj->lists, $listId );

$contactObj->optInSource = "ACTION_BY_CONTACT";

// Update the contact and DONE
$UpdateContact = $ConstantContact->updateContact($contactObj);

if( $UpdateContact ) {
echo 'subscribed';
} else {
echo 'failed to subscribe';
}
} else {
echo 'already subscribed';
}

}

Highlighted
CTCT Employee

Re: Error 400 from Constant Contact API Call

Hi,

 

Ultimately, I believe the problem was around how the new lists were getting set.  I changed the logic around a bit, and made the code more understandable for myself to get this working code.  I believe it does what you want--just set the listId to the list number you want existing members to be added to (if not already there).

 

} // Otherwise we update our existing
else
{

	// Gather data from our previous search and store it into a data type
	$contactObj = $ConstantContact->getContactDetails($search[0]);
	var_dump($contactObj);

	$listId = "24"; //list you want to add existing members to

	$isAlreadySubscribed = false;
	foreach( $contactObj->lists as $subscribedTo ) {
		if( $subscribedTo == $listId ) {
			$isAlreadySubscribed = true;
		}
	}
		
	if( $isAlreadySubscribed ) {
		echo 'already subscribed';
	}
	else {
		array_push($contactObj->lists, $lists['lists'][$listId]->id );
		$contactObj->optInSource = "ACTION_BY_CONTACT";
		// Update the contact and DONE
		$UpdateContact = $ConstantContact->updateContact($contactObj);
		echo 'subscribed';
	}

}

 

 

Best Regards,

Shannon W.

API Support Specialist

Highlighted
Occasional Participant

Re: Error 400 from Constant Contact API Call

Hi Shannon,

 

Original comment:

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

I don't see where $lists was defined.  What is it an instance of and how did you create it?  I was storing a my list name as a string in a hidden input, and then attempting to identify its ID with the api.  How did you do it?

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

 

Updated comment:

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

I see it:

 

$lists = $ConstantContact->getLists();

 Because my lists are numbers 51-54, for now, that collection of lists does not contain those which I need.  How can I get the subsequent pages, using the API

 

Highlighted
CTCT Employee

Re: Error 400 from Constant Contact API Call

Hi,

 

You should be able to retrieve the next page of lists like this:

 

// Get a page of ContactLists
$lists = $ConstantContact->getLists();

// Get the next page of ContactLists
$moreLists = $ConstantContact->getLists($lists['nextLink']);

 

Best Regards,

Shannon W.

API Support Specialist

Developer Portal

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

Visit Page

Constant Contact Would Like To Hear From You!

We want to hear from customers like you about your favorite features and how they have helped your business or organization. Tell us by answering a few questions in...

Read More
Featured