We all started somewhere! Share your experience on the Get Advice: Let's Get Started Sweepstakes thread and be entered to win a $100 credit on your Constant Contact account.

Upload CSV via API with PHP

markwarrick
Regular Participant

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
Ryan_D
Employee

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
markwarrick
Regular Participant

 

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. :)

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
markwarrick
Regular Participant

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!

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

 

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

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
PradeepkarR
Regular Participant

 

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

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
PradeepkarR
Regular Participant

Hi Rayn,

 

In example_verification.php, when i print the array

 

$sessionConsumer = array(
'key' => $CTCTOAuth->access_token->key,
'secret' => $CTCTOAuth->access_token->secret,
'username' => $CTCTOAuth->username
);

 

i am not getting any values for key and secret.

 

Array ( [key] => [secret] => [username] => myusername)

 

What is $_SESSION['return'] used for and what sould be its value.

 

I am getting the request token (requestToken).

 

Am i not getting the access token or what might be the issue.

 

 

 

 

Thanks,

Harika

 

Hey,

 

When you set your oAuth did you specify the consumer secret with your apikey?  Also when you go to the page and the verification link shows and you grant access.  I would print the session to see what is showing up.  See if you have any empty vars.

 

print_r($_SESSION);

 after the session_start()

Ryan Davis
Quality Engineer
PradeepkarR
Regular Participant

 

I have the the query string

  

session variable 'return' is empty.

Hey,

 

I removed the session information as it could cause a security risk to your account. It sounds like it is having trouble authenticating.  I just released the new Campaign Sample forms which uses oAuth.  I would suggest taking a look at them and printing sesssion in the campaign.php file.  That may show you what you are missing.  https://sourceforge.net/projects/ctctphpcampaign/

 

 

Ryan Davis
Quality Engineer
PradeepkarR
Regular Participant

Hey,

 

oAuth is working fine in new Campaign Sample form. I could create a sample campaign.

Hey,

 

I would check to see what the difference between the verification and the authentication is and try to modify your code to meet the difference. 

Ryan Davis
Quality Engineer
PradeepkarR
Regular Participant

 

Hi Ryan.

 

I am getting the error if i try to authenticate from verification.php

 

An error has occurred. Please contactus for details

 

 

campaign.php is fine. I am able to authenticate from here and able to create a sample campaign.

Hey,

 

It is working fine in new Campaign Sample form. Let me check old wrapper classes.

Hey,

 

It sounds like you are not passing a username in to lookup and its looking for "USERNAME" as the username.  Thus getting an authentication error cause your granting access to your own username.

Ryan Davis
Quality Engineer
PradeepkarR
Regular Participant

 

I am passing the user the username. I had changed it while posting in the forum.

Hey,

 

Can you send your project to webservices@constantcontact.com so I can take a look at it.

Ryan Davis
Quality Engineer
Developer Portal

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

Visit Page