Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Adjusted host name for initial script and dependencies

Table of Contents

UltraCart Hosted Credit Card Fields

...

Code Block
languagehtml/xml
themeDJango
<script type="text/javascript" src="https://securetoken.ultracart.com/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://securetoken.ultracart.com/js/json3.min.js"></script>
<script type="text/javascript">
  // Take the version that we just included and scope it locally.  The noConflict will return $ and jQuery to their
  // original values so that the version of jQuery used for the hosted fields does not conflict with any other existing
  // version of jQuery or other JS library that use $ that are on the page.
  var jQueryHostedFields = $.noConflict(true);
  // Also make sure that we're providing consistent JSON functionality in browsers, but don't pollute existing libraries
  // by running our version in noConflict mode.  This will restore whatever is there similar to jQuery.
  // This will also make sure we have a JSON implementation in older versions of IE.
  var jsonHostedFields = JSON3.noConflict();
</script>
<script type="text/javascript" src="https://securetoken.ultracart.com/checkout/checkout-hosted-fields-1.0.js"></script>
<script type="text/javascript">window.UltraCartHostedFields || document.write('<script src="//securetoken.ultracart.com/checkout/checkout-hosted-fields-1.0.js?r=' + new Date().getTime() + '"><\/script>')</script>

...

There is only one method call needed to add the UltraCart Hosted Credit Card Fields to your page.   This static method processes the configuration and returns an instance object.

Parameters

ArgumentTypeDescription
jQueryjQueryAn instance of jQuery. If you're using our sample above then the value would be "jQueryHostedFields", but if you already have jQuery available on the page then you can use "jQuery"
JSONJSON

An instance of the JSON object. If you are using our sample above then the value would be "jsonHostedFields".

Note

Most browsers provide their own JSON object which can be used by the API, but including an external version as the sample above provides consistency across all browsers and versions.


configobject


 
PropertyTypeRequiredDescription
sessionCredentialsObjectYesSee SessionCredentials below.
cssUrlsString[]
An optional array of CSS URLs that you would like injected into the iframe to further style the hosted input.
formString 
An optional jQuery selector to locate the form. The underlying fields will be re-enabled before submission so that the masked values will be submitted.
hostedFieldsObjectYesSee HostedFields below.
overlayZIndexInteger 
Change the default z-index for the overlay. If not specified then the overlay will use a z-index of 999999.
autoCopyStylesString[] 

By default, the hosted fields will copy a set of common styles from the underlying field to the input. This helps to keep fonts, colors, borders, etc. looking the same within the hosted field as the underlying field. If nothing is specified, then the default set of styles copied is:

[

// Padding
"paddingBottom", "paddingLeft", "paddingRight","paddingTop",
// Text
"lineHeight", "fontSize", "fontFamily", "fontStyle", "fontWeight",
// Color
"backgroundColor", "color",
// Border
"borderBottomColor", "borderBottomLeftRadius", "borderBottomRightRadius","borderBottomStyle",
"borderBottomWidth", "borderCollapse", "borderLeftColor", "borderLeftStyle","borderLeftWidth",
"borderRightColor", "borderRightStyle", "borderRightWidth", "borderSpacing", "borderTopColor",
"borderTopLeftRadius", "borderTopRightRadius", "borderTopStyle", "borderTopWidth"

 ]


...

TypeDescription
UltraCartHostFieldsInstance of the hosted fields object. This variable should be stored way if any of the advanced methods need to be called.

 


SessionCredentials

This object contains necessary identifiers that must be passed by the UltraCart Hosted Credit Card Fields to sync up the data properly with the customer's shopping cart session.

PropertyTypeRequiredDescription
merchantIdStringYesThis is the merchant ID for the UltraCart account.
shoppingCartTokenString 
This value is provided to the legacy checkout and the StoreFront checkout as $shoppingCartToken.
shoppingCartIdStringRecommended for javascript checkouts.

This is the cart.cartId for the JavaScript/REST Checkout.

Warning

If you're using the hosted fields on a web page that's collecting credit card information for updating an existing order, or an existing auto order, do NOT provide a shoppingCartId.  By leaving it off the request, the server will return back a token field that you will use to update your order/auto order record.  The shoppingCartId is ONLY for placing new orders.


...

PropertyTypeRequiredDescriptionChild Properties
creditCardNumberObjectYesConfigures the credit card number field on the checkout.


PropertyTypeRequiredDescription
selectorStringYesjQuery selector that identifies the original credit card number input field that will be transformed into a hosted field.
selectorContextElement or jQuery object 
If you need the selector to find elements within a context, populate the selectorContext property. This property along with the one above is passed to a jQuery call like jQuery(selector, selectorContext). This is typically needed only if you have a heavily dynamic page and are rendering HTML using Backbone or another JavaScript MVC framework.
alertIfMissingboolean 
Pop an alert if the underlying field was not found on the page. If this is false the hosted fields script will attempt to log a console message. If you ever see the error or the alert message, you are firing the setup script before the element is visible to jQuery.
tokenSelectorString 
Optional jQuery selector that will be used to store the token received after the card is submitted. This is only necessary for simple form post checkouts where the session credentials only contains the merchant id and the values will be submitted to the UCEditor URL.
placeholderString 
The input fields placeholder value. If your design utilizes placeholders then you can provide it here. If the underlying input field contained a placeholder then it will automatically be read and carrier through to the hosted field.
callbackfunction(card) 
An optional function that will be called with a card object after the card is submitted to the server.
changefunction() 
An optional function that can handle the change to the hosted field. The only parameter to the change function is the masked value. If no change function is provided then the default behavior is to update the underlying credit card number input field with the masked value.


