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

Upload CSV via API with PHP

Highlighted
Developer

Upload CSV via API with PHP

Hey all! I've been trying to setup a syncronization between our mysql database and our constant contact mailling lists.

Right now I have a PHP script exporting CSV files of all the lists I need every night. However, my understanding of the bulk contacts operations documented here: http://community.constantcontact.com/t5/Documentation/Creating-an-Add-Contacts-Remove-Contacts-Activ... is lacking.

 

If anyone has some simple PHP code, showing how to POST a CSV file into a Constant Contact list, I'd be very grateful.

 

Thanks

22 REPLIES 22
Highlighted
Employee

Re: Upload CSV via API with PHP

Hey,

 

This code should do the trick.  It will need to be modified to fit your needs of course. The $_GET['x'] was implented to gather columns as this was made to break down a massive csv into specific lists.

 

set_time_limit(15000);
require 'ConstantContact.php';

// Authentication to Constant Contact
$ConstantContact = new ConstantContact("basic", "YOUR APIKEY", "YOUR USERNAME", "YOUR PASSWORD");

// Set row value
$row = 1;

// Start the URI of which to pass to bulk activities
$BeforeEmailAddress = "activityType=SV_ADD&data=Email+Address";

// set value of totalContacts
$totalContacts = 0;

// Used for to pass in the column number for large CSV 
// You may want to remove this depending on your integration

$x = $_GET['x'];

if (($handle = fopen("YOURCSVFILE.csv", "r")) !== FALSE) {
	
	// itterate through rows
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    	// how many columns are in a row
        $num = count($data);
        
        // use echo for testing
        //echo "<p> $num fields in line $row: <br /></p>\n";

        $row++;
        // $c = 0 if your not using X;
        // data[0] is your first column, this needs to contain your email address
        for ($c=$x; $c < ($x+1); $c++) {
		
                // Checks for value of "x" as this meant that the contact
                // belongs to the current column list
	
        	if ($data[$c] == "x" && $totalContacts < 20000) {
        		$emailAddress .= "\n" . $data[0];
        		$totalContacts++;
                // Bulk activities have a limit of 20k contacts you must have more than 20 contacts
                // to submit the contacts via bulk activity

                // if contacts are over 20k then you need to start a new activity
        	}else if($data[$c] == "x" && $totalContacts >= 20000){
        		$emailAddress2 .= "\n" . $data[0];
        		$totalContacts++;
        	}

        }
        
    }
    // $lv sets your list value and $c can be added to or subtracted to offset difference in list value
    // for example, column in excel = 3 but list = 4 
    // $lv = $c +1;

    $lv = $c; 
    $list = "http://api.constantcontact.com/ws/customers/YOURUSERNAME/lists/".$lv;
   
    fclose($handle);
}
// Echo's the string to verify that you are targeting the correct information to the correct list
echo $BeforeEmailAddress.urlencode($emailAddress)."&".urlencode($list);
 
        // Remove below echo statement to make this script active, always test as your contacts may go to the wrong list

	//echo $ConstantContact->bulkAddContacts($BeforeEmailAddress.urlencode($emailAddress)."&lists=".urlencode($list));
	
        // Start second bulk load activity if more than 20k contacts existed.

	if(isset($emailAddress2))
	{
		//echo $ConstantContact->bulkAddContacts($BeforeEmailAddress.urlencode($emailAddress2)."&lists=".urlencode($list));;
	}
// Tells you how many contacts were uploaded to which list id.
echo $totalContacts . " Have been uploaded to " . $list;
?>

 You do need the wrapper to use this which is found under code samples. 

 

Let me know if this helps.

Ryan Davis
Quality Engineer
Highlighted
Developer

Re: Upload CSV via API with PHP

 

This is very helpful... as in it actually makes a batch upload and adds to the activity list; however, the upload dies there with this error:

Lists:  Status:  Insert Time:  Run Start Time:  Run Finish Time:  Uploaded File Name:  Number of Contacts:  Number of Errors:  Invalid Email Addresses:  

WHITE
Complete
12/7/2011 3:50 PM PST
12/7/2011 3:51 PM PST
12/7/2011 3:51 PM PST
A file was not used for this activity
1
1
email address (invalid format)

My CSV looks like this, but 780 emails long.

"test@example.com"

"test@gmail.com"

"test@hotmail.com"

 

I've been trying to find out what's wrong and I'm sure I will eventually, but maybe you can help speed me a long again. :)

Highlighted
Employee

Re: Upload CSV via API with PHP

Hey,

 

Sure thing, post the code how you have it just remove your constant contact credentials.  It sounds like there is an error in the CSV however.  You can email the CSV file and the code if you would like to webservices@constantcontact.com

Ryan Davis
Quality Engineer
Highlighted
Developer

Re: Upload CSV via API with PHP

Oh... I started picking the script a part and I think I found the problem in this line: 

