0

Hi I want to save the data for a simple html FORM to constant contact. I can't seem to find any info on how this is done. Has anyone used their API before, if so can you shed some light as to how to process a forum and save the data with Constant Contact API

<form id="form" action="form.php">
First: <input name="first" id="first" />
Last: <input name="last" id="last" />
Address: <input name="address" id="address" />
FirstTime: <input type="checkbox" />
</form>
acctman
  • 4,229
  • 30
  • 98
  • 142

4 Answers4

2

For any poor souls who are unfortunate enough to be using Constant Contact for a simple email signup form, save yourself hours of work and just do this:

  1. Create an inline form in the Constant Contact dashboard and add the form to your page.

  2. Use CSS to hide that sucker as fast as you possibly can (display: none; will do).

  3. Create your own beautiful form (including validation) and do something like this:

    $("form.beautimus-maximus").on("submit", function(event) {
      event.preventDefault();
      var email = $(this).find("input").val();
      $(".ctct-inline-form input").val(email);
      $(".ctct-inline-form form").submit();
    });
    
  4. Lower your head in shame for what you've just done.

  5. Enjoy all the time you saved.

David Jones
  • 10,117
  • 28
  • 91
  • 139
  • I was having some trouble with the CC form causing a page refresh, so I changed the `.submit()` line to `$(".ctct-inline-form .ctct-form-button").click();`. I also decided to just display a success message, regardless of what might have really happened. I have lowered my head in even further shame. – Mike Willis Nov 15 '22 at 22:49
  • Note for anyone using `jQuery` - as of 2022-12-02, Constant Contact's script loads jQuery 2.1.4. In my situation it's overwriting window.jQuery to be 2.1.4, but leaving window.$ at my version, which happens to be 3.5.0. – Mike Willis Dec 02 '22 at 21:48
1

Constant Contact doesn't allow very simple forms like that in general because of security concerns caused by simple forms (thus the lack of online examples). That said, they provide a Signup Form Generator

That doesn't require you to code, just have access to the webpage/server you're trying to add the code to. The form generator is probably your best and fastest option, but you can also use the API - General API Documnetation to help you get started if you want to go that route (see the Code Samples link from the main page).

I hope that helps!

Shannon W.

CTCT API Support

Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
Shannon
  • 11
  • 1
1

This simple PHP example should help you. You'll have to signup for a Developer Account and then once you confirm that registration link (via email), you can then login and go to Apps & API Keys tab in the Developer Portal to create a new App and then it gives you the keys you need. As for getting a List ID, click the API Tester tab in the Developer Portal, type in your Access Token, do not click Get Access Token, and then scroll down and look for "Retrieve a collection of ContactLists". Click that link and then just click the Try It button. It will return each list you have setup as well as their numerical ID.

Note that I also have an 'ssl' array block below. I found in my case that it worked with and without that block but still ran the transaction over HTTPS.

For more information on the JSON block used for adding contacts, which has many more options for adding a contact, you can read about it on the online docs. One important extra JSON property variable to note is the confirmed property.

There's a catch, however. If that contact was added previously on a given account, then you'll get an "HTTP 409 Conflict" error. The workaround, however, is not very easy. The steps would be:

  1. Change the code below so that you add 'ignore_errors' => TRUE into the http array.
  2. If the response contains already exists, then this means that the email is already on that account and it won't let you add it into that list without that workaround. So read on....
  3. Trap that condition.
  4. Get the Contact ID by a given email address using HTTP GET on the /contacts API, passing it ?email=$sEmail&status=ALL&limit=1&api_key=$sAPIKey.
  5. Get the Contact JSON object by a given Contact ID using HTTP GET on the /contacts/{contactId} API and use json_decode() to convert that into an object in PHP.
  6. Modify the Contact JSON object so that you append a new list ID with $oJSON->lists[] = (object) array('id'=>'' . $sListID);
  7. Now save the individual Contact with the new list addition. To do this, convert the Contact JSON object into a JSON string and update the contact using HTTP PUT ON the /contacts/{contactId} API. Even if you accidentally call this step more than once, ConstantContact v2 API is smart enough to know not to add the person to the list more than once and won't error out.
<?php

error_reporting(E_ALL);
ini_set('display_errors','On');

header('Content-Type: text/plain');

// REPLACE WITH YOUR OWN
$sAPIKey = '689bnyc8td8dasxeau5bghb';
$sToken = '55de771a-dfee-453b-a654-1e62a5856231';
$sListID = 1000394510;
// END REPLACE BLOCK

// THE USER YOU WANT TO ADD, ONLY USING NAME AND EMAIL
$sEmail = 'username' . rand(1111,9999) . '@example.com';
$sFirst = 'Test';
$sLast = 'Tester'; 

