Using Stripe for SAAS payments

stripe for saas payment

Letting users pay for your software service is important part of building a “Software as a Service” business. Accepting payment requires a third-party service, such as Stripe. Their PHP library makes it easy to accept credit cards and subscribe users to monthly payment plans. My examples use version 6.43. The Stripe JavaScript library is used to create secure UI elements that collect sensitive card data.

Before any coding, log into your Stripe account. Create a product with a monthly price. That product’s API ID is used to programmatically charge users and subscribe them recurring billing.

stripe product dashboard

User Interface (front end)

In this part Stripe collects the payment information, and returns a secure token that can be used server-side to create a charge. Payment does not actually happen until the token is processed on the back-end.

My software product gives users a 7-day free trial before core functionality is disabled. When they decide to activate their account they are presented with a credit card input user interface.

activate account subscription

It is built with basic HTML and CSS.

<style type="text/css">
	#card-element{
		width: 100%;
		margin-bottom: 10px; 
	}
	.StripeElement {
	  box-sizing: border-box;

	  height: 40px;

	  padding: 10px 12px;

	  border: 1px solid transparent;
	  border-radius: 4px;
	  background-color: white;

	  box-shadow: 0 1px 3px 0 #e6ebf1;
	  -webkit-transition: box-shadow 150ms ease;
	  transition: box-shadow 150ms ease;
	}

	.StripeElement--focus {
	  box-shadow: 0 1px 3px 0 #cfd7df;
	}

	.StripeElement--invalid {
	  border-color: #fa755a;
	}

	.StripeElement--webkit-autofill {
	  background-color: #fefde5 !important;
	}
</style>

<div id="stripe-payment-modal" class="modal stripe-payment-modal" style="display: none;">

	<!-- Modal content -->
	<div class="modal-content">
		<p>
		  <button type="button" class="dismiss-modal close" >&times;</button>
		</p>
		<p>Activate your account subscription.</p>
		<p><?php echo $price_point; ?> per month.</p>
		<form id="payment-form">
		  <div class="form-row">
		    <!-- <label for="card-element">
		      Credit or debit card
		    </label> -->
		    <div id="card-element">
		      <!-- A Stripe Element will be inserted here. -->
		    </div>

		    <!-- Used to display Element errors. -->
		    <div id="card-errors" role="alert"></div>
		  </div>

		  <button type="button" class="btn submit-payment">Submit Payment</button>
		</form>

  	</div>

</div>

The actual input elements are generated by Stripe’s JavaScript. The Stripe form handles real-time validation and generates a secure token to be sent to your server.

<script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">

	$(document).ready(function() {
		// var stripe = Stripe('pk_test_xxxx'); //sandbox
		var stripe = Stripe('pk_live_xxxx');

		var elements = stripe.elements();

		// Custom styling can be passed to options when creating an Element.
		var style = {
		  base: {
		    color: '#32325d',
		    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
		    fontSmoothing: 'antialiased',
		    fontSize: '16px',
		    '::placeholder': {
		      color: '#aab7c4'
		    }
		  },
		  invalid: {
		    color: '#fa755a',
		    iconColor: '#fa755a'
		  }
		};

		// Create an instance of the card Element.
		var card = elements.create('card', {style: style});

		// Add an instance of the card Element into the `card-element` <div>.
		card.mount('#card-element');

		// Handle real-time validation errors from the card Element.
		card.addEventListener('change', function(event) {
		  var displayError = document.getElementById('card-errors');
		  if (event.error) {
		    displayError.textContent = event.error.message;
		  } else {
		    displayError.textContent = '';
		  }
		});

		// Handle form submission.
		var form = document.getElementById('payment-form');
		form.addEventListener('submit', function(event) {
		  event.preventDefault();

		  stripe.createToken(card).then(function(result) {
		    if (result.error) {
		      // Inform the user if there was an error.
		      var errorElement = document.getElementById('card-errors');
		      errorElement.textContent = result.error.message;
		    } else {
		      // Send the token to your server.
		      stripeTokenHandler(result.token);
		    }
		  });
		});

		// Submit the form with the token ID.
		function stripeTokenHandler(token) {
		  // Insert the token ID into the form so it gets submitted to the server
		  var form = document.getElementById('payment-form');
		  var hiddenInput = document.createElement('input');
		  hiddenInput.setAttribute('type', 'hidden');
		  hiddenInput.setAttribute('name', 'stripeToken');
		  hiddenInput.setAttribute('value', token.id);
		  form.appendChild(hiddenInput);
		 
		  var data = $("#payment-form").serialize();
		  $.ajax({
		  	url:"/service-layer/stripe-service?method=subscribe",
		  	method: "POST",
		  	data: data,
		  	complete: function(response){
		  		console.log(response);
		  		window.location.reload();
		  	}
		  })
		}

		$(".submit-payment").click(function(){
			stripe.createToken(card).then(function(result) {
		    if (result.error) {
		    	// Inform the customer that there was an error.
		    	var errorElement = document.getElementById('card-errors');
		    	errorElement.textContent = result.error.message;
		    } else {
				$(".submit-payment").attr("disabled", "disabled").html('Working <i class="fas fa-spinner fa-spin"></i>');
		      	// Send the token to your server.
		      	stripeTokenHandler(result.token);
		    }
		  });
		});

	});

</script>

After referencing the CDN JS library, the Stripe object accepts a public API key. That object then creates a customizable element that can be mounted into an existing <div> on your webpage. In your JavaScript, you can either listen for the form to be submitted or for an arbitrary button to be clicked. Then, we rely on the Stripe object to create a card token, which we can pass along to our back-end service.

You can find test payment methods in Stripe’s documentation.

Payment

Creating a subscription

Once the token is passed along to the server, it can be used to subscribe to the monthly product. We will need to load the PHP library and provide our secret API key. The key can be found in Stripe’s web dashboard.

require_once('/stripe-php-6.43.0/init.php');
\Stripe\Stripe::setApiKey('sk_live_XXXXXXX');

A Stripe customer ID is needed to create the subscription. Our code checks if the user record already has a Stripe customer ID saved to our database (in case they signed up previously, and cancelled).  If not, we call the “customer create” method first.

function subscribe(){
	$stripe_token = $_POST['stripeToken'];
	$conn = $this->connection;
	
	if(isset($_SESSION['email'])){
		$email = $_SESSION['email'];
	}else{
		die("No email found.");
	}
	
	if(strlen($email)>0){
		$sql = "SELECT * FROM `account` WHERE email = ?"; 
		$result = $conn->prepare($sql); 
		$result->execute(array($email));
		$row = $result->fetch(PDO::FETCH_ASSOC);
	}
	$customer_id = $row['billing_customer_id'];
	//check if this account already has a billing_customer_id
	if(strlen($customer_id) < 1){
		//if not, create the customer
		$customer = \Stripe\Customer::create([
		  'email' => $email,
		  'source' => $stripe_token,
		]);
		$customer_id = $customer['id'];
		//write stripe ID to db
		$sql = "UPDATE `account` SET billing_customer_id = ? WHERE email = ?"; 
		$result = $conn->prepare($sql); 
		$result->execute(array($customer_id, $email));
	}

	// Create the subscription
	$subscription = \Stripe\Subscription::create([
	  'customer' => $customer_id,
	  'items' => [
	    [
	      // 'plan' => 'plan_FjOzMSMahyM7Ap', //sandbox.
	      'plan' => 'price_1He7vwLjg3FTECK8lb3GDQhV', //"basic" plan. setup in Stripe dashboard.
	    ],
	  ],
	  'expand' => ['latest_invoice.payment_intent'],
	  'billing_cycle_anchor' => time()
	]);
	$subscription_status = $subscription['status'];
	$subscription_id = $subscription['id'];
	if($subscription_status == "active"){
		//set current_period_end to 32 days (1 month plus some leeway) in the future. set past_due as false 
		$sql = "UPDATE `account` SET stripe_subscription_id = ?, current_period_end = ?, past_due = 0 WHERE email = ?"; 
		$result = $conn->prepare($sql);
		$past_due = false;
		$current_period_end = new DateTime;  
		$current_period_end->modify( '+32 day' );
		$current_period_end = $current_period_end->format('Y-m-d H:i:s'); 
		$result->execute(array($subscription_id, $current_period_end, $email));
	}
}

With the subscription complete, their account’s “past due” property is marked as false and “current period end” is recorded to about 1 month in the future. The Stripe subscription ID is recorded for later use and reference.

Subscription life-cycle workflow

The application knows if an account is paying for premium service based on that “past due” property. After a user first signs up, that value is managed by a nightly scheduled cron job. If the “current period end” date is in the past, “past due” is marked as true, all projects are turned off, and a notification email is sent.