if ($data[$c] == "x" && $totalContacts < 20000) {

I changed it to

if ($data[$c] == $x && $totalContacts < 20000) {

and things started working splendidly. 

I still have to try a CSV with over 20000 people, but I'm sure I'll figure it out from there.

 

Thanks for your support!

Highlighted
Developer

Re: Upload CSV via API with PHP

Here's the code I finally settled with... it works on my list of 46000 email addresses. :)

<?PHP
set_time_limit(0);
require 'ConstantContact.php';

###Fill out all this information!###
$username = 'user_name';
$key = "apikey";
$password = "password";
$listNumber = 1;
$FILENAME = "./temp/filename.csv";

//You shouldn't have to edit anything below this line, unless you have a file with greater than 60,000 rows

// Authentication to Constant Contact
$ConstantContact = new ConstantContact("basic", "$key", "$username", "$password");

// Set row value
$row = 1;

// Start the URI of which to pass to bulk activities
$BeforeEmailAddress = "activityType=SV_ADD&data=Email+Address";

// set value of totalContacts
$totalContacts = 0;

// Used for to pass in the column number for large CSV 
// You may want to remove this depending on your integration

$x = $_GET['x'];

if (($handle = fopen("$FILENAME", "r")) !== FALSE) {
	
	// itterate through rows
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    	// how many columns are in a row
        $num = count($data);
        
        // use echo for testing
        //echo "<p> $num fields in line $row: <br /></p>\n";

        $row++;
        // $c = 0 if your not using X;
        // data[0] is your first column, this needs to contain your email address
        for ($c=$x; $c < ($x+1); $c++) {
          echo "<b>$c</b><br>";
                // Checks for value of "x" as this meant that the contact
                // belongs to the current column list
	
        	if ($data[$c] == $x && $totalContacts < 20000) {
        		$emailAddress .= "\n" . $data[0];
        		$totalContacts++;
                // Bulk activities have a limit of 20k contacts you must have more than 20 contacts
                // to submit the contacts via bulk activity

                // if contacts are over 20k then you need to start a new activity
        	}else if($data[$c] == $x && $totalContacts >= 20000 && $totalContacts < 40000){
        		$emailAddress2 .= "\n" . $data[0];
        		$totalContacts++;
        	}else if($data[$c] == $x && $totalContacts >= 40000){
        		$emailAddress3 .= "\n" . $data[0];
        		$totalContacts++;
        	}

        }
        
    }

    $lv = $listNumber; 
    $list = "http://api.constantcontact.com/ws/customers/$username/lists/".$lv;
   
    fclose($handle);
}
// Echo's the string to verify that you are targeting the correct information to the correct list
echo $BeforeEmailAddress.urlencode($emailAddress)."&".urlencode($list);
 
        // Remove below echo statement to make this script active, always test as your contacts may go to the wrong list

	$ConstantContact->bulkAddContacts($BeforeEmailAddress.urlencode($emailAddress)."&lists=".urlencode($list));
	
        // Start second bulk load activity if more than 20k contacts existed.

	if(isset($emailAddress2))
	{
		$ConstantContact->bulkAddContacts($BeforeEmailAddress.urlencode($emailAddress2)."&lists=".urlencode($list));;
	}
	if(isset($emailAddress3))
	{
		$ConstantContact->bulkAddContacts($BeforeEmailAddress.urlencode($emailAddress3)."&lists=".urlencode($list));;
	}

// Tells you how many contacts were uploaded to which list id.
echo "<br>".$totalContacts . " Have been uploaded to " . $list;
?>

 

Highlighted
Occasional Contributor

Re: Upload CSV via API with PHP

Hi Ryan,

 

I am getting the following response using the above code(bulkAddContacts form csv). Can you please suggest me where am i going wrong.

 

Array ( [xml] =>

HTTP Status 401 - Invalid signature for signature method HMAC-SHA1


type Status report

message Invalid signature for signature method HMAC-SHA1

description This request requires HTTP authentication (Invalid signature for signature method HMAC-SHA1).

 

 

Thanks,

Harika

Highlighted
Employee

Re: Upload CSV via API with PHP

Hey,

 

The 401 would be that you are not setting your credentials correctly.  You would want to change where $ConstantContact = new ConstantContact(".....") to your own information.

 

Please let me know if this helps.

Ryan Davis
Quality Engineer
Highlighted
Occasional Contributor

Re: Upload CSV via API with PHP

 

Thanks a lot Ryan. It works.

 

I was using 'oauth'. Changing it to basic works.

 

Changed the following

$ConstantContact = new ConstantContact('oauth', $apiKey, $DatastoreUser['username'], $consumerSecret);

 

 

to
$ConstantContact = new ConstantContact("basic", $apiKey, $username,$password);

Highlighted
Employee

Re: Upload CSV via API with PHP

Hey,

 

If you are using oAuth, it sounds like there is somethign wrong with your token or access has not been granted.  Are you verifying with the example_verification.php example?

Ryan Davis
Quality Engineer
Developer Portal

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

Visit Page

Constant Contact 2020 End of Summer Community Sweepstakes!

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

Read More
Featured