|
<?php |
|
|
|
/** |
|
* Adds a Wordpress route `tools/subscribe` in order |
|
* to subscribe a user to Constant Contact using API v2 |
|
*/ |
|
|
|
use JetRouter\Router; |
|
use Ctct\ConstantContact; |
|
use Ctct\Components\Contacts\Contact; |
|
use Ctct\Exceptions\CtctException; |
|
|
|
$r = Router::create(); |
|
|
|
$r->options('tools/subscribe', 'subscribe_preflight', function () { |
|
header('Access-Control-Allow-Origin: *'); |
|
header('Access-Control-Allow-Methods: OPTIONS'); |
|
}); |
|
|
|
$r->post('tools/subscribe', 'subscribe', function () { |
|
header('Access-Control-Allow-Origin: *'); |
|
header('Access-Control-Allow-Methods: POST'); |
|
header('Content-Type: application/json'); |
|
|
|
$email = isset($_POST['email']) ? $_POST['email'] : null; |
|
$list = isset($_POST['list']) ? $_POST['list'] : null; |
|
|
|
if (!$email) { |
|
return wp_send_json_error([ |
|
'key' => 'no.email', |
|
'message' => 'No email address provided' |
|
]); |
|
} |
|
|
|
if (!$list) { |
|
return wp_send_json_error([ |
|
'key' => 'no.list', |
|
'message' => 'No list provided' |
|
]); |
|
} |
|
|
|
if (!isset($_ENV['CTCT_APIKEY']) || !$_ENV['CTCT_APIKEY']) { |
|
return wp_send_json_error([ |
|
'key' => 'no.apikey', |
|
'message' => 'No Constant Contact v2 API key provided' |
|
]); |
|
} |
|
|
|
if (!isset($_ENV['CTCT_ACCESSTOKEN']) || !$_ENV['CTCT_ACCESSTOKEN']) { |
|
return wp_send_json_error([ |
|
'key' => 'no.accesstoken', |
|
'message' => 'No Constant Contact v2 access token provided' |
|
]); |
|
} |
|
|
|
$cc = new ConstantContact($_ENV['CTCT_APIKEY']); |
|
|
|
// signup flow |
|
// re: https://github.com/constantcontact/php-sdk/blob/master/examples/addOrUpdateContact.php |
|
|
|
try { |
|
// check to see if a contact with the email address already exists in the account |
|
$response = $cc->contactService |
|
->getContacts($_ENV['CTCT_ACCESSTOKEN'], ['email' => $email]); |
|
// create a new contact if one does not exist |
|
if (empty($response->results)) { |
|
$contact = new Contact(); |
|
$contact->addEmail($email); |
|
$contact->addList($list); |
|
$returnContact = $cc->contactService |
|
->addContact($_ENV['CTCT_ACCESSTOKEN'], $contact); |
|
return wp_send_json([ |
|
'success' => true |
|
]); |
|
// update the existing contact if address already existed |
|
} else { |
|
$contact = $response->results[0]; |
|
if ($contact instanceof Contact) { |
|
$contact->addList($list); |
|
$returnContact = $cc->contactService |
|
->updateContact($_ENV['CTCT_ACCESSTOKEN'], $contact); |
|
return wp_send_json([ |
|
'success' => true |
|
]); |
|
} else { |
|
$e = new CtctException(); |
|
$e->setErrors(['type', 'Contact type not returned']); |
|
throw $e; |
|
} |
|
} |
|
// catch any exceptions thrown during the process |
|
} catch (CtctException $ex) { |
|
return wp_send_json_error([ |
|
'key' => 'server.error', |
|
'details' => $ex->getErrors() |
|
]); |
|
} |
|
}); |