Skip to content

Instantly share code, notes, and snippets.

@wpconsulate
Last active June 30, 2020 15:41
Show Gist options
  • Save wpconsulate/40418d25f7b49b7e7f3fb497a64c14a3 to your computer and use it in GitHub Desktop.
Save wpconsulate/40418d25f7b49b7e7f3fb497a64c14a3 to your computer and use it in GitHub Desktop.
<?php
define( 'CC_API_VER', '3');
define( 'CC_API_KEY', 'CC_KEY_HERE');
define( 'CC_API_SECRET', 'SECRET HERE');
define( 'CC_CREDS_FILE', dirname(__FILE__) .'/cccreds.json' );
define( 'CC_REDIRECT_URI', 'https://abbalist.org/service-listings' );
define( 'CC_REFRESH_INTERVAL', 60*60*2 ); // In seconds 60 seconds * 60 Mins * 24 hours
define( 'CC_POPUP_TIMEOUT', 30 ); // In secnods
if( ! function_exists('pr') ){
function pr( $arr , $dye = 0){
$root = debug_backtrace();
$file = str_replace($_SERVER['DOCUMENT_ROOT'],'',$root[0]['file']);
$string = '</br>Line: '.$root[0]['line'].'</br>File : '.$file;
echo "<pre>";
print_r($arr);
echo "</pre>";
if($dye == 1){
die($string);
}
}
}
/*
* This function can be used to generate the URL an account owner would use to allow your app to access their account.
* After visiting the URL, the account owner is prompted to log in and allow your app to access their account.
* They are then redirected to your redirect URL with the authorization code appended as a query parameter. e.g.:
* http://localhost:8888/?code={authorization_code}
*/
/***
* @param $redirectURI - URL Encoded Redirect URI
* @param $clientId - API Key
* @return string - Full Authorization URL
*/
function getAuthorizationURL($redirectURI, $clientId) {
// Create authorization URL
$baseURL = "https://api.cc.email/v3/idfed";
$authURL = $baseURL . "?client_id=" . $clientId . "&scope=contact_data&response_type=code" . "&redirect_uri=" . $redirectURI;
return $authURL;
}
/*
* This function can be used to exchange an authorization code for an access token.
* Make this call by passing in the code present when the account owner is redirected back to you.
* The response will contain an 'access_token' and 'refresh_token'
*/
/***
* @param $redirectURI - URL Encoded Redirect URI
* @param $clientId - API Key
* @param $clientSecret - API Secret
* @param $code - Authorization Code
* @return string - JSON String of results
*/
function getAccessToken($redirectURI, $clientId, $clientSecret, $code) {
// Use cURL to get access token and refresh token
$ch = curl_init();
// Define base URL
$base = 'https://idfed.constantcontact.com/as/token.oauth2';
// Create full request URL
$url = $base . '?code=' . $code . '&redirect_uri=' . $redirectURI . '&grant_type=authorization_code&scope=contact_data';
curl_setopt($ch, CURLOPT_URL, $url);
// Set authorization header
// Make string of "API_KEY:SECRET"
$auth = $clientId . ':' . $clientSecret;
// Base64 encode it
$credentials = base64_encode($auth);
// Create and set the Authorization header to use the encoded credentials
$authorization = 'Authorization: Basic ' . $credentials;
curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization));
// Set method and to expect response
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Make the call
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/*
* This function can be used to exchange a refresh token for a new access token and refresh token.
* Make this call by passing in the refresh token returned with the access token.
* The response will contain a new 'access_token' and 'refresh_token'
*/
/***
* @param $refreshToken - The refresh token provided with the previous access token
* @param $clientId - API Key
* @param $clientSecret - API Secret
* @return string - JSON String of results
*/
function refreshToken($refreshToken, $clientId, $clientSecret) {
// Use cURL to get a new access token and refresh token
$ch = curl_init();
// Define base URL
$base = 'https://idfed.constantcontact.com/as/token.oauth2';
// Create full request URL
$url = $base . '?refresh_token=' . $refreshToken . '&grant_type=refresh_token';
curl_setopt($ch, CURLOPT_URL, $url);
// Set authorization header
// Make string of "API_KEY:SECRET"
$auth = $clientId . ':' . $clientSecret;
// Base64 encode it
$credentials = base64_encode($auth);
// Create and set the Authorization header to use the encoded credentials
$authorization = 'Authorization: Basic ' . $credentials;
curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization));
// Set method and to expect response
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Make the call
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function write_file( $file, $contents ){
$fp = fopen($file, "w");
fwrite($fp, $contents);
fclose($fp);
}
function saveAccessToken( $response ){
write_file(CC_CREDS_FILE, $response);
}
function getLocalAccessToken(){
$tokenContents = file_get_contents(CC_CREDS_FILE);
if($tokenContents){
$tokenContents = json_decode($tokenContents);
return $tokenContents;
}
return null;
}
function createContact($accessToken, $email, $name, $useful, $findHow){
try {
// Use cURL to get a new access token and refresh token
$ch = curl_init();
// Define base URL
$url = 'https://api.cc.email/v3/contacts';
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>"
{
\"email_address\": {
\"address\": \"{$email}\",
\"permission_to_send\": \"implicit\"
},
\"first_name\": \"{$name}\",
\"last_name\": \"\",
\"create_source\": \"Account\",
\"custom_fields\": [
{
\"custom_field_id\": \"7ba14cea-ad71-11ea-bd4b-d4ae5275396f\",
\"value\": \"{$findHow}\",
},
{
\"custom_field_id\": \"ecd225e8-77ab-11ea-aa18-d4ae528eade9\",
\"value\": \"{$useful}\",
}
]
}
",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/json",
"Accept: application/json",
"Authorization: Bearer {$accessToken}"
),
));
// Make the call
$result = curl_exec($ch);
$result = json_decode($result);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode === 409){
return "Contact already exists!";
}
if( isset($result->contact_id) )
return "Thanks you for your submission.";
return "Something went wrong please try again.";
} catch (HttpException $ex) {
echo $ex;
}
}
function getValidAccessToken(){
$tokenContents = null;
// $authURL = getAuthorizationURL(CC_REDIRECT_URI, CC_API_KEY);
if($tokenContents = getLocalAccessToken()){
// pr($tokenContents, 1);
// Now check for access token
$lastUpdate = filemtime(CC_CREDS_FILE);
// If time is due to refresh
if( time() > ( $lastUpdate + CC_REFRESH_INTERVAL ) ){
$res = refreshToken($tokenContents->refresh_token, CC_API_KEY, CC_API_SECRET);
saveAccessToken($res);
$tokenContents = json_decode($res);
}
}else{
}
return $tokenContents;
}
if(isset($_GET['code']) && trim($_GET['code']) != "" ){
$res = getAccessToken( CC_REDIRECT_URI, CC_API_KEY, CC_API_SECRET, $_GET['code'] );
saveAccessToken( $res );
header('Location: ' . CC_REDIRECT_URI);
exit;
}
if(isset($_POST['infouseful']) && trim($_POST['infouseful']) != "" ){
$tokenData = getValidAccessToken();
$infouseful = $_POST['infouseful'];
$findHow = implode(' | ',$_POST['findHow']);
$name = $_POST['name'];
$email = $_POST['email'];
$res = createContact($tokenData->access_token, $email, $name, $infouseful, $findHow);
// pr($res, 1);
header('Location: ' . CC_REDIRECT_URI.'?ccsubmitted');
exit;
}
?>
<!-- <button id="myBtn">Open Modal</button> -->
<!-- popup start -- >
<!-- The Modal -->
<div id="myModal" class="modal-pop">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">We'd Welcome your Feedback</h4>
</div>
<div class="modal-body-area">
<?php
if(!isset($_GET['ccsubmitted'])){
?>
<form id="popupSubs" action="<?php echo CC_REDIRECT_URI;?>" method="POST">
<div class="form-group">
<label for="recipient-name" class="col-form-label">Did you find this information useful?</label>
<!-- <input type="text" class="form-control" id="recipient-name"> -->
<div class="custom-control custom-radio">
<label class="custom-control-label" for="infouseful1">Yes</label>
<input type="radio" value="Yes" required class="custom-control-input" id="infouseful1" name="infouseful" checked>
</div>
<!-- Group of default radios - option 2 -->
<div class="custom-control custom-radio">
<label class="custom-control-label" for="infouseful">No</label>
<input type="radio" value="No" required class="custom-control-input" id="infouseful" name="infouseful" />
</div>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">How did you find out about us?</label>
<div class="in-checkbox">
<label>
Friend: <input type="checkbox" value="Friend" name="findHow[friend]"> </label>
<label>
Church Referral: <input type="checkbox" value="Church Referral" name="findHow[church]"> </label>
<label>
Caseworker: <input type="checkbox" value="Caseworker" name="findHow[caseworker]"> </label>
<label>
Billboard: <input type="checkbox" value="Billboard" name="findHow[billboard]"> </label>
<label>
Internet: <input type="checkbox" value="Internet" name="findHow[internet]"> </label>
<label>
Other: <input type="checkbox" value="Other" name="findHow[other]"> (specify:) <input type="text" class="form-control" name="findHow[other_value]" id="recipient-name">
</label>
</div>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">join our Monthl Newsletter</label>
<input type="text" name="name" required class="form-control" placeholder="Your Name">
<input type="email" name="email" required class="form-control" placeholder="Your email">
</div>
<div class="form-group submit-but">
<button type="submit" name="popupsubmit" id="popupsubmit" value="Submit">Submit</button>
</div>
</form>
<?php
}else{
?>
<p>Thank you for your submission. We appreciate your feedback.</p>
<?php
}
?>
</div>
</div>
</div>
<!-- popupend -->
<script>
function WriteCookie( name, value ) {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(value) + ";"
document.cookie = name + "=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
}
function ReadCookie(name) {
var allcookies = document.cookie;
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
cookieName = cookiearray[i].split('=')[0];
cookieValue = cookiearray[i].split('=')[1];
if(name == jQuery.trim(cookieName))
return cookieValue;
}
return null;
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
// btn.onclick = function() {
// modal.style.display = "block";
// }
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
function GetSelectedHowFinds() {
//Create an Array.
var selected = new Array();
//Reference the Table.
var form = document.getElementById("popupSubs");
//Reference all the CheckBoxes in Table.
var inputs = form.getElementsByTagName("INPUT");
// Loop and push the checked CheckBox value in Array.
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === 'checkbox') {
if ( inputs[i].checked) {
selected.push(inputs[i].value);
}
}
}
return selected;
};
setTimeout(() => {
var isPopUpOpened = ReadCookie('ccpopup');
if(!isPopUpOpened){
modal.style.display = "block";
WriteCookie('ccpopup', 'OK');
}
}, <?php echo 1000 * CC_POPUP_TIMEOUT ?>);
<?php
if(isset($_GET['ccsubmitted'])){
?>
setTimeout(() => {
modal.style.display = "block";
}, 1000);
<?php
}
?>
jQuery("body").on( 'click', "#popupsubmit", function(ev){
ev.preventDefault();
if (!jQuery("input[name='infouseful']:checked").val()) {
alert("Please select if information is useful??");
return;
}
var findHowArr = GetSelectedHowFinds();
if (findHowArr.includes("Other") && jQuery("#recipient-name").val() == "") {
alert("Please input Other value of how did you find us?");
return;
}
if (jQuery("input[name='name']").val() == "") {
alert("Please enter your name?");
return;
}
if (jQuery("input[name='email']").val() == "") {
alert("Please enter your email?");
return;
}
jQuery("#popupSubs").submit();
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment