cancel
Showing results for 
Search instead for 
Did you mean: 
Constant Contact wants to help you succeed! We’re celebrating our professional service programs on the Constant Contact Community this month and you have a chance to try one of the services for free! Learn more.

Any sample PHP for bulk-adding contacts?

Occasional Contributor

Any sample PHP for bulk-adding contacts?

I've been working with the sample code in the SDK, but all I can find are scripts that add contacts one at a time. I really need to be able to bulk-add contacts, and while I know the API supports this, I can't find any sample code that illustrates it. Does such sample code exist? Thanks, Matthew
8 REPLIES 8
CTCT Employee

Re: Any sample PHP for bulk-adding contacts?

Hi Matthew,

 

We do have a small example in the PHP unit tests folder in the PHP sdk for adding contacts.  If you go to this unit test link, you can find a testAddCreateContactsActivity function, which shows how you can use the add contacts bulk activity method.

 

Best Regards,

Shannon W.

API Support Specialist

CTCT Employee

Re: Any sample PHP for bulk-adding contacts?

Also check out the bulk add contact activity example here, which takes the contact data from a file.

 

Best Regards,

Shannon W.

API Support Specialist

Occasional Contributor

Re: Any sample PHP for bulk-adding contacts?

Hi Shannon, thanks for your reply.

 

The first link looks helpful, but the second link isn't working. Is that info available anywhere else, or could you post the code here?

 

Thanks,

 

Matthew

CTCT Employee

Re: Any sample PHP for bulk-adding contacts?

Hi Matthew,

 

Sorry about that.  That might be an internal link.  The contents of the page are this script.  You probably only need the first few lines, and then to use the appropriate services in the PHP wrapper.  Here is all of it for completeness.

 

// Usage
$accessToken = 'your access token';
$cc = new ConstantContact($accessToken);

$response = $cc->addCreateContactsActivityFromFile(
    $accessToken,
    'contacts.txt',
    file_get_contents('/Users/johndoe/Desktop/contacts.txt'),
    '7'
);


// ConstantContact.php
 /**
     * Create an Add Contacts Activity from a file. Valid file types are txt, csv, xls, xlsx
     * @param string $accessToken - Constant Contact OAuth2 access token
     * @param string $fileName - The name of the file (ie: contacts.csv)
     * @param string $contents - The contents of the file
     * @param string $lists - Comma separated list of ContactList id's to add the contacts to
     * @return Activity
     */
    public function addCreateContactsActivityFromFile($accessToken, $fileName, $contents, $lists)
    {
        return $this->activityService->createAddContactsActivityFromFile($accessToken, $fileName, $contents, $lists);
    }


// ActivityService.php

/**
     * Create an Add Contacts Activity from a file. Valid file types are txt, csv, xls, xlsx
     * @param string $accessToken - Constant Contact OAuth2 access token
     * @param string $fileName - The name of the file (ie: contacts.csv)
     * @param string $contents - The contents of the file
     * @param string $lists - Comma separated list of ContactList id's to add the contacts to
     * @return \Ctct\Components\Activities\Activity
     */
    public function createAddContactsActivityFromFile($accessToken, $fileName, $contents, $lists)
    {
        $eol = "\r\n";
        $data = '';
        $boundary=md5(time());

        $data .= '--' . $boundary . $eol;
        $data .= 'Content-Disposition: form-data; name="file_name"' . $eol;
        $data .= 'Content-Type: text/plain' . $eol . $eol;
        $data .= $fileName . $eol;

        $data .= '--' . $boundary . $eol;
        $data .= 'Content-Type: text/plain' . $eol;
        $data .= 'Content-Disposition: form-data; name="lists"' . $eol . $eol;
        $data .= $lists . $eol;

        $data .= '--' . $boundary . $eol;
        $data .= 'Content-Disposition: form-data; name="data"' . $eol . $eol;
        $data .= $contents . $eol;
        $data .= "--" . $boundary . "--" . $eol;

        $headers = array(
            "Authorization: Bearer {$accessToken}",
            "Content-Type: multipart/form-data; boundary={$boundary}"
        );

        $baseUrl = Config::get('endpoints.base_url') . Config::get('endpoints.add_contacts_activity');
        $url = $this->buildUrl($baseUrl);

        $response = parent::getRestClient()->post($url, $headers, $data);
        return Activity::create(json_decode($response->body, true));
    }

 

 

Best Regards,

Shannon W.

API Support Specialist

Re: Any sample PHP for bulk-adding contacts?

On average, how long should it take before one is to see the added contacts show up in the specified list?  My $response object has all its fields except for the following:

 

["status"]=> NULL ["start_date"]=> NULL ["finish_date"]=> NULL

 

However, my contacts are not being populated to the specified list in Constant Contact.  Does this take time?  Should the object have a status, start_date and finish_date?  If so, the example given doesn't appear to require these.

 

Thanks

Moderator

Re: Any sample PHP for bulk-adding contacts?

Our Bulk Activity API is an async queued processing job.  What you create with that request is a queued import activity.  This will be processed by our batch import services in a FIFO manner with all of our customer imports.

 

Generally, this only takes 10-20 minutes (or less) depending on the size of your file.  However, during peak times you could see this take longer.  Also, if you import multiple activities at the same time, we process those imports serially,  IE if you import jobs A, B and C, B can't start until A is complete.  This is to prevent any one customer from taking over our entire batch import bandwidth with a large number of jobs. 

 

Hope this helps, you can read more about this here: http://developer.constantcontact.com/docs/bulk_activities_api/bulks-activities-import-contacts-api.h...

Dave Berard
Senior Product Manager, Constant Contact
Occasional Contributor

Re: Any sample PHP for bulk-adding contacts?

Hi,

 

I tried applying this below code

 

$cc = new ConstantContact(APIKEY);
$contact = new AddContactsImportData();
$cid[0]['email'] = "devteam@DOMAINNAME.com";
$cid[0]['first_name'] = "ufname";
$cid[0]['last_name'] = "ulnam";

$cid[1]['email'] = "devteam01@DOMAINNAME.com";
$cid[1]['first_name'] = "ufname01";
$cid[1]['last_name'] = "ulname01";
foreach($cid as $elem)
{
$contact->first_name = $elem['first_name'];
$contact->last_name = $elem['last_name'];
$contact->addEmail($elem['email']);
}
$addContacts = new AddContacts(array($arr),array("1904872245"));

 

But it's not giving correct output, any method how to add bulk contacts through this function

 

$return = $cc->addCreateContactsActivity(ACCESS_TOKEN,$addContacts);

 

My Moto is only to add bulk contacts to my selected list id.

CTCT Employee

Re: Any sample PHP for bulk-adding contacts?

Hi,

 

I don't have an example that doesn't use a file right now, but this code will import a file using one of the bulk import functions in the PHP SDK.

 

define("APIKEY", "xxx");
define("ACCESS_TOKEN", "xxx");

$cc = new ConstantContact(APIKEY);

try {
	$listID = "xxx"; //insert your list ID
        $directory = __DIR__ . '/new list';	
      	$fileName = 'test.csv'; //change to your fileName
      	$contents = file_get_contents($directory . '/' . $fileName);
      	$fillList = $cc->addCreateContactsActivityFromFile(ACCESS_TOKEN, $fileName, $contents, $listID);

} catch (CtctException $ex) {  //catch & print exceptions
        print json_encode(array('status'=>'failure', 'message'=>$ex->getMessage()));
}

 

You might consider catching the errors from your script to see what the problem is, if you don't want to use a file. I hope that helps!

 

Best Regards,

Shannon Wallace

Partner API Support Engineer