sepiariver
11/20/2014 - 1:36 AM

POST newsletter signup submissions to iContact via custom FormIt hook

POST newsletter signup submissions to iContact via custom FormIt hook

<?php
/*
 * @author @sepiariver
 *
 * GPL, no warranties, no liability, etc.
 *
 * USAGE EXAMPLE:
 * [[!FormIt? &hooks=`iContactPost`]]
 *
 * NOTE: using iContact's API would be a more robust approach 
 * http://www.icontact.com/developerportal/
 */
// Allow customization of API URL via FormIt $scriptProperties
$url = $hook->formit->config['url'];
$url = (!empty($url)) ? $url : 'https://app.icontact.com/icp/signup.php';
// Placeholder to output response from iContact
$icsph = $hook->formit->config['iContactSuccessPlaceholder'];
$icsph = (!empty($icsph)) ? $icsph : 'icontact_success';
// Get all FormIt values into an array, post-sanitation
$values = $hook->getValues();

// Initialize curl, set some options
$curl = curl_init();
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
// POST the values array
curl_setopt($curl, CURLOPT_POSTFIELDS, $values);
curl_setopt($curl, CURLOPT_URL, $url);
// Save the response
$response = curl_exec($curl);
curl_close($curl);

if ($response) {
	/* Hook succeeds. We add the iContact response to the placeholder. 
	 * NOTE: using this method of POSTing to their form URL, iContact returns a 200 response 
	 * code even if the submission failed or is invalid.
	 * Therefore it's a good idea to parse the $response in some way, or at least output it 
	 * to the placeholder as feedback to the user.
	 */
	$hook->setValue($icsph, $response);
	// FormIt will output $successMessage by default and execute the next hook.
	return true;
} else {
	// Hook fails. Log and output error messages
	$hook->addError('api', 'Sorry no response at the moment.');
	$modx->log(xPDO::LOG_LEVEL_ERROR,'NO response from iContact API.');
	return false;
}