function checkPastDue(){	
	$sql = "SELECT * FROM `account` WHERE past_due = '0'";
	$result = $conn->prepare($sql); 
	$result->execute(); 
	$rows = $result->fetchAll(PDO::FETCH_ASSOC);
	$number_of_rows = $result->rowCount();
	
	include 'send-email-service.php';	

	foreach ($rows as $key => $value) {
		$current_period_end = $value['current_period_end'];
		$date = new DateTime($current_period_end);
		$now = new DateTime();
		if($date < $now) {
		   
		    //extend their trial 1 time, for an additional week
		    $extended_trial = $value['extended_trial'];
		    $accountid = $value['accountid'];
		    $email = $value['email'];
		    $billing_customer_id = $value['billing_customer_id'];
		    if($extended_trial == 0 && strlen($billing_customer_id) == 0){

		    	$sql = "UPDATE `account` SET extended_trial = '1' WHERE accountid = ?";
				$result1 = $conn->prepare($sql); 
				$result1->execute(array($accountid)); 

				$current_period_end = new DateTime;  
				$current_period_end->modify( '+8 day' );
				$current_period_end = $current_period_end->format('Y-m-d H:i:s'); 

		    	$sql = "UPDATE `account` SET current_period_end = ? WHERE accountid = ?";
				$result1 = $conn->prepare($sql); 
				$result1->execute(array($current_period_end, $accountid)); 
				 
				$SendEmailService = new SendEmailService();
				
				$subject = "SplitWit trial extended!";

				$body = "Your SplitWit trial was supposed to expire today. As a courtesy, we're extending it another 7 days!<br><br>";
				
				$altBody = "Your SplitWit trial was supposed to expire today. We're extending it another 7 days!";

				$SendEmailService -> sendEmail($subject, $body, $altBody, $email);


		    }else{
				
				$sql = "UPDATE `account` SET past_due = '1' WHERE accountid = ?";
				$result1 = $conn->prepare($sql); 
				$result1->execute(array($accountid)); 
				
				//turn off all experiments
				$status = "Not running";
				$sql = "UPDATE `experiment` set status = ? where accountid = ?";
				$result2 = $conn->prepare($sql); 
				$result2->execute(array($status, $accountid));


				//update all snippets for this account (1 snippet per project)
				$sql = "SELECT * FROM `project` WHERE accountid = ?";
				$result3 = $conn->prepare($sql); 
				$result3->execute(array($accountid));
				$rows3 = $result3->fetchAll(PDO::FETCH_ASSOC);
				foreach ($rows3 as $key3 => $value3) {
					$projectid = $value3['projectid'];
			    	$write_snippet_service = new ProjectService();
					$write_snippet_service -> writeSnippetFile(false, false, $projectid);
				}
				
				$SendEmailService = new SendEmailService();
				$subject = "SplitWit account past due";

				$body = "Your SplitWit account is past due. Please login to your account and update your payment information to continue running A/B experiments.<br><br>";
				
				$body .= "A/B testing helps you increase conversion rates and avoid unnecessary risk. <a href='https://www.splitwit.com/blog/'>Check out the SplitWit blog for experiment ideas</a>. Remember, everything is testable!";
				 
				$body .= "<br><br><a href='https://www.splitwit.com/'><img src='https://www.splitwit.com/img/splitwit-logo.png'></a>";

				$altBody = "Your SplitWit account is past due. Please login to your account and update your payment information to continue running A/B experiments. A/B testing helps you increase conversion rates and avoid unnecessary risk. Check out the SplitWit blog for experiment ideas: https://www.splitwit.com/blog/ ";

				$SendEmailService -> sendEmail($subject, $body, $altBody, $email);

		    }
			
		}
	}

}

The “current period end” date is updated each month after the customer is invoiced.

webhook payment success

When the Stripe “payment succeeded” event happens, a webhook triggers our custom end-point code.

function webhookPaymentSuccess(){
	$payload = @file_get_contents("php://input"); 
	$endpoint_secret = "whsec_XXXX";

	$sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"];
	$event = null;

	try {
	  $event = \Stripe\Webhook::constructEvent(
	    $payload, $sig_header, $endpoint_secret
	  );
	} catch(\UnexpectedValueException $e) {
	  // Invalid payload
	  http_response_code(400); // PHP 5.4 or greater
	  exit();
	} catch(\Stripe\Error\SignatureVerification $e) {
	  // Invalid signature
	  http_response_code(400); // PHP 5.4 or greater
	  exit();
	}
	
	if($event->type == 'invoice.payment_succeeded'){

		$invoice = $event->data->object;
		$customer_id = $invoice['customer'];
		//update their accocunt current_period_end
		$conn = $this->connection;
		$sql = "UPDATE `account` SET  current_period_end = ?, past_due = 0 WHERE billing_customer_id = ?"; 
		$result = $conn->prepare($sql);
		$past_due = false;
		$current_period_end = new DateTime;  
		$current_period_end->modify( '+32 day' );
		$current_period_end = $current_period_end->format('Y-m-d H:i:s'); 
		$result->execute(array($current_period_end, $customer_id));
	}else{
		http_response_code(400);
	    exit();
	}
	
	http_response_code(200);
	// var_dump($payload);
}

Although there is a webhook available for payment failure, the scheduled cron job handles that scenario.

If a user decides to cancel their subscription, we use their Stripe subscription ID and update their account records.

function cancelSubscription(){
	include '/var/www/html/service-layer/project-service.php';
	$conn = $this->connection;
	if(isset($_SESSION['userid'])){
		$accountid = $_SESSION['userid'];
	}else{
		die("No userid found.");
	}
	
	if(strlen($accountid)>0){
		
		$sql = "SELECT * FROM `account` WHERE accountid = ?"; 
		$result = $conn->prepare($sql); 
		$result->execute(array($accountid));
		$row = $result->fetch(PDO::FETCH_ASSOC);
	}
	$stripe_subscription_id = $row['stripe_subscription_id'];
	$subscription = \Stripe\Subscription::retrieve($stripe_subscription_id);
	$subscription->cancel();
	
	//#TODO: We should let the cron job handle this, so the user gets the rest of their month's service.
	//turn off experiments and update snippets. clear stripe IDs. set current_period_end to yesterday. set past_due = 1
	$current_period_end   = new DateTime;  
	$current_period_end->modify( '-1 day' );
	$current_period_end = $current_period_end->format('Y-m-d H:i:s'); 
	$sql = "UPDATE `account` SET billing_customer_id = '', stripe_subscription_id = '', past_due = 1, current_period_end = ? WHERE accountid = ?"; 
	$result = $conn->prepare($sql); 
	$result->execute(array($current_period_end, $accountid));

	//turn off all experiments
	$status = "Not running";
	$sql = "UPDATE `experiment` set status = ? where accountid = ?";
	$result2 = $conn->prepare($sql); 
	$result2->execute(array($status, $accountid));

	//update all snippets for this account (1 snippet per project)
	$sql = "SELECT * FROM `project` WHERE accountid = ?";
	$result3 = $conn->prepare($sql); 
	$result3->execute(array($accountid));
	$rows3 = $result3->fetchAll(PDO::FETCH_ASSOC);
	foreach ($rows3 as $key3 => $value3) {
		$projectid = $value3['projectid'];
    	$write_snippet_service = new ProjectService();
		$write_snippet_service -> writeSnippetFile(false, false, $projectid);
	}

	$this->status = "complete";
}

Being able to charge money for your web based software is an important step in building a SAAS business. Using a Stripe as your payment infrastructure makes it easy. Build stuff that people love and you can get paid to do it!

Update

I recently integrated Stripe payments for one of my apps, BJJ Tracker. I used version 13.0.0 of Stripe’s PHP library, which requires a slightly different code syntax. For this use-case I only needed to create a one-time payment instead of a subscription. I was able to create a charge on the fly, and did not need to create a “product” in the Stripe dashboard:

$stripe = new \Stripe\StripeClient('sk_test_XXX');
$customer = $stripe->customers->create([
	'email' => $_SESSION['email'],
	'source' => $stripe_token
]);
$charge = $stripe->charges->create([
	'amount' => 1000,
	'currency' => 'usd',
	'description' => 'BJJ Tracker',
	'customer' => $customer->id,
]);

$sql = "UPDATE `users` SET paid = ?, customer_id = ? WHERE ID = ?"; 
$result = $conn->prepare($sql);
 
$result->execute(array($charge->id, $customer->id, $_SESSION['userid']));

 

Visual Website Editor in PHP

visual editor in php

Tools for non-programmers to manage websites are growing in demand. No-code solutions increase bandwidth. Many SaaS products promise marketers and project managers a way to get things done without a developer. A visual website editor baked into an app is an important technology for digital product builders. The ability for a software service to interact with a client’s website can be a critical selling point.

SplitWit A/B Testing is an example of a web app that had that requirement. It lets user specify an existing website and displays it in an editor window. The user can then click on elements, make changes, and add new content. Those changes are actually applied to the live website by a JavaScript snippet. This post explains how it was built using PHP and jQuery.