creditCardCvv2ObjectRecommendedConfigured the credit card CVV2 field on the checkout.


PropertyTypeRequiredDescription
selectorStringYesjQuery selector that identifies the original credit card CVV2 input field that will be transformed into a hosted field.
selectorContextElement or jQuery object 
If you need the selector to find elements within a context, populate the selectorContext property. This property along with the one above is passed to a jQuery call like jQuery(selector, selectorContext). This is typically needed only if you have a heavily dynamic page and are rendering HTML using Backbone or another JavaScript MVC framework.
alertIfMissingboolean 
Pop an alert if the underlying field was not found on the page. If this is false the hosted fields script will attempt to log a console message. If you ever see the error or the alert message, you are firing the setup script before the element is visible to jQuery.
tokenSelectorString 
Optional jQuery selector that will be used to store the token received after the CVV2 is submitted. This is only necessary for simple form post checkouts where the session credentials only contains the merchant id and the values will be submitted to the UCEditor URL.
placeholderString 
The input fields placeholder value. If your design utilizes placeholders then you can provide it here. If the underlying input field contained a placeholder then it will automatically be read and carrier through to the hosted field.
changefunction() 
An optional function that can handle the change to the hosted field. The only parameter to the change function is the masked value. If no change function is provided then the default behavior is to update the underlying credit card CVV2 input field with the masked value.


...

PropertyTypeDescription
maskedCreditCardNumberStringThe masked credit card number returned after the real card number is stored.
tokenStringA token that can be passed to the UCEditor URL for simple hosted forms.
cardTypeStringThe type of card. This value can be used to select a drop box input for perform validation.

 


The instance object returned from setup also has some additional methods that can be called.  

...

Tip

addClass and removeClass are not static methods. They regular methods you may call from your hosted fields object.

Example:

var hostedFields = UltraCartHostedFields.setup(jQuery, JSON3, {/* tons of configuration here that's been omitted for brevity */});

//later, during validation, if the credit card field is blank, add a class to the cc number overlay field like this:

hostedFields.addClass('someMissingFieldClassName', "creditCardNumber")

 


The next two methods addClass and removeClass can be used to adjust classes on the iframe's document body.  This allows for the CSS of the internal iframe to change state based upon behaviors taking place on the parent document.  

...

The next method destory should be used to cleanup the hosted fields.  If you're repainting the screen using an advanced MVC JavaScript framework then make sure you destory the UltraCartHostedFields instance, repaint the page's content, and then re-initialize a new UltraCartHostedFields instance using the setup method.


The following sections demonstrate various types of usages for the UltraCart Hosted Credit Card Fields.

Implementing UltraCart Hosted Credit Card Fields in Simple Form Post Checkouts

...

Code Block
languagehtml/xml
themeDJango
titleSample Simple Form Post
linenumberstrue
<script type="text/javascript" src="https://securetoken.ultracart.com/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://securetoken.ultracart.com/js/json3.min.js"></script>
<script type="text/javascript">
  // Take the version that we just included and scope it locally.  The noConflict will return $ and jQuery to their
  // original values so that the version of jQuery used for the hosted fields does not conflict with any other existing
  // version of jQuery or other JS library that use $ that are on the page.
  var jQueryHostedFields = $.noConflict(true);
  // Also make sure that we're providing consistent JSON functionality in browsers, but don't pollute existing libraries
  // by running our version in noConflict mode.  This will restore whatever is there similar to jQuery.
  // This will also make sure we have a JSON implementation in older versions of IE.
  var jsonHostedFields = JSON3.noConflict();
</script>
<script type="text/javascript" src="https://securetoken.ultracart.com/checkout/checkout-hosted-fields-1.0.js"></script>
<!-- the following line is a redundant check to ensure the hosted fields file is loaded first -->
<script type="text/javascript">window.UltraCartHostedFields || document.write('<script src="//securetoken.ultracart.com/checkout/checkout-hosted-fields-1.0.js?r=' + new Date().getTime() + '"><\/script>')</script>
<script type="text/javascript">

  jQueryHostedFields(document).ready(function() {
    UltraCartHostedFields.setup(jQueryHostedFields, jsonHostedFields, {
          'sessionCredentials': {
            'merchantId': 'DEMO' // Change to your merchant ID
            // NOTE: This example if for a form post.  If you're using a javascript checkout, the session credentials
            // also need the 'shoppingCartId'.  But ONLY for javascript checkouts.
          },
          'cssUrls':[
//              'https://www.mysite.com/styles.css'
          ],
          'form': '#myForm',  // This is only needed for a form POST.  javascript checkouts should not be providing this.
          'hostedFields':{
            'creditCardNumber': {
              'selector': '#cardNumber',
              'tokenSelector': '#cardNumberToken' // This is only needed for a form POST.  javascript checkouts dont deal with tokens
            },
            'creditCardCvv2': {
              'selector': '#cvv2',
              'tokenSelector': '#cvv2Token' // This is only needed for a form POST.  javascript checkouts dont deal with tokens
            }
          }
        });
  });

