cancel
Showing results for 
Search instead for 
Did you mean: 

PHP Subscription Form using ACTION_BY_VISITOR

SOLVED
Highlighted
All Star

PHP Subscription Form using ACTION_BY_VISITOR

I'm a noob who could really use help. I'm adapting the sample v2 code addOrUpdateConact.php. The form will be used by customers to subscribe to my lists (I have 88 of them). I can't seem to figure out how to make updateContact(ACCESS_TOKEN, $contact, true); work with the form as-is. The only major changes I made to the same code is that I'm trying to use checkboxes rather than an option list so people can subscribe to multiple lists at once.

 

I think I want to use ACTION_BY_VISITOR because my form is intended for use by customers, not list owners. 

 

Note: I'm using a foreach loop and sorting to show only a subset of my complete list based on list name prefixes. 

 

Original code:

https://github.com/constantcontact/php-sdk/blob/development/examples/addOrUpdateContact.php

 

My changes

<!DOCTYPE HTML>
<html>
<head>
    <title>Constant Contact API v2 Add/Update Contact Example</title>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
    <link href="examples/styles.css" rel="stylesheet">
</head>

<!--
README: Add or update contact example
This example flow illustrates how a Constant Contact account owner can add or update a contact in their account. In order for this example to function 
properly, you must have a valid Constant Contact API Key as well as an access token. Both of these can be obtained from 
http://constantcontact.mashery.com.
-->

<?php
// require the autoloaders
require_once 'src/Ctct/autoload.php';
require_once 'vendor/autoload.php';

use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Exceptions\CtctException;

// Enter your Constant Contact APIKEY and ACCESS_TOKEN
define("APIKEY", "");
define("ACCESS_TOKEN", "");

$cc = new ConstantContact(APIKEY);

// attempt to fetch lists in the account, catching any exceptions and printing the errors to screen
try {
    $lists = $cc->listService->getLists(ACCESS_TOKEN);
} catch (CtctException $ex) {
    foreach ($ex->getErrors() as $error) {
        print_r($error);
    }
    if (!isset($lists)) {
        $lists = null;
    }
}

// check if the form was submitted
if (isset($_POST['email']) && strlen($_POST['email']) > 1) {
    $action = "Getting Contact By Email Address";
    try {
        // check to see if a contact with the email address already exists in the account
        $response = $cc->contactService->getContacts(ACCESS_TOKEN, array("email" => $_POST['email']));

        // create a new contact if one does not exist
        if (empty($response->results)) {
            $action = "Creating Contact";

            $contact = new Contact();
            $contact->addEmail($_POST['email']);
            $contact->addList($_POST['list']);
            $contact->first_name = $_POST['first_name'];
            $contact->last_name = $_POST['last_name'];

            /*
             * The third parameter of addContact defaults to false, but if this were set to true it would tell Constant
             * Contact that this action is being performed by the contact themselves, and gives the ability to
             * opt contacts back in and trigger Welcome/Change-of-interest emails.
             *
             * See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
             */
            $returnContact = $cc->contactService->addContact(ACCESS_TOKEN, $contact);

            // update the existing contact if address already existed
        } else {
            $action = "Updating Contact";

            $contact = $response->results[0];
            if ($contact instanceof Contact) {
                $contact->addList($_POST['list']);
                $contact->first_name = $_POST['first_name'];
                $contact->last_name = $_POST['last_name'];

                /*
                 * The third parameter of updateContact defaults to false, but if this were set to true it would tell
                 * Constant Contact that this action is being performed by the contact themselves, and gives the ability to
                 * opt contacts back in and trigger Welcome/Change-of-interest emails.
                 *
                 * See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
                 */
                $returnContact = $cc->contactService->updateContact(ACCESS_TOKEN, $contact, true);
            } else {
                $e = new CtctException();
                $e->setErrors(array("type", "Contact type not returned"));
                throw $e;
            }
        }

        // catch any exceptions thrown during the process and print the errors to screen
    } catch (CtctException $ex) {
        echo '<span class="label label-important">Error ' . $action . '</span>';
        echo '<div class="container alert-error"><pre class="failure-pre">';
        print_r($ex->getErrors());
        echo '</pre></div>';
        die();
    }
}

	//build a subset array based on list prefix
	$baArray = array();
	$baString = 'WMRC BA';
	
	foreach($lists as $list) {
		//print_r($list->name); // this works
		if (strpos($list->name, $baString) === 0) {
			array_push($baArray, $list);
		}
	}
	
	//sort the sub-set array
	function cmp ($a, $b) {
		return strcmp($a->name, $b->name);
	}
	usort($baArray, "cmp");
?>

<body>
<div class="well">
    <h1>Add or Update a Contact</h1>

    <form class="form-horizontal" name="submitContact" id="submitContact" method="POST" action="wmrc-list.php">
        <div class="control-group">
            <label class="control-label" for="email">Email</label>

            <div class="controls">
                <input type="email" id="email" name="email" placeholder="Email Address">
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="first_name">First Name</label>

            <div class="controls">
                <input type="text" id="first_name" name="first_name" placeholder="First Name">
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="last_name">Last Name</label>

            <div class="controls">
                <input type="text" id="last_name" name="last_name" placeholder="Last Name">
            </div>
        </div>
		<h2>Receive Email for Which Topics?</h2>
		<p>Please select the items about which you are interested in receiving information.</p>
        <div class="control-group">
			<h3>Waste Management and Radiation Control Board</h3>
            <div class="controls">
        		<?php
					foreach ($baArray as $list) {
						echo '<input type="checkbox" name="' . $list->name . '"' . ' value="' . $list->id . '">'. substr($list->name, 10) . '<br>' . "\n";
					}
				?>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">
                <div class="controls">
                    <input type="submit" value="Submit" class="btn btn-primary"/>
                </div>
        </div>
    </form>
</div>

<!-- Success Message -->
<?php if (isset($returnContact)) {
    echo '<div class="container alert-success"><pre class="success-pre">';
    print_r($returnContact);
    echo '</pre></div>';
} ?>

</body>
</html>

 

1 REPLY 1
Moderator

Re: PHP Subscription Form using ACTION_BY_VISITOR

Hello,

 

At first glance the issue appears to be that you are dynamically adding checkboxes to the form, and the name="" field is being populated with the list name. But when you are creating or updating your contact object before sending it to Constant Contact, you are using the addList() function and only passing through $_POST['list'] which doesn't match to any field in your form.

 

For this to work you would need to iterate through each of your $_POST variables, find the lists, make sure they are checked off, and then use addList() to add that list ID to your contact object.

 

Please let me know if you have any other questions!

 

Regards,
David B.
Tier II API Support Engineer