$sURL = "https://api.constantcontact.com/v2/contacts?action_by=" . 
  "ACTION_BY_OWNER&api_key=$sAPIKey";

$sJSON = <<<EOD
{
  "lists": [
    {
    "id": "$sListID"
    }
  ],
  "email_addresses": [
    {
    "email_address": "$sEmail"
    }
  ],
  "first_name": "$sFirst",
  "last_name": "$sLast"
}
EOD;

$sResponse = file_get_contents($sURL,false,stream_context_create(array(
  'http'=>array(
    'method' => 'POST',
    'header' => "Authorization: Bearer $sToken\nContent-Type: application/json",
    'content' => $sJSON
  ),
  'ssl'=>array(
    'verify_peer'=>false,
    'verify_peer_name'=>false,
    'allow_self_signed'=>true,
  )
)));

echo $sResponse;
Volomike
  • 23,743
  • 21
  • 113
  • 209
  • You deserve more than 1 upvote for this. i mean really, wtf is with that conflict response?! wouldnt want to have an "append" parameter to the http array or anything. let's just have it gracelessly crash. Thanks a million – Kai Qing Jun 18 '19 at 19:46
0

Just to follow up on Volomike's answer, which should get all the credit here so upvote his, this is my expanded code that covers the conflict error. This is a procedural approach. Feel free to write a better one.

Keep in mind I had to handle this as a crisis last minute hot fix for something. I have no idea what I put in here that may be unnecessary or could be written better. I just had to mash it out fast to get it working. If there is a more complete, cleaner way to do it, feel free to write it as an answer and comment on this answer so I can plus you.

The //REPLACE WITH YOUR OWN segment - see Volomike's answer for the whole dev account process. It is very fast so don't let that discourage you. Just sign up, grab your token and keys and plug this in.

    error_reporting(E_ALL);
    ini_set('display_errors','On');

    header('Content-Type: text/plain');

    // REPLACE WITH YOUR OWN
    $sAPIKey = 'your-api-key';
    $sToken = 'your-token';
    $sListID = 11111111; //your list id
    $email = 'email-to-be-added@gmail.com';
    // END REPLACE BLOCK

    $sURL = "https://api.constantcontact.com/v2/contacts?action_by=" . 
      "ACTION_BY_OWNER&api_key=$sAPIKey";

//DONT INDENT THIS. remember heredoc needs it to be rammed right up against the wall

$sJSON = <<<EOD
{
  "lists": [
    {
    "id": "$sListID"
    }
  ],
  "email_addresses": [
    {
    "email_address": "$email"
    }
  ]
}
EOD;

    $sResponse = file_get_contents($sURL,false,stream_context_create(array(
      'http'=>array(
        'method' => 'POST',
        'header' => "Authorization: Bearer $sToken\nContent-Type: application/json",
        'content' => $sJSON,
        'ignore_errors' => TRUE
      ),
      'ssl'=>array(
        'verify_peer'=>false,
        'verify_peer_name'=>false,
        'allow_self_signed'=>true,
      )
    )));

    if(strpos($sResponse, 'http.status.email_address.conflict') > -1)
    {
        $sResponse = file_get_contents("https://api.constantcontact.com/v2/contacts?email=$email&status=ALL&limit=1&api_key=$sAPIKey",false,stream_context_create(array(
          'http'=>array(
            'header' => "Authorization: Bearer $sToken",
            'ignore_errors' => TRUE
          ),
          'ssl'=>array(
            'verify_peer'=>false,
            'verify_peer_name'=>false,
            'allow_self_signed'=>true,
          )
        )));

        $res = json_decode($sResponse);

        $id = $res->results[0]->id;
        $res->results[0]->lists[] = (object) array('id' => ''.$sListID);

        $sResponse = file_get_contents("https://api.constantcontact.com/v2/contacts/$id?action_by=ACTION_BY_OWNER&api_key=$sAPIKey",false,stream_context_create(array(
          'http'=>array(
            'method' => 'PUT',
            'header' => "Authorization: Bearer $sToken\nContent-Type: application/json",
            'content' => json_encode($res->results[0]),
            'ignore_errors' => TRUE
          ),
          'ssl'=>array(
            'verify_peer'=>false,
            'verify_peer_name'=>false,
            'allow_self_signed'=>true,
          )
        )));

        echo $sResponse;
    }
    else
    {
        // didnt have a conflict
        echo $sResponse;
    }

    //there was a problem of some kind if it reaches here
Kai Qing
  • 18,793
  • 5
  • 39
  • 57