Showing the website via iFrame

Displaying an already existing website on your app is easy with an iFrame. But, since users should be able to view and edit any page they choose, challenges arise. If a non-SSL URL is used (http:// instead of https://), the editor app will throw a “mixed-content warning”. If the page has X-FRAME-OPTIONS set to DENY, then the request will fail. To get around these issues I load an internal page into the iFrame that contains all of the DOM code from the one specified.

var pageIframe = $('<iframe id="page-iframe" style="" src="/page-to-edit.php?baseUrl='+baseUrl+'&url=<?php echo $url; ?>"></iframe>').appendTo(".page-iframe-wrapper");

The page to be edited is entered into an input field.  That 3rd party webpage’s URL is passed along to my internal “page-to-edit.php” as a query parameter. From there, I get its full code using PHP Simple HTML DOM Parser. You’ll notice that I also pass along a “base url” – which is the root domain of the page. I’m able to grab it using JavaScript.

<?php
$url = "";
if(isset($_GET['url']) && strlen($_GET['url']) > 0){
  $url = $_GET['url'];
}
?>
function removeSubdirectoryFromUrlString(url, ssl){
  
  var ssl = ssl || false;
  if(url.indexOf("https://")){
    ssl = true;
  }

  url = url.replace("http://", "");
  url = url.replace("https://", "");
  var pathArray = url.split("/")
  url = pathArray[0];
  if(ssl){
    url = "https://" + url;
  }else{
    url = "http://" + url;
  }

  return url;
}

var url = "<?php echo $url; ?>";
var ssl = false;
var pageIframe;
 
if(url.length > 0){

  if(url.indexOf("https:") !== -1){
    ssl = true
  }
   
  var baseUrl = removeSubdirectoryFromUrlString(url, ssl);
  if(baseUrl.slice(-1) !== "/"){
    baseUrl = baseUrl + "/";
  }
}

I need to append that to any assets (images, scripts, etc.) that use relative references – or else they won’t load.

<?php 
// Report all errors
error_reporting(E_ALL);
ini_set("display_errors", 1);
require 'simple_html_dom.php';


class HtmlDomParser {
	
	/**
	 * @return \simplehtmldom_1_5\simple_html_dom
	 */
	static public function file_get_html() {
		return call_user_func_array ( '\simplehtmldom_1_5\file_get_html' , func_get_args() );
	}

	/**
	 * get html dom from string
	 * @return \simplehtmldom_1_5\simple_html_dom
	 */
	static public function str_get_html() {
		return call_user_func_array ( '\simplehtmldom_1_5\str_get_html' , func_get_args() );
	}
}

$base_url = $_GET['baseUrl'];
$url = $_GET['url'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$html = curl_exec($ch);
$redirectedUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$url = $redirectedUrl;

$parse = parse_url($url);

$base_url = $parse["scheme"] . "://" . $parse["host"];

$html = @HtmlDomParser::file_get_html($url);

if(substr($base_url, 0, 1) == "/"){
    $base_url = substr_replace($base_url ,"",-1);
}

if($html === FALSE) { 
    echo "Sorry, we do not have permission to analyze that website. ";
    return;
}
foreach($html->find('script') as $element){
    $src = $element->src;
    // echo "<script>console.log('starting src: ".$src."')</script>";
    
    if (strlen($src) > 0 && strpos($src, '//') === false){
        if(substr($src, 0, 1) !== "/"){
            $src = "/" . $src;
        }
        $element->src = $base_url . $src;
    }
    if(strlen($element->integrity) > 0){
        $element->integrity = "";
    }
    // echo "<script>console.log('final src: ".$base_url . $src."')</script>";

    // echo $element->src . "\n";
} 
foreach($html->find('link') as $element){
    $src = $element->href;
    
    if (strlen($src) > 0 && strpos($src, '//') === false){
        if(substr($src, 0, 1) !== "/"){
            $src = "/" . $src;
        }
        $element->href = $base_url . $src;
    }
    if(strlen($element->integrity) > 0){
        $element->integrity = "";
    }
   
}
foreach($html->find('a') as $element){
    $src = $element->href;
    
    if (strlen($src) > 0 && strpos($src, '//') === false){
        if(substr($src, 0, 1) !== "/"){
            $src = "/" . $src;
        }
        $element->href = $base_url . $src;
    } 
  
}
foreach($html->find('img') as $element){
    $src = $element->src;
    if (strlen($src) > 0 && strpos($src, '//') === false){
        if(substr($src, 0, 1) !== "/"){
            $src = "/" . $src;
        }

        $element->src = $base_url . $src;
    } 
   
}
foreach($html->find('source') as $element){
    $src = $element->srcset;
    $sources = explode(",",$src);
    $src = trim($sources[0]);

    if (strlen($src) > 0 && strpos($src, '//') === false){
        if(substr($src, 0, 1) !== "/"){
            $src = "/" . $src;
        }

        $element->srcset = $base_url . $src;
    } 
}

echo $html;

?>

I check against five different element types for assets that could need to be updated: <script>, <link>, <a>, <img>, and <source>. In version 1.0, I had missed the <link> and <source> elements.

Now that I was able to load any website into my editor UI, I had to think about layout. I split the screen in half, having the right side display the website, and the left side showing editor options.

visual website editor

Update: Eventually, I noticed that some pages were not loading properly. I found it to be two issues: a security error & a permission-denied response. The security error was a PHP problem. The permission-denied (401) response was due to server settings. Some sites don’t want to be accessed by bots and try to ensure that an actual user is making the request. I was able to fix it by passing context settings to the ‘file_get_html’ method.

$arrContextOptions=array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
    "http" => array(
        "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
    )
); 
$html = file_get_html($url, false, stream_context_create($arrContextOptions));

Element selection

Page-clicks in the editor window need to be intercepted to stop links from being followed and any other actions from happening. Instead, any thing clicked is selected by the editor and its details shown in the options panel.

highlight element selected

As elements are moused over, a semi-transparent red highlight is applied as a visual cue. It is achieved by injecting CSS into the iFrame and adding mouseenter and mouseout event listeners.

pageIframe.on('load', function(){
    var style = "<style>.highlighted{background-color:rgba(255, 0, 0, 0.5);} </style>";         
    pageIframe.contents().find("body").prepend(style);
     
    pageIframe.contents().find("body *").mouseenter(function(){
	$(this).addClass('highlighted'); 
    }).mouseout(function(){
	$(this).removeClass('highlighted');   
    });

});

When something is clicked, normal functionality is stopped by using the web browser’s preventDefault() method. Once the element is grabbed (using the this keyword), we want to be sure that we’re as deep into the DOM tree as possible. That way, our “Text / HTML” content won’t contain unnecessary code tags.

To do so, we use a while loop to iterate an arbitrary number of times. Eight iterations seems to be the number that gets us to the heart of any selected content, without taking too much time.

First, we check if the element has any child nodes – if it does, we grab the first one. If that node happens to be a <style> or <script> tag, we move onto the second instead. As long as that new node is not a formatting element (<strong>, <em>, etc.), we set it as the new element before continuing our loop.

testSelectorEl = $(this);
var i = 8;
while(i > 0){
	if ( $(testSelectorEl).children().length > 0 ) {
	  nextEl = $(testSelectorEl).find(">:first-child");
	  if(nextEl.is( "style" ) || nextEl.is( "script" ) || nextEl.is( "noscript" )){
	     nextEl = $(testSelectorEl).find(">:nth-child(2)");
	  }
	  if ( !nextEl.is( "u" ) && !nextEl.is( "i" ) && !nextEl.is( "strong" ) && !nextEl.is( "em" )) {
	    testSelectorEl = nextEl;
	  }
	}
	i--;
}

The above code is added to the click event listener on all elements within the iFrame. Next, below that code, we determine a unique CSS selector by which we can later reference the element. This is important for writing any changes to the JavaScript snippet to effect changes on the 3rd-party website.

var node = testSelectorEl;
var path = "";
while (node.length) {
  var realNode = node[0], name = realNode.localName;
  if (!name) break;
  name = name.toLowerCase();

  var parent = node.parent();

  var siblings = parent.children(name);
  if (siblings.length > 1) { 
      name += ':eq(' + siblings.index(realNode) + ')';
  }

  path = name + (path ? '>' + path : '');
  node = parent;
}
var value = path;
$(".selector-input").val(value);

The final iFrame on-load function looks like this:

var url = "<?php echo $url; ?>";
var ssl = false;
var pageIframe;
 
if(url.length > 0){

  if(url.indexOf("https:") !== -1){
    ssl = true
  }
   
  var baseUrl = removeSubdirectoryFromUrlString(url, ssl);
  if(baseUrl.slice(-1) !== "/"){
    baseUrl = baseUrl + "/";
  }

  var style = "<style>.highlighted{background-color:rgba(255, 0, 0, 0.5);} </style>";


  var pageIframe = $('<iframe id="page-iframe" style="" src="/new-page-to-edit.php?baseUrl='+baseUrl+'&url=<?php echo $url; ?>"></iframe>').appendTo(".page-iframe-wrapper");
     
  pageIframe.on('load', function(){

    pageIframe.contents().find("body").prepend(style);
       
    pageIframe.contents().find("body *").mouseenter(function(){

      $(this).addClass('highlighted'); 

      testSelectorEl = $(this);
        
    }).mouseout(function(){

      $(this).removeClass('highlighted');   

    }).click(function(e){

      e.preventDefault();
      e.stopPropagation();
      
      //dig deeper down the dom
      var i = 8;
      while(i > 0){
        if ( $(testSelectorEl).children().length > 0 ) {
          nextEl = $(testSelectorEl).find(">:first-child");
          if(nextEl.is( "style" ) || nextEl.is( "script" ) || nextEl.is( "noscript" )){
             nextEl = $(testSelectorEl).find(">:nth-child(2)");
          }
          if ( !nextEl.is( "u" ) && !nextEl.is( "i" ) && !nextEl.is( "strong" ) && !nextEl.is( "em" )) {
            testSelectorEl = nextEl;
          }
        }
        i--;
      }
      
      var node = testSelectorEl;
      var path = "";
      while (node.length) {
          var realNode = node[0], name = realNode.localName;
          if (!name) break;
          name = name.toLowerCase();

          var parent = node.parent();

          var siblings = parent.children(name);
          if (siblings.length > 1) { 
              name += ':eq(' + siblings.index(realNode) + ')';
          }

          path = name + (path ? '>' + path : '');
          node = parent;
      }
      var value = path;
                
      $(".selector-input").val(value); //for html insert section (redundant for change element section)
      if(! $(".insert-html-wrap").is(':visible')){
        selectNewElement(value); // prepare editor options        
        $(".page-editor-info").offset().top; //scroll user to selector input
      }
      return false;
    });

   
   //make sure images load   
   pageIframe.contents().find("img").each(function(){
      var src = $(this).attr("src");
      if(src && src.length > 0 && src.indexOf("//") == -1){  //if not absolute reference
        if(src.charAt(0) !== "/"){
          src = "/" + src;
        }
        $(this).attr("src", baseUrl + src);
      }
   });
   
   //make sure links aren't followed  
   pageIframe.contents().find("a").each(function(){
      var href = $(this).attr("href");
      $(this).attr("href", "");
      $(this).attr("data-href", href);
   });

   pageIframe.contents().find("body").attr("style", "cursor: pointer !important");
    
   $(".loading-iframe").hide();

  }); //page-iframe load
   
}else{
  //no URL found
   $(".loading-iframe").hide();
}

Lastly, we prepare the editor options panel. This involves setting the original content for the selected element and removing any newly added features (modals, sticky-bars) that were not saved.

Editor Options

After an element is clicked its content and style properties are loaded into the editor panel. The original values are stored in memory. As users edit values a change indicator icon is revealed and the right-panel editor view is updated in real time.

var testSelectorEl;
var testSelectorElPath = "";
var testSelectorElHtml = "";
var testSelectorElImage = "";
var testSelectorElLink = "";
var originalVisibilityState = "";
var originalValues = [];
originalValues['height'] = "";
originalValues['width'] = "";
originalValues['margin'] = "";
originalValues['padding'] = "";
originalValues['border'] = "";
originalValues['font-family'] = "";
originalValues['font-weight'] = "";
originalValues['font-style']= "";
originalValues['text-decoration'] = "";
originalValues['background'] = "";
originalValues['css'] = "";
originalValues['classes'] = "";

$(".html-input").keyup(function(){
    var value = $(this).val();  
    if (value !== testSelectorElHtml){
      $(this).parent().find(".change-indicator").show();
    }else{
      $(this).parent().find(".change-indicator").hide();
    }

    if($(".change-indicator").is(":visible")){
      $(".element-change-save-btn").removeAttr("disabled");
    }else{
      $(".element-change-save-btn").attr("disabled", "disabled");
    }

    var selector = $(".selector-input").val();
    var iFrameDOM = $("iframe#page-iframe").contents()
    iFrameDOM.find(selector).html(value);
    
  });

Besides changing existing elements, new ones can also be added. The “insert content” section, also based on selecting an element, lets users add new text, html, or images before or after whatever has been clicked. In both sections, the CSS selector can also be manually typed (instead of clicking). Adding or editing images is handled by a custom built image upload gallery that leverages AWS S3 and PHP.

insert content

Out-of-the-box elements, such as sticky bars and modals, can also be added with a few clicks and configurations. The HTML and CSS for those are pre-built, with variables for any options that may be set. Any changes made are saved to the database in relation to the user account, project, experiment, and variation.

function addSticky(){
	$conn = $this->connection;
	$accountid = $this->accountid;
	$variationid = $_GET['variationid'];
	$experimentid = $_GET['experimentid'];
	$text = $_POST['text'];
	$color = $_POST['color'];
	$background = $_POST['background'];
	$position = $_POST['position'];
	$linkurl = $_POST['linkurl'];

	$insertStatement = "INSERT INTO `variationchange` (accountid, variationid, experimentid, selector, changetype, changecode, content) VALUES (:accountid, :variationid, :experimentid, :selector, :changetype, :changecode, :content)";
	$changetype = "stickybar";
	$selector = "body";

	$link_opening = "";
	$link_closing = "";

	if(strlen($linkurl) > 0){
		$link_opening = "<a style='color:".$color."' href='".$linkurl."'>";
		$link_closing = "</a>";
	}

	$sticky_html = "<div style='font-weight:bold;".$position.":0;position:fixed;z-index:100000;left:0px;text-align:center;padding:8px 20px;width:100%;background:".$background.";color:".$color."' id='splitwit-sticky'><p style='margin:0px'>".$link_opening.$text.$link_closing."</p></div>";

	$changecode = '$("body").append("'.$sticky_html.'")';

	$stmt = $conn->prepare($insertStatement);	
	$stmt->bindParam(':accountid', $accountid);
	$stmt->bindParam(':variationid', $variationid);
	$stmt->bindParam(':experimentid', $experimentid);
	$stmt->bindParam(':selector', $selector);
	$stmt->bindParam(':changetype', $changetype);
	$stmt->bindParam(':changecode', $changecode);
	$stmt->bindParam(':content', $text);
	$stmt->execute();	

	$this->writeSnippetFile($variationid);
}
		

Writing changes to the snippet

Every project has a unique JavaScript file that users must add to their webpage. The file is hosted by SplitWit, so website owners only need to copy/paste a snippet. The WordPress and Shopify plugins automatically add the snippet, making it even more friendly to non-developers.

Each project may contain multiple experiments with their own changes, metrics, variations, and conditions. After the data is produced by a SQL join statement, it is massaged into a nested object and parsed in JSON. That JavaScript output is concatenated to the necessary libraries and helper functions.

function writeSnippetFile($variationid=false, $experimentid=false, $projectid=false){
	
	$conn = $this->connection;
	$variationid = $variationid || false;
	$experimentid = $experimentid || false;
	
	if(isset($_GET['variationid'])){
		$variationid = $_GET['variationid'];
	}
	if(isset($_GET['experimentid'])){
		$experimentid = $_GET['experimentid'];
	}


	if($variationid){
		$variationid = $_GET['variationid'];
		$sql = "SELECT experiment.projectid FROM `variation` right join `experiment` on variation.experimentid = experiment.experimentid WHERE variationid = ?"; 
		$result = $conn->prepare($sql); 
		$result->execute(array($variationid));
		$experiment_row = $result->fetch(PDO::FETCH_ASSOC);
	}elseif($experimentid){
		$experimentid = $_GET['experimentid'];
		$sql = "SELECT projectid FROM `experiment` WHERE experimentid = ?"; 
		$result = $conn->prepare($sql); 
		$result->execute(array($experimentid));
		$experiment_row = $result->fetch(PDO::FETCH_ASSOC);
	}
	
	if(!$projectid){
		$projectid = $experiment_row['projectid'];
	}

	$sql = "SELECT experiment.experimentid, experiment.status, experimentcondition.experimentconditionid, variation.variationid, variationchange.variationchangeid, variationchange.changecode, variation.css, variation.javascript, experimentcondition.url, experimentcondition.matchtype, experimentcondition.conditiontype, metric.metricid, metric.type, metric.input, metric.urlmatch FROM `experiment` left join `metric` on metric.experimentid = experiment.experimentid join `experimentcondition` on experimentcondition.experimentid = experiment.experimentid join `variation` on variation.experimentid = experiment.experimentid left join `variationchange` on variationchange.variationid = variation.variationid WHERE experiment.projectid = ?"; 
	
	// echo "<br />"."variationid: ".$variationid . "<br />";
	// echo "<br />"."experimentid: ".$experimentid . "<br />";
	// echo "<br />"."projectid: ".$projectid . "<br />";

	// $this->status = "SQL: " . $sql;
	$result = $conn->prepare($sql); 
	$result->execute(array($projectid));
	 
	$experiment_row = $result->fetchAll(PDO::FETCH_ASSOC);
	 
	//turn flat array, into a nested one
	$endResult = array();
	foreach($experiment_row as $row){
	    if (!isset($endResult[$row['experimentid']])){
	        $endResult[$row['experimentid']] = array(
	            'experimentid' => $row['experimentid'],
	            'status' => $row['status'],
	            'conditions' => array(),
	            'variations' => array(),
	            'metrics' => array()
	        );
	    }

	    if (!isset($endResult[$row['experimentid']]['conditions'][$row['experimentconditionid']])){
		    $endResult[$row['experimentid']]['conditions'][$row['experimentconditionid']] = array(
		        'experimentconditionid' => $row['experimentconditionid'],
		        'url' => $row['url'],
		        'matchtype' => $row['matchtype'],
		        'conditiontype' => $row['conditiontype']
		    );
		}

	    if (!isset($endResult[$row['experimentid']]['variations'][$row['variationid']])){
		    $endResult[$row['experimentid']]['variations'][$row['variationid']] = array(
		        'variationid' => $row['variationid'],
		        'javascript' => $row['javascript'],
		        'css' => $row['css'],
		        'changes' => array()
		    );
		}

	    if (!isset($endResult[$row['experimentid']]['variations'][$row['variationid']]['changes'][$row['variationchangeid']])){
		   	$endResult[$row['experimentid']]['variations'][$row['variationid']]['changes'][$row['variationchangeid']] = array(
		        'variationchangeid' => $row['variationchangeid'],
		        'changecode' => $row['changecode']
		    );
		}

	    if (!isset($endResult[$row['experimentid']]['metrics'][$row['metricid']])){
		    $endResult[$row['experimentid']]['metrics'][$row['metricid']] = array(
		        'metricid' => $row['metricid'],
		        'type' => $row['type'],
		        'input' => $row['input'],
		        'urlmatch' => $row['urlmatch']
		    );
		}
		
	}

	$json_output = json_encode($endResult);
	// echo $json_output;
	// get snippet file name.
	$sql = "SELECT snippet from `project` where projectid=?";
	$result = $conn->prepare($sql); 
	$result->execute(array($projectid));
	$projectrow = $result->fetch(PDO::FETCH_ASSOC);
	$filename = $projectrow['snippet'];
	// echo $filename;
	$snippet_template = file_get_contents("/var/www/html/snippet/snippet-template.min.js");
	// concat json to snippet template. write file			
	$myfile = fopen("/var/www/html/snippet/".$filename, "w") or die("Unable to open file!");
	//if there are any animation changes, include the necessary library.
	$txt = "";
	if(strpos($json_output, "addClass('animated") !== false){
		$txt .= 'var head=document.getElementsByTagName("head")[0],link=document.createElement("link");link.rel="stylesheet";link.type="text/css";link.href="https://www.splitwit.com/css/animate.min.css";link.media="all";head.appendChild(link); ';
	}
	$txt .= "window.splitWitExperiments = ".$json_output . "\n" . $snippet_template;
	
	fwrite($myfile, $txt) or die("Unable to save file!");

	fclose($myfile);

	//if this project is for a shopify app, we need to update the snippet cache
	$update_snippet_url = "https://www.splitwit.com/service-layer/shopify-app-service.php?method=updateSnippetScriptTag&projectid=".$projectid;
	$params = [];
	$curl_update_snippet = $this->curlApiUrl($update_snippet_url, $params);

}

One of the helper functions is a method that checks if the current URL matches the experiment’s conditions to run on:

function testUrl(testurl, conditions){
	
	if(testurl.search(/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/) < 0){
		console.log("no domain")
		return window.inputError($(".test-url-input"), "Please test a valid URL.");
	}
	var valid = false;

	for (i = 0; i < conditions.length; i++) { 
		 var url = conditions[i].url;
		 var matchtype = conditions[i].matchtype;
		 var conditiontype = conditions[i].conditiontype;

		 //exact match
		 if(matchtype == "exact" && conditiontype == "target" && url == testurl){
		 	valid = true;
		 }
		 if(matchtype == "exact" && conditiontype == "exclude" && url == testurl){
		 	valid = false;
		 }

		 //basic match
		 if(matchtype == "basic"){
		 	//strip off querystring, hashtags, protocols, and www from url and testurl - then compare
		 	var cleanTestUrl = testurl.toLowerCase();
		 	var cleanUrl = url.toLowerCase();

		 	if (cleanTestUrl.indexOf("?") > 0) {
					cleanTestUrl = cleanTestUrl.substring(0, cleanTestUrl.indexOf("?"));
				}
		 	if (cleanUrl.indexOf("?") > 0) {
					cleanUrl = cleanUrl.substring(0, cleanUrl.indexOf("?"));
				}
		 	if (cleanTestUrl.indexOf("&") > 0) {
					cleanTestUrl = cleanTestUrl.substring(0, cleanTestUrl.indexOf("&"));
				}
		 	if (cleanUrl.indexOf("&") > 0) {
					cleanUrl = cleanUrl.substring(0, cleanUrl.indexOf("&"));
				}
		 	if (cleanTestUrl.indexOf("#") > 0) {
					cleanTestUrl = cleanTestUrl.substring(0, cleanTestUrl.indexOf("#"));
				}
		 	if (cleanUrl.indexOf("#") > 0) {
					cleanUrl = cleanUrl.substring(0, cleanUrl.indexOf("#"));
				}
				cleanTestUrl = cleanTestUrl.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "");
				cleanUrl = cleanUrl.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "");
				cleanTestUrl = cleanTestUrl.replace(/\/$/, "");
				cleanUrl = cleanUrl.replace(/\/$/, ""); //remove trailing slash

				// console.log(cleanTestUrl);
				// console.log(cleanUrl);
				if(conditiontype == "target" && cleanUrl == cleanTestUrl){
					valid = true;
				}
				if(conditiontype == "exclude" && cleanUrl == cleanTestUrl){
					valid = false;
				}

		 }
		 
		 //substring match
		 if(matchtype == "substring"){
		 	if(testurl.includes(url) && conditiontype == "target"){
					valid = true;
		 	}
		 	if(testurl.includes(url) && conditiontype == "exclude"){
					valid = false;
		 	}
		 }
		 
	} //end conditions loop
	
	$(".test-url-msg").hide();		
	if(valid){
		$(".valid-msg").fadeIn();
	}else{
		$(".invalid-msg").fadeIn();
	}

}

While the snippet code is specific to this use-case (experimental A/B UI changes), the visual editor can be used in a variety of other contexts. You can look through more of the code I used in this GitHub repository I created.

Build an image upload gallery

media gallery upload with s3

Allowing users to upload images to your app can be a pivotal feature. Many digital products rely on it. This post will show you how to do it using PHP and AWS S3.

image upload gallery

After launching version 1.0 of SplitWit, I decided to enhance the platform by adding features. An important A/B experiment involves swapping images. This is particularly useful on ecommerce stores that sell physical products.

Originally, users could only swap images by entering a URL. To the average website owner, this would seem lame. For SplitWit to be legit, adding images on the fly had to be a feature.

I wrote three scripts – one to upload files, one to fetch them, and one to delete them. Each leverages a standalone PHP class written by Donovan Schönknecht, making it easy to interact with AWS S3. All you’ll need is your S3 bucket name and IAM user credentials. The library provides methods to do everything you need.

AWS S3

Amazon S3 stands for “simple storage service”. It provides data storage that is scalable, secure, highly available, and performant.

A new bucket can be created directly from the management console.

create new s3 bucket

You’ll want to create a new IAM user to programmatically interact with this bucket. Make sure that new user is added to a group that includes the permission policy “AmazonS3FullAccess”. You can find the access key ID and secret in the “Security credentials” tab.

IAM user in AWS with permissions for S3

Uploading image files

When users select an image in the visual editor, they are shown a button to upload a new file. Clicking on it opens the gallery modal.

<div id="image-gallery-modal" class="modal image-gallery-modal" style="display: none;">
  <div class="modal-content">
    <h3>Your image gallery</h3>
    <p><strong>Upload a new file:</strong></p>
    <input class="uploadimage" id="uploadimage" type="file" name="uploadimage" />
    <p class="display-none file-error"></p>
    <div><hr /></div>
    <div class="image-gallery-content"></div>
    <p class="loading-images"><i class="fas fa-spinner fa-spin"></i> Loading images...</p>
  </div>
</div>

The HTML file-type input element presents a browser dialog to select a file. Once selected, the image data is posted to the S3 upload script. The newly uploaded image then replaces the existing image in the visual editor. 

$(".uploadimage").change(function(){
    
    var file = $(this)[0].files[0];   
    var formData = new FormData();
    formData.append("file", file, file.name);
    formData.append("upload_file", true);         

    $.ajax({
      type: "POST",
      url: "/s3-upload.php",
      xhr: function () {
        var myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload) {
            // myXhr.upload.addEventListener('progress', that.progressHandling, false);
        }
        return myXhr;
      },
      success: function (response) {
        console.log(response);
        
        document.getElementById("uploadimage").value = "";

        if(response !== "success"){
          $(".file-error").text(response).show();
          setTimeout(function(){ $(".file-error").fadeOut();}, 3000)
          return;
        }
        
        $("#image-gallery-modal").hide();
        loadS3images();
        var newImageUrl = "https://splitwit-image-upload.s3.amazonaws.com/<?php echo $_SESSION['userid'];?>/" + file.name;
        $("input.img-url").val(newImageUrl);
        $(".image-preview").attr("src", newImageUrl).show();
        $(".image-label .change-indicator").show();

        //update editor (right side)
        var selector = $(".selector-input").val();
        var iFrameDOM = $("iframe#page-iframe").contents()
        if($(".element-change-wrap").is(":visible")){
          iFrameDOM.find(selector).attr("src", newImageUrl).attr("srcset", "");
          $(".element-change-save-btn").removeAttr("disabled");
        }
        if($(".insert-html-wrap").is(":visible")){
          var position = $(".position-select").val();
          var htmlInsertText = "<img style='display: block; margin: 10px auto;' class='htmlInsertText' src='"+newImageUrl+"'>";
          iFrameDOM.find(".htmlInsertText").remove();
          if(position == "before"){
            iFrameDOM.find(selector).before(htmlInsertText);
          }
          if(position == "after"){
            iFrameDOM.find(selector).after(htmlInsertText);
          }
        }
      },
      error: function (error) {
        console.log("error: ");
        console.log(error);
      },
      async: true,
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      timeout: 60000
  });

});

The upload script puts files in the same S3 bucket, under a separate sub-directory for each user account ID. It checks the MIME type on the file to make sure an image is being uploaded.

<?php
require 's3.php';
 
$s3 = new S3("XXXX", "XXXX"); //access key ID and secret

// echo "S3::listBuckets(): ".print_r($s3->listBuckets(), 1)."\n";

$bucketName = 'image-upload';

if(isset($_FILES['file'])){
	$file_name = $_FILES['file']['name'];   
	$uploadFile = $_FILES['file']['tmp_name']; 

	if ($_FILES['file']['size'] > 5000000) { //5 megabyte
     	   echo 'Exceeded filesize limit.';
     	   die();
    	}
    	$finfo = new finfo(FILEINFO_MIME_TYPE);
	if (false === $ext = array_search(
	        $finfo->file($uploadFile),
	        array(
	            'jpg' => 'image/jpeg',
	            'png' => 'image/png',
	            'gif' => 'image/gif',
	        ),
	        true
	    )) {
	    	if($_FILES['file']['type'] == ""){
	    		echo 'File format not found. Please re-save the file.';
	    	}else{
		    	echo 'Invalid file format.';
		    }
     	    die();
	 }

	//create new directory with account ID, if it doesn't already exist
	session_start();
	$account_id = $_SESSION['userid'];

	if ($s3->putObjectFile($uploadFile, $bucketName, $account_id."/".$file_name, S3::ACL_PUBLIC_READ)) {
		echo "success";
	}

}
?>

After upload, the gallery list is reloaded by the loadS3images() function.

Fetching image files from S3

When the image gallery modal first shows, that same loadS3images() runs to populate any images that have been previously uploaded.

function loadS3images(){

  $.ajax({
      url:"/s3-get-objects.php",
      complete: function(response){
        gotImages = true;
        $(".loading-images").hide();
        var data = JSON.parse(response.responseText);
        var x;
        var html = "<p><strong>Select existing file:</strong></p>";
        var l = 0;
        for (x in data) {
          l++;
          var name = data[x]["name"];
          nameArr = name.split("/");
          name = nameArr[1];
          var imgUrl = "https://splitwit-image-upload.s3.amazonaws.com/<?php echo $_SESSION['userid'];?>/" + name;
          html += "<div class='image-data-wrap'><p class='filename'>"+name+"</p><img style='width:50px;display:block;margin:10px;' src='' class='display-none'><button type='button' class='btn select-image'>Select</button> <button type='button' class='btn preview-image'>Preview</button> <button type='button' class='btn delete-image'>Delete</button><hr /></div>"
        }
        if(l){
          $(".image-gallery-content").html(html);
        }

      }
    });
}

It hits the “get objects” PHP script to pull the files in the account’s directory.

<?php
require 's3.php';
 
$s3 = new S3("XXX", "XXX"); //access key ID and secret

$bucketName = 'image-upload';
session_start();
$account_id = $_SESSION['userid'];
$info = $s3->getBucket($bucketName, $account_id);
echo json_encode($info);

?>

Existing images can be chosen to replace the one currently selected in the editor. There are also options to preview and delete.

Delete an S3 object

When the delete button is pressed for a file in the image gallery, all we need to do is pass the filename along. If the image is currently being used, we also remove it from the editor.

$(".image-gallery-content").on("click", ".delete-image", function() {
    var parent = $(this).parent();
    var filename = parent.find(".filename").text();
    var currentImageUrl = $(".img-url").val();
    if(currentImageUrl =="https://splitwit-image-upload.s3.amazonaws.com/<?php echo $_SESSION['userid'];?>/" + filename){
      $(".img-url").val(testSelectorElImage);
      $(".image-preview").attr("src", testSelectorElImage);
      var selector = $(".selector-input").val();
      var iFrameDOM = $("iframe#page-iframe").contents()
      iFrameDOM.find(selector).attr("src", testSelectorElImage);
    }
    $.ajax({
      method:"POST",
      data: { 
        'filename': filename, 
      },
      url: "/s3-delete.php?filename="+filename,
      complete: function(response){
        parent.remove();
        if(!$(".image-data-wrap").length){
          $(".image-gallery-content").html("");
        }
      }
    })

}); 

 

<?php
require 's3.php';
 
$s3 = new S3("XXX", "XXX"); //access key ID and secret

$bucketName = 'image-upload';
session_start();
$account_id = $_SESSION['userid'];
$filename = $_POST['filename'];
if ($s3->deleteObject($bucketName, $account_id."/".$filename) ){
	echo "S3::deleteObject(): Deleted file\n";
}

?>

 

Reset password flow in PHP

reset password

My email account is a skeleton key to anything online I’ve signed up for. If I forget a password, I can reset it. Implementing this feature for a web app takes just a few steps.

When users enter an incorrect password, I prompt them to reset it.

incorrect password warning

Clicking the reset link calls a “forgot password” back-end service.

$(document).on("click",".reset-pw-cta", function(){
	var email = $(this).attr("data");
	$.ajax({
		url:"/service-layer/user-service.php?method=forgotPw&email="+email,
		complete:function(response){
			console.log(response.responseText)
			window.showStatusMessage("A password reset email as been sent to " + email);
		}
	})
});

A token is created in our ‘password recovery’ database table. That token is related back to an account record.

password recovery database table

As a security practice, recovery tokens are deleted nightly by a cron job.

An email is then sent containing a “reset password” link embedded with the token. AWS SES and PHPMailer is used to send that message.

function forgotPw(){
	$email = $this->email;
	$row = $this->row;
	$number_of_rows = $this->number_of_rows;
	$conn = $this->connection;
	if($number_of_rows > 0){
		$this->emailFound = 1;
		$userid = $row['ID'];
		$this->userid = $userid;

		//create reset token
		$timestamp = time();
		$expire_date = time() + 24*60*60;
		$token_key = md5($timestamp.md5($email));
		$statement = $conn->prepare("INSERT INTO `passwordrecovery` (userid, token, expire_date) VALUES (:userid, :token, :expire_date)");
		$statement->bindParam(':userid', $userid);
		$statement->bindParam(':token', $token_key);
		$statement->bindParam(':expire_date', $expire_date);
		$statement->execute();

		//send email via amazon ses
		include 'send-email-service.php';	
		$SendEmailService = new SendEmailService();

		$reset_url = 'https://www.bjjtracker.com/reset-pw.php?token='.$token_key;
	        $subject = 'Reset your password.';
	        $body    = 'Click here to reset your password: <a href="'.$reset_url.'">'. $reset_url .'</a>';
	        $altBody = 'Click here to reset your password: ' . $reset_url;
	        $this->status = $SendEmailService -> sendEmail($subject, $body, $altBody, $email);


	}else{
		$this->emailFound = 0;
	}
}

That link navigates to a page with a “reset password” form.

reset password form

Upon submission the new password and embedded token are passed along to the server.

$(document).ready(function() {
    $(".reset-button").click(function(){
      var newPassword = $(".password-reset-input").val();
      if(newPassword.length < 1){
        var notifications = new UINotifications();
        notifications.showStatusMessage("Please don't leave that blank :( ");
        return;
      }
      var data = $(".resetpw-form").serialize();
      $.ajax({
        url: "/service-layer/user-service.php?method=resetPw&token=<?php echo $_GET['token']; ?>",
        method: "POST",
        data: data,
        complete: function(response){
          // console.log(response);
          window.location = "/";
        }
      });
    });
    $("input").keypress(function(e) {
      if(e.which == 13) {
        e.preventDefault();
          $(".reset-button").click();
      }
  });
  

});

The correct recovery record is selected by using the token value. That provides the user ID of the account that we want to update. The token should be deleted once the database is updated.

function resetPw(){
	$conn = $this->connection;
	$token = $_GET['token'];
	$password = $_POST['password'];
	$passwordHash = password_hash($password, PASSWORD_DEFAULT);
	$statement = $conn->prepare("SELECT * FROM `passwordrecovery` where token = ?");
	$statement->execute(array($token));
	$row = $statement->fetch(PDO::FETCH_ASSOC);
	$userid = $row['userid'];

	$update_statement = $conn->prepare("UPDATE `users` SET password = ? where ID = ?");
	$update_statement->execute(array($passwordHash, $userid));

	$delete_statement = $conn->prepare("DELETE FROM `passwordrecovery` where token = ?");
	$delete_statement->execute(array($token));
}

This is a secure and user-friendly workflow to allow users to reset their passwords.

Building my career in tech as a programmer

Anthony Pace's resume and portfolio

Building a fulfilling career can seem daunting. Technology and programming is a great option in today’s world. Resources and opportunities are abundant. You can work from anywhere and help build the future. When I started out, I faced challenges, doubt, and struggle. The ride has been worth it, and I’m excited to keep moving forward.

Starting out

About half way through college, I decided to dropout. I was majoring in Philosophy at a small school in New York.  My main source of income was delivering pizza in the Bronx.

A decade earlier, I found computer programming. I spent my nights coding desktop applications, learning HTML, and exploring the web. Those early days of technology laid the foundation for what would be my career.

When I left school in 2007, I wasn’t sure what to do next. I started earning money in tech that same year by starting a business. It focused on creating blogs and producing content. Ads and affiliate programs served to generate revenue.

It wasn’t as lucrative as I hoped. The real value came from the web development skills I honed. The software and technologies I used then, I still rely on today.

WordPress, Linux, and PHP. Writing, SEO, and digital marketing. These were the bricks I used to form the ground floor of my career in tech.

Service worker

While my early stint at entrepreneurship didn’t make me wealthy, it proved valuable. I managed to grow a freelance business leveraging this experience.

Networking and word-of-mouth were my primary means of growth. After printing business cards, I would give them to everyone I met. While delivering pizzas, I would hand them out to any small businesses or shops I passed.

I found my first paying customer in 2008. Since then, my client list has grown to triple digits.

The services I’ve offered range beyond web development. I’ve designed logos and written copy. I’ve managed infrastructure: web hosting, domain names, email, and more.

I have designed and managed both print and digital marketing campaigns. I’ve given strategy advice to young startups. Truly full stack: business, technology, and design. This has been a theme that has rung true my entire career.

The lessons learned during this period were ones of hard-work and getting the job done. The most valuable skills translate across industries. Finding clients fuels the engine of any business. The art of pitching and selling is a career-long study. Being able to manage business needs has proven to be foundational.

Office life

By 2011 I landed my first in-house gig, working at a marketing company. It felt like a turning point. I was the only developer, and got to deal directly with clients. I worked there for less than a year.

In 2012 I connected with a recruiter for the first time. They set me up on many interviews. I clicked with a small medical education company based in Manhattan. Hired as a web developer, I graduated to senior engineer and marketing specialist.

Team work

There, I was the head of all things digital. That meant building websites, coding native apps, and managing infrastructure. After a promotion to head of marketing my responsibilities expanded. Managing analytics took time. Copywriting promotional materials required patience. My horizons expanded while coordinating live events, and traveling internationally to exhibition shows.

Educational grants funded our projects. They included apps, websites, live events, and digital newsletters. Having a coordinated team was imperative to making things work. The project management and leadership was world-class and invaluable.

A single project was multifarious. I would design responsive layouts, build registration websites, deploy apps, and more. Once a product would launch, I would travel to live events to handle promotion and logistics. While I fulfilled many roles, I was lucky to work with a talented group.

Software Engineer

After four years, I made the difficult decision to leave the job that helped shape my career. A better opportunity presented itself in 2016. I was hired as a software engineer. This is when I came into my own as a programmer. I was able to collaborate with a brilliant team. The technologies I became familiar with continued to grow.

I got to work with early-stage startups and brands backed by venture capital. I learned the intricacies of building digital products and growing direct-to-consumer brands. My colleagues included entrepreneurs, CEOs, and product experts. The office was exciting and full of talent.

At the time of writing this (2020), we are stuck in quarantine due to the COVID-19 pandemic. We’re working remotely, but continuing to grow. Uncertain times prompt us to evaluate our circumstances and take inventory of what we value. What is the future of my career? How does it play into my life overall?

What’s next?

I love what I do for a living. I enjoy programming; I love problem solving; I’m an artist at heart. I plan on continuing to build software products. Chances are, I’ll be doing it somewhere other than New York City – especially since remote work seems to be the future of business.

If you’re thinking about starting a career in technology as a programmer, my advice is to jump right in. Start building, keep learning, and put yourself out there. If anyone reading this wants to chat about careers, technology, programming, or anything else, feel free to email me!

Statistics for hypothesis testing

statistics

Recently, I had to implement a function into SplitWit to determine statistical significance. Shortly after, I wrote a blog post that explains what statistical significance is, and how it is used.

Here, I’ll attempt to expound the code I wrote and what I learned along the way.

Statistical significance implies that the results of an experiment didn’t happen by random chance. SplitWit specifically deals with running A/B experiments (hypothesis testing) to help increase conversion rates. Getting this right is important.

Probability

Statistical significance is determined by calculating a “probability value”. The lower that value is, the more confident we can be that our results are probably not random. Statisticians refer to it as “p-value”. In this field of study, a p-value less than 0.05 is considered good. That translates to a less than 5% chance that the results of an experiment are due to error. Source.

When the probability of a sampling error is that low, we are said to have rejected the “null hypothesis” and affirmed our “alternative hypothesis”. Our alternative hypothesis, in the context of A/B website testing, refers to the experimental UI change we made successfully increasing our conversion rate. The null hypothesis represents the idea that our changes had no true affect on any improvement we may have seen.

SplitWit experiment results
SplitWit lets you set custom metrics to measure conversion rates

How do we calculate our p-value for an A/B split test on a eCommerce website?

Here are the steps to figure out if a hypothesis test is statistically significant:

  1. Determine the conversion rates for the control and variation
  2. Work out the standard error of the difference of those rates
  3. Derive a z-score using the conversion rates and the standard error
  4. Convert that z-score to a p-value
  5. Check if that p-value is below the desired confidence level (<0.05 for 95% confidence)

This recipe is based on a field of study called Bayesian statistics. It attempts to describe a degree of certainty for our experiments.

Conversion rates

The goal of running A/B split tests is to increase your website’s conversion rate. The idea is to make a UI change, show that variation to a portion of users, and then measure conversions against the control version. I calculate conversion rates by dividing the number of conversions by the number of visitors, giving me an average:

$control_conversion_rate = $control_conversions/$control_visitors;
$variation_conversion_rate = $variation_conversions/$variation_visitors;

Which ever version’s conversion rate is higher is the winner of the experiment. I calculate the winner’s uptick in conversion rate using this formula: (WinningConversionRate – LosingConversionRate) / LosingConversionRate

$uptick = 0;
if($control_conversion_rate > $variation_conversion_rate){
	$uptick = (($control_conversion_rate - $variation_conversion_rate) / ($variation_conversion_rate)) * 100;
}

if($control_conversion_rate < $variation_conversion_rate){
	$uptick = (($variation_conversion_rate - $control_conversion_rate) / ($control_conversion_rate)) * 100;
}

 

Calculating p-value

After researching, I determined that I would calculate my p-value from a “z-score”.

$p_value = calculate_p_value($z_score);

A z-score (also known as a standard score) tells us how far a data point is from the mean. Source.

For the purposes of A/B testing, the data points we are interested in is the conversion rates of our control and variation versions. Consider this code snippet for determining our z-score:

$z_score = ($variation_conversion_rate-$control_conversion_rate)/$standard_error;

This formula takes the difference between the two conversion rates, and divides it by their “standard error”. The standard error is meant to tell us how spread out our data is (sampling distribution). Source.

Standard error of two means’ difference

A conversion rate is essentially an average (mean). To properly determine our z-score, we’ll want to use the standard error of their difference.

First, we’d want to get the standard error of each of those rates. Source.

This is the formula to use: ( conversion_rate * ( 1 – conversion_rate ) / visitors )1/2

Translated as PHP code:

$standard_error_control = sqrt($control_conversion_rate * (1-$control_conversion_rate) / $control_visitors;)
$standard_error_variation = sqrt($variation_conversion_rate * (1-$variation_conversion_rate) / $variation_visitors);

Then, we’d use those values to find the standard error of their difference.

This is the formula: ( standard_error_control2 + standard_error_variation2  )1/2

Translated as PHP code:

$x = pow($standard_error_control, 2) + pow($standard_error_variation, 2);
$standard_error_of_difference = sqrt($x);

If we skip squaring our values in the 2nd step, we can also skip getting their square root in the first. Then, the code can be cleaned up, and put into a function:

public function standardErrorOfDifference($control_conversion_rate, $variation_conversion_rate, $control_visitors, $variation_visitors){
		
	$standard_error_1 = $control_conversion_rate * (1-$control_conversion_rate) / $control_visitors;
	$standard_error_2 = $variation_conversion_rate * (1-$variation_conversion_rate) / $variation_visitors;
	$x = $standard_error_1 + $standard_error_2;

	return sqrt($x);

}

This algorithm represents the “difference between proportions” and can be expressed by this formula: sqrt [p1(1-p1)/n1 + p2(1-p2)/n2]

Source.

Simplified even further, as PHP code:

$standard_error = sqrt( ($control_conversion_rate*(1-$control_conversion_rate)/$control_visitors)+($variation_conversion_rate*(1-$variation_conversion_rate)/$variation_visitors) );

Statistics as a service

Having considered all of these steps, we can put together a simple method to determine statistical significance. It takes the number of visitors and conversions for the control and the variation.

public function determineSignificance($controlVisitors, $variationVisitors, $controlHits, $variationHits){
	
	$control_conversion_rate = $control_hits/$control_visitors;
	$variation_conversion_rate = $variation_hits/$variation_visitors;

	$standard_error = sqrt( ($control_conversion_rate*(1-$control_conversion_rate)/$control_visitors)+($variation_conversion_rate*(1-$variation_conversion_rate)/$variation_visitors) );

	$z_score = ($variation_conversion_rate-$control_conversion_rate)/$standard_error;

	$p_value = $this->calculate_p_value($z_score);

	$significant = false;
	
	if($p_value<0.05){
		$significant = true;
	}else{
		$significant = false;
	}
        return $significant;
}

You can find this code on GitHub.

Additional References

https://github.com/markrogoyski/math-php#statistics—experiments

https://www.evanmiller.org/how-not-to-run-an-ab-test.html

https://codereview.stackexchange.com/questions/85508/certainty-of-two-comparative-values-a-b-results-certainty

https://www.mathsisfun.com/data/standard-deviation-formulas.html

https://sites.radford.edu/~biol-web/stats/standarderrorcalc.pdf

https://help.vwo.com/hc/en-us/articles/360033991053-How-Does-VWO-Calculate-the-Chance-to-Beat

https://towardsdatascience.com/the-math-behind-a-b-testing-with-example-code-part-1-of-2-7be752e1d06f

https://abtestguide.com/calc/

Launching a website on AWS EC2

Using AWS for a website

In 2008 I deployed my first website to production. It used a simple LAMP stack , a GoDaddy domain name, and HostGator hosting.

Since 2016, I’ve used AWS as my primary cloud provider. And this year, I’m finally cancelling my HostGator package. Looking through that old server, I found artifacts of past projects – small businesses and start-ups that I helped develop and grow. A virtual memory lane.

Left on that old box was a site that I needed to move to a fresh EC2 instance. This is an opportunity to document how I launch a site to Amazon Web Services.

Amazon Elastic Compute Cloud

To start, I launch a new EC2 instance from the AWS console. Amazon’s Elastic Compute Cloud provides “secure and resizable compute capacity in the cloud.” When prompted to choose an Amazon Machine Image (AMI), I select “Amazon Linux 2 AMI”. I leave all other settings as default. When I finally click “Launch”, it’ll ask me to either generate a new key file, or use an existing one. I’ll need that file later to SSH or sFTP into this instance. A basic Linux server is spun up, with little else installed.

Linux AMI
Amazon Linux 2 AMI is free tier eligible.

Next, I make sure that instance’s Security Group allows inbound traffic on SSH, HTTP, and HTTPS. We allow all traffic via HTTP and HTTPS (IPv4 and IPv6, which is why there are 2 entries for each). That way end-users can reach the website from a browser. Inbound SSH access should not be left wide open. Only specific IP addresses should be allowed to command-line in to the server. AWS has an option labeled “My IP” that will populate it for your machine.

Inbound security rules
Don’t allow all IPs to access SSH in a live production environment.

Recent AWS UI updates let you set these common rules directly from the “Launch an instance” screen, under “Network settings”

AWS Network settings screen

Configure the server

Now that the hosting server is up-and-running, I can command-line in via SSH from my Mac’s terminal using the key file from before. This is what the command looks like:

 ssh -i /Users/apace/my-keys/keypair-secret.pem ec2-user@ec2-XXX-XXX-XX.us-east-2.compute.amazonaws.com

You might get a CLI error that says:

” It is required that your private key files are NOT accessible by others. This private key will be ignored. “

Bad permissions warning against a pem key file in the CLI

That just means you need to update the file permissions on the key file. You should do that from the command line, in the directory where the file resides:

chmod 400 KeyFileNameHere.pem

Make sure everything is up-to-date by running “sudo yum update“.  I begin installing the required software to host a website:

sudo amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2

Note: amazon-linux-extras doesn’t exist on the Amazon Linux 2023 image.

That command gives me Apache, PHP, and MariaDB – a basic LAMP stack. This next one installs the database server:

sudo yum install -y httpd mariadb-server

MariaDB is a fork of the typical MySQL, but with better performance.

By default, MariaDB will not have any password set. If you choose to install phpMyAdmin, it won’t let you login without a password (as per a default setting). You’ll have to set a password from the command line. While connected to your instance via SSH, dispatch this command:

mysql -u root -p

When it prompts you for a password, just hit enter.

login to mariadb for the first time

Once you’re logged in, you need to switch to the mysql database by running the following command:

use mysql;

Now you can set a password for the root user with the following command:

UPDATE user SET password = PASSWORD('new_password') WHERE user = 'root';

After setting the password, you need to flush the privileges to apply the changes:

FLUSH PRIVILEGES;

Start Apache: “sudo systemctl start httpd“. And, make sure it always starts when the server boots up “sudo systemctl enable httpd

The server setup is complete. I can access an Apache test page from a web browser by navigating to the EC2 instance’s public IP address.

Apache test page
A test page shows when no website files are present.

I’ll take my website files (that are stored on my local machine and synched to a Git repo) and copy them to the server via sFTP.

Copy website files to server
I use FileZilla to access my EC2 public directory

I need to make sure the Linux user I sFTP with owns the directory “/var/www/html”, or else I’ll get a permission denied error:

sudo chown -R ec2-user /var/www/html

Later, if I want to be able to upload media to the server from the WordPress CMS, I’ll need to be sure to change the owner of the blog’s directory to the apache user (which is the behind-the-scenes daemon user invoked for such things):

sudo chown -R apache /var/www/html/blog

* AWS Documentation Reference

Domain name and Route 53

Instead of having to use the EC2 server’s public address to see my website from a browser, I’ll point a domain name at it. AWS Route 53 helps with this. It’s a “DNS web service” that routes users to websites by mapping domain names to IP addresses.

In Route 53 I create a new “hosted zone”, and enter the domain name that I’ll be using for this site.  This will automatically generate two record sets: a Name Server (NS) record and a Start-of-Authority (SOA) record. I’ll create one more, an IPv4 address (A) record. The value of that record should be the public IP address that I want my domain to point at. You’ll probably also want to add another, identical to the last one, but specifying “www” in the record name.

setting a record in AWS

Finally, I’ll head over to my domain name registrar, and find my domain name’s settings. I update the nameserver values there to match those in my Route 53 NS record set. It’ll likely take some time for this change to be reflected in the domain’s settings. Once that is complete, the domain name will be pointing at my new EC2 instance.

And that’s it – I’ve deployed my website to AWS. The next step is to secure my site by configuring SSL and HTTPS.

If you’re migrating a dynamic WordPress site, you’ll require a some additional steps to complete the migration.