Using TaxCloud with Simplify Commerce by MasterCard

June 20, 2014

Simplify Commerce by MasterCard

Overview

It’s easy to use TaxCloud with Simplify Commerce to automatically calculate and collect sales tax for any street address in the United States. We are proud to announce the immediate availability of taxcloudSimplify.js, a new version of our TaxCloud javascript library that has been designed specifically for merchants using Simplify Commerce.

Here’s how it works (you will see this is a slightly extended version of Simplify’s base tutorial):

simplify_workflow
View full resolution image

Steps 1, 2, 3, and 4 (indicated in orange) are the normal Simplify process, and are not altered by our efforts here today. Rather, the steps we will be adding (indicated in blue) will allow TaxCloud to manage sales tax – these steps happen immediately before, and immediately after the Simplify steps. In sequence, the revised order is as follows:

A. Tell TaxCloud about all the items being purchased (by category), including where they are being shipped from, and where they are going.

B. TaxCloud will respond with the amount of sales tax to collect.

[then you begin the normal Simplify Process]

1. At the checkout, you will display a form (which taxcloudSimplify.js provides in our example today) that collects required payment information. Simplify’s JavaScript library (Simplify.js) encrypts the data and sends it to Simplify Commerce servers.

2. The Simplify Commerce server will return a single-use token that represents the payment information.

3. Save the token to your server(s) using one of Simplify’s SDKs.

4. Your server application makes a call to Simplify Commerce servers to charge the token.

[after the purchase is complete]

C. Tell TaxCloud the purchase is complete (the sales tax has been collected).

This is the concept, now let’s take a deeper dive into exactly how to do it. For this example we will be using the following:

  • taxcloudSimplify.js – our API in javascript form
  • TaxCloud.php or TaxCloud.aspx – our minimal ‘forwarding’ script/page to handle cross-domain posting
  • simplify.js – a library provided by Simplify to handle purchases with a credit card
  • jquery.min.js – everyone knows about JQuery, right?
  • HelloSimplify.html – a sample page using everything described in this post

As I mentioned earlier we will be using the built-in UI cart that taxcloudSimplify.js supports. The goal of this is to make things as easy as possible for web masters to show a cart of items with their tax as a line item, provide a simple credit card collection page and printable receipt. Our sample using this solution covers everything described in this post is a little over 50 lines in length and works. Download the HelloSimplify.html page and take a look at it. If you put HelloSimplify.html on your web server you can step through all the concepts described here at your convenience. Don’t worry, when you start with TaxCloud your account is in test mode. It doesn’t become live until you say so!

Act 1: The Setup

First thing we need to set up is the proxy page/script that will run on your web server. We have two flavors for you to choose from:

If you are using another server processing extension you can either create the same page functionality on your platform (nothing tricky going on) or let us know so that we can create it.

Open TaxCloud.php/TaxCloud.aspx in your editor and take a look at it. This file has two purposes:

  1. It holds your credentials for TaxCloud
  2. It receives posts from our taxcloudSimplify.js library running in your domain and forwards the data to our TaxCloud web service running in our TaxCloud.net domain.

websites_api_id_and_keyWhile you have TaxCloud.php/TaxCloud.aspx open, lets go ahead and add your unique credentials.

The credentials you need are from your TaxCloud account, specifically your apiLoginID and apiKey. Log into TaxCloud and go to the Websites Section. Select your website, and your ‘API ID’ and ‘API KEY’ will be displayed.

Excerpt of TaxCloud.php

// Put your TaxCloud API Login and API Key values here, along with the USPS User ID.
$apiLoginID = "XXXXXXX"; //Use the API ID from TaxCloud
$apiKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"; //Use the API KEY from TaxCloud
$uspsUserID = "XXXXXXXXXXXX";//depricated

Excerpt of TaxCloud.aspx

private void Page_Load(object sender, EventArgs e){
// Put your TaxCloud API Login and API Key values here, along with the USPS User ID.
string apiLoginID = "XXXXXXXX";// Use the API ID from TaxCloud
string apiKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"; //Use the API KEY from TaxCloud
string uspsUserID = "XXXXXXXXXXXX";//depricated
...
}

You can close TaxCloud.php/TaxCloud.aspx now – you are done with it.

Act 2: “Install” The Code

Second, open your HTML file in an editor (your HTML file is the page where you sell stuff, not the TaxCloud.php/TaxCloud.aspx file). You need to add the following javascript reference:

<!-- TaxCloud Requirements -->
<script type="text/javascript" src="https://taxcloud.net/taxcloudSimplify.js"></script>

Note that we are including with ‘https’ because we are doing a purchase page. Payment processors usually have this requirement. In fact, as we are demonstrating integration with Simplify, we need to ensure https per their requirements:

<!-- Simplify Requirements -->
<script
type="text/javascript"
src="https://www.simplify.com/commerce/v1/simplify.js"></script>

And a bit of JQuery for good measure:

<script
type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script
type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

Finally, we are going to add reference to our default JQuery UI Theme, a slightly modified version of the JQuery UI Cupertino theme:

<link
href="https://taxcloud.net/downloads/TaxCloud.js/HelloSimplify.html/jquery-ui-1.10.3.simplify.min.css"
rel="stylesheet"/>

Of course, if your site already uses a JQuery UI Theme, you can omit this link, and the taxcloudSimplify.js UI will look like the rest of your site automatically.

Now we will look at the actual javascript code needed to make all this work. This seems like a good spot to introduce the TaxCloud objects defined in taxcloudSimplify.js. They are:

  • TaxCloudConnection — this handles the actual network communication between the web page and TaxCloud (via TaxCloud.php/TaxCloud.aspx).
  • TaxCloudAddress — this class makes it easy to use a shipping address with both the US Post Office (for verification) and TaxCloud (for tax lookups)
  • TaxCloudCartItem — represents an item in your cart a customer can purchase. It has a price, quantity and Taxability Information Code (TIC). [You will need to be logged-in to review complete TIC documentation]
  • TaxCloudCart — manages a collection of TaxCloudCartItems
  • TaxCloud — manages your cart, origin and destination (shipping) addresses and communication. The TaxCloud javascript object exposes the actual methods you’ll be calling to work with our TaxCloud online services (VerifyOriginAddress, VerifyDestinationAddress, Lookup, AuthorizedWithCapture, Returned).

But what does this look like in code? In a script section, start with this:

var myTaxCloud = new TaxCloud("TaxCloud.php", "doPurchase.php");
myTaxCloud.publicKey = “Your Simplify Public Key”;
myTaxCloud.storeName = “Your Store Name";

$().ready(function(){//be sure page is fully loaded
   myTaxCloud.Install(4);  // Show all four UI tabs
   myTaxCloud.SetCustomerID(getCustomerID(), true);
 });

function getCustomerID(){
  //go get your customer identifier from somewhere
  //if you already have their address, you could pre-populate the address form.
  return "fabulousCustomer399";
}

When we create our new TaxCloud instance, we provide two parameters:

  1. taxCloudPostUrl — the path to the TaxCloud.php/TaxCloud.aspx page on your server
  2. purchasePostUrl — the path to your payment handler page on your server, in our case doPurchase.php which uses Simplify as our payment gateway

simplifyCommerceKeysNext we have to set the Simplify public key for TaxCloud to use. Not much will happen without this. Go to your Simplify dashboard to get your public key.

You can also see that we have set the TaxCloud variable “storeName” – you should set this to the name of your store, which will be seen by your customers in the checkout UI titlebars.

After initializing TaxCloud, we use JQuery’s ready() to register an event and finish “installing” taxcloud on your HTML page.
TaxCloud has several events you can hook into during the processing of the address and cart. Every button you see in the TaxCloud UI can be wired for a callback in case you need to do any special processing. For example, this can notify you that the customer has completed the cart steps (provided their shipping address and looked up their tax information) and therefore a ‘Grand Total’ is available. You could stop the default TaxCloud processing, grab that grand total and begin your own unique purchase process. Or you can let TaxCloud handle everything. The choice is yours.

The last line in this code snippet sets the unique customer id for the end user. The customerID is a field you supply that uniquely represents the customer. The function also takes a flag that tells TaxCloud whether or not to retrieve previous address and cart information, if found. This handles the case where people start a purchase, cancel it and then return later to pick up where they left off. Right now we only store this information for 24 hours. You can use this customerID later to view customer specific transactions in our activity log. The customerID field is required.

Fabulous, taxcloudSimplify.js is now installed and ready to go to work.

Act 3: Where are you?

