Small fix to prior...check for CURL errors before closing... <?php
//error_reporting(E_ALL);
$apikey = "API KEY";
$token = "AUTHENTICATION TOKEN";
$listid = "LIST ID";
$email = "EMAIL";
$first_name = "FIRST NAME";
$last_name = "LAST NAME";
$url = "https://api.constantcontact.com/v2/contacts?email=$email&status=ALL&limit=50&api_key=$apikey";
$header[] = "Authorization: Bearer $token";
$header[] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch));
if(curl_error($ch))
{
echo 'CURL Error:' . curl_error($ch);
exit;
}
curl_close($ch);
// Check if exists and on list already
$list_array = [$listid]; // new list
$contactid = '';
if($response->results)
{
$contactid = $response->results[0]->id;
$lists = $response->results[0]->lists;
// Need to save existing lists!
foreach($lists as $obj)
{
if ($obj->id == $listid) continue; // already on this list
$list_array[] = $obj->id;
}
}
// If contact exists, will update, else add.
// If updating, can even change name, other fields. Probably just add a new list, tho.
if ($contactid)
{
$contactid = "/$contactid";
}
$url = "https://api.constantcontact.com/v2/contacts$contactid?action_by=ACTION_BY_VISITOR&api_key=$apikey";
$body = '{
"lists":
[';
foreach ($list_array as $listid)
{
$body .= '{"id": "' . $listid . '"},';
}
$body = substr($body,0,strlen($body)-1); // drop last comma
$body .= '],
"confirmed": false,
"email_addresses":
[
{"email_address": "'. $email .'"}
],
"first_name": "' . $first_name . '",
"last_name": "' . $last_name . '"
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
if ($contactid)
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // PUT to update contact
}
else
{
curl_setopt($ch, CURLOPT_POST, 1); // Post to add contact
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch , CURLINFO_HTTP_CODE);
if(curl_error($ch))
{
echo 'CURL Error:' . curl_error($ch);
exit;
}
curl_close($ch);
echo "Response: ";
var_dump($response);
?>
... View more