</script>

<form action="https://secure.ultracart.com/cgi-bin/UCEditor" method="POST" id="myForm">

  <!-- Change the value of this input to your merchant ID -->
  <input type="hidden" name="merchantId" value="DEMO">

  <!-- These are the two token values that will be submitted to the UltraCart server that will sync up the sensitive data -->
  <input type="hidden" name="CreditCardNumberToken" id="cardNumberToken">
  <input type="hidden" name="CreditCardCvv2Token" id="cvv2Token">

  <input type="text" name="CreditCardNumber" id="cardNumber" value=""/>
  <br/><br/>

  <input type="text" name="CreditCardCVV2" id="cvv2"/>
  <br/><br/>

  <input type="submit" value="submit">
</form>

...

The github home page for the responsive checkout has a section with instructions for adding hosted fields to your javascript checkout.  It's easy.  There's a detailed github gist linked within the instructions that has all the code you should need.

 


Anchor
testing
testing

How do I know if Hosted Fields are even working??

...

Second, do you see a couple of hosted field jsp files loading?  One should load for each field (credit card, cvv) to create an iframe for each.

 


 


Third, do you see a call going out to UCCheckoutAPIHostedFields each time you enter a full value in either the credit card or cvv field?  Was the call successful?

 


Finally, can you put through test orders?  If you're seeing all of the above correctly, and still getting back errors about a missing credit card number, check your UltraCartHostedFields.setup block.  That's been the problem the majority of the time.   Here are the usual culprits:

...

Code Block
languagejavascript
themeDJango
// as a reminder, jQueryHostedFields is a reference to a jQuery object. 
// The CSS style of the hosted fields will mimic the underlying fields, so for example, if you
// change the credit card field to have a red background, then the hosted fields will also change to red.
 
    jQueryHostedFields("#cardNumber").on('change', function(){
      // Clear existing classes
      jQueryHostedFields("#cardNumber").removeClass("noCreditCardNumber");
      jQueryHostedFields("#cardNumber").removeClass("validCreditCardNumber");
      jQueryHostedFields("#cardNumber").removeClass("invalidCreditCardNumber");

      // Regex for basic validation of a masked Amex or other 16 digit card.
      var re = /[X]{4}-[X]{6}-X[0-9]{4}|[X]{4}-[X]{4}-[X]{4}-[0-9]{4}/i;

      // Test to see if the field is empty, appears valid or is invalid
      var fieldValue = jQueryHostedFields(this).val();
      if (fieldValue === "") {
        jQueryHostedFields("#cardNumber").addClass("noCreditCardNumber");
      } else if (re.test(fieldValue)) {
        jQueryHostedFields("#cardNumber").addClass("validCreditCardNumber");
      } else {
        jQueryHostedFields("#cardNumber").addClass("invalidCreditCardNumber");
      }
    });

    jQueryHostedFields("#cvv2").on('change', function(){
      // Clear existing classes
      jQueryHostedFields("#cvv2").removeClass("noCreditCardCvv2");
      jQueryHostedFields("#cvv2").removeClass("validCreditCardCvv2");
      jQueryHostedFields("#cvv2").removeClass("invalidCreditCardCvv2");

      // Regex for basic validation of a masked CVV2 value.
      var re = /[X]{3,4}/i;

      // Test to see if the field is empty, appears valid or is invalid
      var fieldValue = jQueryHostedFields(this).val();
      if (fieldValue === "") {
        jQueryHostedFields("#cvv2").addClass("noCreditCardCvv2");
      } else if (re.test(fieldValue)) {
        jQueryHostedFields("#cvv2").addClass("validCreditCardCvv2");
      } else {
        jQueryHostedFields("#cvv2").addClass("invalidCreditCardCvv2");
      }
    });

    // Perform initial validation
    jQueryHostedFields("#cardNumber,#cvv2").trigger("change");

 


FAQ

Q: I'm a small merchant, do I have to be PCI 3.0 compliant?

...

Code Block
languagexml
themeDJango
linenumberstrue
<div class="bender-12 columns">
  <ul id="card_logos" {{#ucCompare cart.creditCardType 'false' operator="!="}}class="is_{{cart.creditCardType}}"{{/ucCompare}}>
    <li class="card_visa">Visa</li>
    <li class="card_mastercard">MasterCard</li>
    <li class="card_amex">American Express</li>
    <li class="card_discover">Discover</li>
  </ul>
</div>  

...


 


Q: I've implemented hosted fields and now the credit card number isn't masked after entering it.

A: That's okay.  The card will mask if the number is loaded from the cart or the page is reloaded.  By design, it doesn't mask upon entry anymore.