We have one more step before you can get onto the business of selling things. You need to tell taxcloudSimplify.js what your address is (your store or office location). Note: This location must also be added to the TaxCloud website, in the Locations section.

SetMyAddress();//this should be done within the $(document).ready function

function SetMyAddress() {
  myTaxCloud.addressOrigin.address1 = "Your Address";
  myTaxCloud.addressOrigin.city = "Your City";
  myTaxCloud.addressOrigin.state = "Your State as Two Letters";
  myTaxCloud.addressOrigin.zip5 = "Your 5-Digit zip code";
}

Act 4: The Products

Next we need to let TaxCloud know what the items are that we will be checking tax information for. This means we need to create a TaxCloudCart with a list of TaxCloudCartItem objects. Each TaxCloudCartItem object has five properties:

  1. an item identifier (a SKU works great) but we do not recommend using a title or product name – this identifier is for machine use, not human use
  2. the item display name or brief description – this one is for human use
  3. the unit price
  4. a quantity
  5. a TIC (remember that Taxability Information Code?)

You can add TaxCloudCartItems to the TaxCloudCart one at a time or in bulk. For example, to add a single item at a time you could create a button as follows:

<button
  id="001"
  onclick="myTaxCloud.cart.AddItem(new TaxCloudCartItem('TST001','Awesome product',24.99,1,00000))"
  type="button">
   Add to cart
</button>

The ‘onclick’ handler adds the new TaxCloudCartItem to the TaxCloudCart, which triggers an internal event so that it immediately appears in the UI. Then the ‘onclick’ handler does a Lookup to update all the line items in the cart, including the new one we just added.

We could also fill a cart with items in bulk like this:

FillTaxCloudCart();

function FillTaxCloudCart() {
 if (myTaxCloud.cart.items.length == 0) {
  myTaxCloud.cart.AddItem(new TaxCloudCartItem("MTS102", "Blue T-shirt", 1.5, 1, 20010));
  myTaxCloud.cart.AddItem(new TaxCloudCartItem("MTS103", "Pencil", .99, 1, 20070));
  myTaxCloud.cart.AddItem(new TaxCloudCartItem("PRD711", "Potato Chips", 1.9, 1, 40030));
  myTaxCloud.cart.AddItem(new TaxCloudCartItem("PRD712", "8 oz. bottle of water", .49, 12, 40060));
  myTaxCloud.cart.AddItem(new TaxCloudCartItem("FLG001", "Connecticut flag", 19.99, 1, 90104));
  myTaxCloud.cart.AddItem(new TaxCloudCartItem("GRP001", "Graphic design", 99, 1, 91040));
  myTaxCloud.cart.AddItem(new TaxCloudCartItem("SVC003", "Running shoes", 149, 1, 92005));
  myTaxCloud.deliveredBySeller = false;//True only if delivered in a seller vehicle
 }
}

Act 5: The Customer

Once we have the origin address and the cart in place we need to get the shipping address, verify it and do the tax lookup. Here we will make use of the taxcloudSimplify.js built-in UI to display an address form the customer can fill out. We respond to a click event on the page to start the purchase flow. In this case we created a standard button that a JQuery handler will catch the ‘click’ event for. I named it with id=’TaxCloudPurchaseButton’, but you can call it anything you like.

So, let’s create our purchase button:

<button id="TaxCloudPurchaseButton" type="button">Purchase</button>

Now, let’s wire-it up to the taxcloudSimplify.js:

//this should be put within the $(document).ready function
$('#TaxCloudPurchaseButton').click(function () {
 myTaxCloud.Open();
 return false;
});

When a user clicks the button identified by ‘TaxCloudPurchaseButton’, it fires the javascript code above and taxcloudSimplify.js initiates the UI.TaxCloud Address Entry for Simplify Commerce

Specifically, it calls ‘Open()’. This tells the TaxCloud library to use its built-in UI components. Once this call is made the UI pops up to obtain the customer’s shipping address.

This form will be filled out by the customer and represents their shipping address for all the items in the cart. If the customer is outside of the USA they can click the ‘My shipping address is not in the USA’ checkbox and TaxCloud will not compute sales tax for the items in the cart. The button at the lower-left lets them know the ‘state’ of their address. That is, if its verified or unverified. At this point, you can click on the USPS verify address button if you want the US Post Office to validate what you have entered, but it is not necessary because taxcloudSimplify.js does this automatically when you press ‘Next’. So, let’s enter an example shipping address to work with and click ‘Next’ to go to our second page.TaxCloud Cart Items for Simplify Commerce

Now we see all the items in our cart. Lets talk for a moment about what else is going on here. You can see now that the address has been verified (or verification failed). You don’t need to have a verified address in order to complete a purchase, but a verified address will ensure the most accurate sales tax rates.

After attempting to verify the address, taxcloudSimplify.js proceeds to lookup the correct sales tax amount due for each item in the cart. These calls happen asynchronously, which means the customer may see the sales tax amounts appear/update in the cart.

We also see each item listed with a unit price, the current quantity, the line item price, the line item tax amount and the line item total (price + tax). Finally, just above the ‘Update’ and ‘Purchase’ buttons we have the total, which is the sum of price and tax for all line items.

This form is interactive as well in that the customer can change quantity amounts and everything will be looked-up and computed again. Simply adjust a quantity and either click in another field to trigger the update, or click the ‘Update’ button. The new prices and tax amounts will be changed in the screen when the asynchronous calls receive their responses.

At this point you may be curious what code you need to add in order to handle the transition from the first purchase page to the second. The answer is no additional code is needed. The TaxCloud library, being UI aware, handles this transition for you. We do make callback hooks available if you require additional processing before proceeding, but we’re keeping things simple for the time being. In a future post we will look at all the TaxCloud UI events available.

Act 6: The Purchase

Once the customer agrees with their cart they click ‘Next’ to purchase the items in the cart. This brings up the third tab containing a very simple credit card form modeled right from Simplify. All of the best practices recommended by MasterCard Simplify Commerce are followed on this page for your, and your customers, peace of mind.TaxCloud Credit Card Entry for Simplify Commerce

The purchase amount is carried forward from the items tab and the rest of the fields the customer fills in. Once that is done they click ‘Process Payment’. Again, taxcloudSimply.js will handle the payment processing by default. You can attach a callback so that you handle your own payment process if you like.

So what does the Simplify purchasing code look like? Our implementation looks like this:

TaxCloud.prototype.PurchaseStep3ProcessClicked = function () {
    if (this.OnPurchaseStep3ProcessClicked)
        this.OnPurchaseStep3ProcessClicked(this);
    else {
        SimplifyCommerce.generateToken({
            key: this.publicKey,
            card: {
                number: $("#cc-number").val(),
                cvc: $("#cc-cvc").val(),
                expMonth: $("#cc-exp-month").val(),
                expYear: $("#cc-exp-year").val()
            }
        }, TaxCloudHelper_SimplifyResponseHandler);
    }
}

function TaxCloudHelper_SimplifyResponseHandler(data, status) {
    if (data.error) {
        // Show any validation errors
        if (data.error.code == "validation") {
            var fieldErrors = data.error.fieldErrors,
                fieldErrorsLength = fieldErrors.length,
                errorList = "";
            for (var i = 0; i < fieldErrorsLength; i++) {
                errorList += "</pre>
<div class="error">Field: '" + fieldErrors[i].field +
 "' is invalid - " + fieldErrors[i].message + "</div>
<pre>";
            }
            // Display the errors
            $paymentForm.after(errorList);
        }
    } else {
        // The token contains id, last4, and card type
        var token = data["id"];
        var request = new TaxCloudConnection(TaxCloudHelper_myTaxCloudInstance);
        var formData = "amount=" + Math.floor(TaxCloudHelper_myTaxCloudInstance.cart.GrandTotal() * 100);
        formData += "&description=" + encodeURIComponent(this.storeName);
        formData += "&reference=" + new Date().getTime().toString();
        formData += "&token=" + token;
        request.postPurchase("doPurchaseSimplify.php", formData, "SimplifyPurchaseResponse");
    }
}

TaxCloud.prototype.SimplifyPurchaseResponse = function (request) {
    var responseText = request.GetResponseText();
    if (this.OnPurchaseStep3ProcessResponse)
        this.OnPurchaseStep3ProcessResponse(this, responseText);
    else {
        // go to the fourth tab: Receipt
        $('#TaxCloudTabs').tabs('option', 'active', 3);
    }
}

This is a fair amount of code that you don’t have to do yourself. But, again, the choice is yours as you notice a conditional user supplied callback that lets you gain control of the actual payment processing:

if (this.OnPurchaseStep3ProcessClicked)
        this.OnPurchaseStep3ProcessClicked(this);

To enable this callback simply set the TaxCloud.OnPurchaseStep3ProcessClicked value to a function and it will be called at the appropriate time.

One additional step that TaxCloud handles for you is the ‘Capture’ notification to TaxCloud that lets the system know funds will be transferring and sales tax should be retrieved. If you handle the ‘OnPurchaseStep3ProcessClicked’ event, then you will also need to handle the ‘AuthorizedWithCapture’ call to TaxCloud’s servers.

Act 7: The Receipt

Even though everything has been handled online, a receipt is still valuable for helping the customer feel secure in their purchase. Upon a successful purchase, TaxCloudSimply lists out details of the sale onto a printable page.TaxCloud receipt for Simplify Commerce

At this point we are done. The items have been identified, the sales tax was calculated, the grand total was used to process a payment and TaxCloud was notified of the event for future tax collection. So what was the sum total of javascript that a web developer had to write in order to make all this happen? Given an HTML purchase page, they could start by copying and pasting the following into a javascript block:

   var myTaxCloud = new TaxCloud("TaxCloud.php", "doPurchaseSimplify.php");
   myTaxCloud.publicKey = "Your Simplify Public Key";
   myTaxCloud.storeName = "Your Store Name";
   $().ready(function () {
     myTaxCloud.Install(4);
     SetMyAddress();
     myTaxCloud.SetCustomerID(getCustomID(), true);
     FillTaxCloudCart();
     //enable to verify communications via TaxCloud.php (or TaxCloud.aspx) are working correctly
     //myTaxCloud.Ping(null, TaxCloudPingCallback);
     $("#TaxCloudPurchaseButton").click(function () {
       $('#TaxCloudDialog').dialog('open');
         return false;
       });
   });
   function SetMyAddress() {
     myTaxCloud.addressOrigin.address1 = "3205 South Judkins Street";
     myTaxCloud.addressOrigin.city = "Seattle";
     myTaxCloud.addressOrigin.state = "WA";
     myTaxCloud.addressOrigin.zip5 = "98144";
   }
   function getCustomerID(){
     //go get your customer identifier from somewhere
     return "fabulousCustomer399";
   }
   function FillTaxCloudCart() {
     if (myTaxCloud.cart.items.length == 0) {
       myTaxCloud.cart.AddItem(new TaxCloudCartItem("SAU102", "This is a really long item name", 1.5, 1, 30070));
       myTaxCloud.cart.AddItem(new TaxCloudCartItem("MTS102", "Blue T-shirt", 1.5, 1, 20010));
       myTaxCloud.cart.AddItem(new TaxCloudCartItem("MTS103", "Pencil", .99, 1, 20070));
       myTaxCloud.cart.AddItem(new TaxCloudCartItem("PRD711", "Potato Chips", 1.9, 1, 40030));
       myTaxCloud.cart.AddItem(new TaxCloudCartItem("PRD712", "8 oz. bottle of watter", .49, 12, 40060));
       myTaxCloud.cart.AddItem(new TaxCloudCartItem("FLG001", "Connecticut flag", 19.99, 1, 90104));
       myTaxCloud.cart.AddItem(new TaxCloudCartItem("GRP001", "Graphic design", 99, 1, 91040));
       myTaxCloud.cart.AddItem(new TaxCloudCartItem("SVC003", "Running shoes", 149, 1, 92005));
       myTaxCloud.deliveredBySeller = false; // Set to true if delivered in a seller vehicle.
     }
   }

This is our second iteration of TaxCloud javascript integration and we are excited to hear your feedback as to how to improve it. Our goal is to make calculating sales tax as easy as possible for everyone – at no cost.

One last thing

Congratulations are in order! You have successfully integrated real-time sales tax for your customers – and you probably did it in less than an hour. Now that you have completed a transaction with your account in test-mode, you should return to TaxCloud, go to the Websites section, and click Go Live. This is important so that TaxCloud can begin preparing your monthly sales tax reports – and in 24 states, TaxCloud can even file your returns and remit your sales tax proceeds for you (with more states coming soon).

And best of all, it’s free!