UltraCart REST Checkout API


This is Version 1 of the UltraCart REST API. It is now legacy. It will remain forever, but no new development will be done.

Please see Version 2 for new development.  Version 2 contains language specific SDKs, more functionality, and reduced API call counts.

Version 2 Main Documentation

Version 2 Supplemental Documentation


Additional Note, August 2020:

To prevent anyone from using this code in a new installation, several key samples have been removed.  These samples referred to php scripts that are no longer compatible with the UltraCart engine.    You should not be using this javascript anymore.   This documentation exists only for a reference for old legacy implementations.



Changes

(this list was started Aug 2014)

August 2014

Added localization to support non US currencies.    There are two ways to set the currency of the shopping cart.    

1. Updating the cart with cart.currencyCode will cause the localized fields to display in that currency.

2. Adding an item to the cart which has the item cost in a different currency will set the cart to that currency.   Only the first item added alters the currency of the cart.

You will now see additional fields on the Cart and CartItem ending with "Localized" and "LocalizedFormatted".  The localized fields contain currency amounts in the local currency.    The formatted fields are strings containing currency symbols for easy use in templates and mark up.

Introduction (Things you'll wish you read first)

The UltraCart REST API aims to be a lightweight protocol for tying a checkout page(s) to the UltraCart back end.


Merchant ID Required

Every call needs a merchant id (our merchant id is DEMO). We need to know who you are. There are three ways to provide the merchant id to the server:

  1. Query Parameter: _mid=DEMO
  2. HTTP Header: 'X-UC-Merchant-Id': 'DEMO'
  3. Cookie named UltraCartMerchantID

Most of the examples below use the http header since it's easy to use with jQuery. If you wished to do it for all your ajax calls, you could execute this javascript:

jQuery.ajaxSetup({ cache: false, headers: {'X-UC-Merchant-Id': 'DEMO', "cache-control": "no-cache"});

However, that makes each call less atomic (and jQuery doesn't recommend it). Still, it's an option and may work well with your site.

If you receive an error "Missing Merchant ID", you've forgotten to do one of the above.


Now, in case you're wondering why the three methods use different names...

  1. We made the query parameter as short as possible to keep the urls as short as possible. We used an underscore to denote "meta data" to the call.
  2. We follow common practices for naming custom http headers. While the X- prefix is officially out of vogue, we still think it looks cool.
  3. The cookie 'UltraCartMerchantID' is used in hundred of existing UltraCart checkout pages. So it made sense to stick with that cookie name.


Where are the errors?

When something doesn't work or you get an error, open your browser console and view the headers. Look for the error.

then fix it.

Can't? Then get on github.com. Ask for help here.

Note Regarding Support for API

API troubleshooting

UltraCart's free support does not cover API development questions or troubleshooting of custom checkout pages.

Please post your questions to the "Issues" section of the github.com API reponsitories, which are monitored and responded to by the API developers. Please allow 24-48 hours for a reply.

Additional API support and troubleshooting services can be purchased at $100/hr (1 hour minimum) via UltraCart Professional Services.

(Scheduling of paid for support will be determined by Professional Services personnel.)


/rest/cart/checkout is not the end

/rest/cart/checkout is NOT THE END! It's the beginning of the end. If the response from checkout has no errors, you must redirect the browser to the url found in checkoutResonse.redirectToUrl. That finishes the order. Any errors during that phase (card declined) will send the browser back to checkoutRequest.redirectOnErrorUrl, which is usually set to your checkout page. It's a circle, one that handles shipping companies and payment gateway timeouts without timing out the browser. It also handles any upsell gauntlets. So make sure you follow the redirect!

// incompatible code.  this code was removed.


Do this or you'll never complete an order...

By July 15th, 2015, all UltraCart checkouts must use Hosted Fields to collect credit card information.  This replaces the old storeCard function.   This is a requirement for PCI 3.0.  UltraCart staff has already updated many sites and the average time to retrofit an existing site to using Hosted Fields has taken under 20 minutes.   Some of them have been switched over in less than 5 minutes.  While the implementation of Hosted Fields is gory, the installation of them is trivial.   Please see this page for details.

Reference Implementations

All reference implementations will be hosted on github.com under the UltraCart tree ( https://github.com/UltraCart ).  You are invited and encouraged to participate in the development of these interfaces.  We hope you will use, clone, fork, and help improve these interfaces by filing suggestions and bug reports.

Current Implementations

NameDesign GoalLocationComments
responsive checkoutsingle page checkout, mobile friendlyhttps://github.com/UltraCart/responsive_checkout
two page trialsimple, geared toward trial offers
coming soon


Object Model

These json objects are used with the Cart REST API.   The documentation below is shared with checkout versions 1.0 and 2.0.  So you will see references to those libraries as well.   Please consult the API section below the REST specific usage.

Cart


FieldTypeComment
cartIdstringThe unique ID for the cart. This needs to be stored as a cookie on the customer's browser so that the cart can be retrieved.
merchantIdstringThe char(5) merchant designation (created during sign up)
errorsstring[]an array of errors returned from a call.  This property should always be consulted after a call returns and messages displayed to the end customer.

advertisingSourcestringAdvertising source the customer selected or entered.
affiliateIdstringThe ID of the affiliate associated with this cart. You can set this field to manually assign an order to a specific affiliate. If no affiliate is associated with the order then this field will be null.
affiliateSubIdstringThe Sub ID of the affiliate associated with this cart. The same comments for affiliateId apply to this field as well.
amazonMerchantIdstringThe merchant's Amazon Seller ID as configured in the UltraCart system.
amazonOrderReferenceIdstring

The reference id provided by Amazon once the customer has initiated checkout with them. If this is non-null and cart.paymentMethod is "Amazon", the order will be processed through Amazon.

This cart example has all of the amazon code plumbed. Take some time to understand it. It is NOT a trivial few lines of code to make it work seamlessly.

https://github.com/UltraCart/rest_api/tree/master/cart_example

amazonWidgetUrlstring

The url for the amazon widget script. This will be production or sandbox depending on your UltraCart configuration.

The example link in the amazonOrderReferenceId does not use these values since the scripts are loaded statically.

amazonButtonUrlstringThe url for the amazon button script. This will be production or sandbox depending on your UltraCart configuration.
arbitraryShippingHandlingTotalnumberOverride field allowing merchant to override the shipping and handling calculated by the system. To use this field, the Shipping and Handling must be configured to allow overrides.
arbitraryTaxnumberOverride field allowing merchants to override calculated tax. To use this field, the Tax must be configured to allow overrides.
arbitraryTaxRatenumberOverride field allowing merchants to override calculated tax rate. To use this field, the Tax must be configured to allow overrides.
arbitraryTaxableSubtotalnumberOverride field allowing merchants to override the taxable subtotal. To use this field, the Tax must be configured to allow overrides.
baseCurrencyCodestring

The default currency code for the merchant. For most merchants, this will be USD, but can be changed in the merchant's configuration.

see also currencyCode

Valid values are:

AUD Australian Dollar
CAD Canadian Dollar
EUR Euro
JPY  Japanese Yen
MXN  Mexican Peso
NOK  Norwegian Krone
NZD  New Zealand Dollar
GBP  Pound Sterling
RUB  Russian Ruble
SGD  Singapore Dollar
SEK  Swedish Krona
CHF  Swiss Franc
TRY  Turkish New Lira
USD  US Dollar
BRL  Brazilian Real

billToAddress1stringBill to address line 1
billToAddress2stringBill to address line 2
billToCitystringBill to city
billToCompanystringBill to company
billToCountrystringBill to country. Must be a valid country name from the getAllowedCountries() API call.
billToDayPhonestringBill to day phone
billToEveningPhonestringBill to evening phone
billToFirstNamestringBill to first name
billToLastNamestringBill to last name
billToPostalCodestringBill to postal code
billToStatestringBill to state
billToTitlestringBill to title
ccEmailstringCC Email address
collectCreditCardVerificationNumberbooleanTrue if the CVV2 should be collected for this merchant.
commentsstring

customer comments. this is usually collected via a textarea field.

Added 12/2/2013

couponsCartCoupon[ ]Coupons that have been applied to the cart.
creditCardExpirationMonthIntegerCredit card expiration month 1 = January 12 = December
creditCardExpirationYearintegerCredit card expiration year. Must be a four digit year.
creditCardNumberstring

Credit card number

As of January 2014, there is a new method for collecting credit card numbers. Please collect card numbers through the card store script. This optional method will become a requirement in the very near future.

creditCardTokenstringCredit card token (if you are using a tokenizing gateway like Stripe.com)
creditCardTypestringType of credit card. See the CREDIT_CARD_TYPE_ constants in the checkoutapi.js file for valid values.
creditCardTypesstring[]An array of credit card types (Visa, Mastercard, etc.) that are currently accepted. Used to generate drop down lists.
creditCardVerificationNumberstringCredit card verification number 4 digits for American Express and 3 digits for all other types of credit cards.
currencyCodestring

The currency of the cart. The default is the merchant default. Change this value to set the currency of the cart to a different value. If the first item added to the cart has a default currency other than USD, the cart currency will change to match the first item automatically.

(see also baseCurrencyCode)

customerProfileCreditCardIdInteger

The oid (object id) of a stored (on file) credit card to use with the checkout. Supply this to us a credit card on file.

When this is value is passed in to an update call, it will return back a cart with all the card information populated (number masked).

If you wish to remove a stored credit card from an order, set this property to 0 (zero). That will reset it.

The credit card id is found in the cart object of a logged in customer at cart.customerProfile.creditCards[0].id

UltraCart does not store CVV values. If you chose to allow stored credit cards, you must configure your payment gateway not to require CVV values. If a stored card is used, UltraCart will not validate/require a CVV.

A list of stored credit cards can be obtained from the MyAccount REST API. The customer must be logged in to retrieve a list of credit cards on file.

There are two ways to create a customer account (profile). The /rest/cart methods do not actually create the customer profile until the order completes. At that time, it will store the addresses used and credit cards (if your merchant account is configured to do so).

The MyAcccount REST API does create the customer immediately so it can be used with the MyAccount customer portal. Both APIs use a shopping cart as the underlying cookie/state maintenance. So a customer logged into one is automatically logged into the other.

customField1stringA custom field to store up to 50 characters.
customField2stringA custom field to store up to 50 characters.
customField3stringA custom field to store up to 50 characters.
customField4stringA custom field to store up to 50 characters.
customField5stringA custom field to store up to 50 characters.
customField6stringA custom field to store up to 50 characters.
customField7stringA custom field to store up to 50 characters.
customerProfileCustomerProfileIf loggedIn, this variable will contain the CustomerProfile for the current session.
deliveryDateDateDelivery date (optional)
emailstringEmail address
emailConfirmstringSecond copy of email address used to confirm the customer entered it correctly
exchangeRatenumberThe conversion rate between merchant default and local currencies
giftCertificatestringGift certificate code

giftCertificateAmount

giftCertificateAmountLocalized

giftCertificateAmountLocalizedFormatted

number

number

string

Gift certificate amount

giftCertificateRemainingBalanceAfterOrder

giftCertificateRemainingBalanceAfterOrderLocalized

giftCertificateRemainingBalanceAfterOrderLocalizedFormatted

number

number

string

The balance remaining the gift certificate if its initial value was greater than the cart total.

giftCharge

giftChargeLocalized

giftChargeLocalizedFormatted

number

number

string

Gift charge
giftEmailstringEmail address of the person receiving this purchase as a gift
giftEmailstringGift Email address
giftMessagestringGift message

giftWrapCost

giftWrapCostLocalized

giftWrapCostLocalizedFormatted

number

number

string

Gift wrap cost
hasAmazonbooleanThis will be true if the merchant has "Pay with Amazon" configured properly AND the cart supports it, i.e. the items can be process through Amazon Payments. If the cart is empty, this will be false, since you can't checkout with zero items.
hasPayPalbooleanTrue if the merchant has PayPal enabled.
ipAddressstringIP Address of the customer. Used for geo-location of shipping estimates.
itemsCartItem[ ]All the items in the cart.
liftGatebooleanTrue if this purchase will require delivery by lift gate, false (default) otherwise.
loggedInbooleantrue if a customer profile is active, false if otherwise
mailingListOptInbooleanWhether the customers wants to receive news and special offers via email.
needShippingbooleantrue if the cart needs shipping calculated.
needPaymentboolean

true if the cart should collect payment. This may seem a little useless since it would stand to reason that any time the total is greater than zero payment should be collected. However, there are outside cases where this flag makes the difficult easy. For example, if a customer purchases a free product that is tied to an auto order, then the total of the cart is zero, but payment must be collected for the recurring item to be charged against. This flag makes those scenarios automatic where they would otherwise be impossible to determine without some hardcoded measures.

Note: Added January 2014. Only available with the REST API

passwordstring

the password is only used during the login (or register) process to log a customer in. It is not populated on any returned objects, so it is lost (purposely) after login.

Constraints: 30 characters max.

payPalButtonAltTextstringAlt text to use on the PayPal express checkout image
payPalButtonUrlstringURL of the PayPal express checkout image
payPalCompatiblebooleanTrue if this cart is compatible with PayPal
paymentMethodstringType of payment method. See the PAYMENT_METHOD_ constants in the checkoutapi.js file for valid values.
purchaseOrderNumberstringPurchase order number
rtgCodestringSpecify the Rotating Transaction Gateway for this checkout experience.
screenBrandingThemeCodestringThe screen branding theme associated with the cart.
shipOnDateDateShip on date (optional)
shipToAddress1stringShip to address line 1
shipToAddress2stringShip to address line 2
shipToCitystringShip to city
shipToCompanystringShip to company
shipToCountrystringShip to country. Must be a valid country name from the getAllowedCountries() API call.
shipToFirstNamestringShip to first name
shipToLastNamestringShip to last name
shipToPhonestringShip to phone
shipToPostalCodestringShip to postal code
shipToResidentialbooleanTrue if the address is residential.
shipToStatestringShip to state
shipToTitlestringShip to title

shippingHandling

shippingHandlingLocalized

shippingHandlingLocalizedFormatted


number

number

string

Shipping and handling cost

This must be set manually when assigning the shippingMethod! The backend will not calculate this during cart updates. Shipping costs are extremely slow to calculate because numerous third party companies (Fed Ex, UPS, USPS) must be contacted etc. Therefore, when you assign the shipping method, you must also set the price in order the the customer to see it correctly reflected during the ordering process. When the order is submitted, the actual shipping is recalculated and set by the back end. This prevents any clever customers from trying to override the cost by putting zero in the field.

shippingHandlingDiscount

shippingHandlingDiscountLocalized

shippingHandlingDiscountLocalizedFormatted

number

number

string

Shipping and handling discount (because of coupon)

shippingHandlingWithDiscount

shippingHandlingWithDiscountLocalized

shippingHandlingWithDiscountLocalizedFormatted

number

number

string

Shipping and handling cost after discount applied.
shippingMethodstringShipping method
specialInstructionsstringSpecial instructions for delivery.
storeCreditCardboolean

If true and the customer has logged in (cart.customerProfile != null and cart.loggedIn == true), then the credit used during the purchase is stored in the customer's profile.

UltraCart considers it good ettiquette to prompt the user to store their credit card. On the normal checkout pages, this is done via a checkbox.

subtotal

subtotalLocalized

subtotalLocalizedFormatted

number

number

string

Subtotal

subtotalDiscount

subtotalDiscountLocalized

subtotalDiscountLocalizedFormatted

number

number

string

Subtotal discount (because of coupon)

subtotalWithDiscount

subtotalWithDiscountLocalized

subtotalWithDiscountLocalizedFormatted

number

number

string

Subtotal after discounts have been applied

surcharge

surchargeLocalized

surchargeLocalizedFormatted

number

number

string

Credit card surcharge amount

tax

taxLocalized

taxLocalizedFormatted

number

number

string

Tax
taxCountystringThe tax county assigned to this customer. See method getTaxCounties().
taxExemptnumberTrue if the customer is tax exempt
taxRatenumberTax rate

taxableSubtotal

taxableSubtotalLocalized

taxableSubtotalLocalizedFormatted

number

number

string

Taxable subtotal

taxableSubtotalDiscount

taxableSubtotalDiscountLocalized

taxableSubtotalDiscountLocalizedFormatted

number

number

string

Taxable subtotal discount (because of coupons)

taxableSubtotalWithDiscount

taxableSubtotalWithDiscountLocalized

taxableSubtotalWithDiscountLocalizedFormated

number

number

string

Taxable subtotal after discounts.

total

totalLocalized

totalLocalizedFormatted

number

number

string

Total
upsellPathCodestring

A string dictating which upsell path code should be followed. By specifying this path, this will override any upsells normally followed based on the cart contents.

Note: Added Dec, 2013, Available only for the Checkout REST API.


CartCoupon

This object represents a coupon that has been applied to a shopping cart.

Field

Type

Description

couponCode

String

The coupon code used by the customer.

CartItem

This object represents a an item currently in the shopping cart.

Why two items? Item and CartItem are mostly the same, but CartItem contains pricing information relative to the cart. For example, coupons added to the cart could affect the price of an item, etc. So you want to an Item object to display an item on a product page or list, and use the CartItem when displaying an item contained in a cart. This shouldn't be a real issue, as the CartItem objects are only found with the items array property of the Cart itself.

currency fields, such as unitCost, will have two other fields, a Localized and LocalizedFormatted field. The Localized Field is the amount in the cart currency, which may differ from the base currency of the item. The LocalizedFormatted field is the amount in the cart currency, and formatted for that currency with proper symbols, commas, and decimal places. *You should almost always be using the Localized and LocalizedFormatted fields so that your shopping cart can handle multiple currencies.

All "Localized" and "LocalizedFormatted" fields are available to the REST API only. They are not present in the older APIs.



Field

Type

Description

Comments

itemId

string

Item ID




arbitraryUnitCost

arbitraryUnitCostLocalized

arbitraryUnitCostLocalizedFormatted

number

number

string

Arbitrary unit cost (not functional at this time) (works with the REST API)


attributes

CartItemAttribute

Attributes configured on the item

autoOrderSchedule

string

Schedule to put this auto orderable item on (only applicable if the item is configured for customer selected auto order)


defaultImageUrl

string

The full url for the item's default image.

Added June 2011, available to versions 1.1+

defaultImageSslstringThe full url for hte item's default image with an https:// protocol

defaultThumbnailUrl

string

The full url for the item's default thumbnail.

Added June 2011, available to versions 1.1+

defaultThumbnailSslstringThe full url for the item's default thumbnail with an https:// protocol

description

string

Description


discount

discountLocalized

discountLocalizedFormatted

number

number

string

The discount this item is receiving, be it from a combination of products purchased, coupons, whatever.



extendedDescription

string

Extended description


height

Distance

Height of the item


itemOid

integer

A unique item object identifier. This is provided to easy debugging with UltraCart premium support. Note, this uniquely identifies an item, but a single item may appear more than once in a cart. So it is NOT guaranteed to be unique within a cart.


kit

boolean

True if this item is a kit


kitComponentOptions

CartKitComponentOption

Kit component options that the customer needs to provide


length

Distance

Length of the item


manufacturerSuggestedRetailPrice

manufacturerSuggestedRetailPriceLocalized

manufacturerSuggestedRetailPriceLocalizedFormatted

number

number

string

The MSRP of the item.


maximumQuantity

number

The maximum quantity of this item a customer can purchase.


minimumQuantity

number

The minimum quantity of this item the customer must purchase.


multimedias

CartItemMultimedia

Multimedia objects available for this item.


options

CartItemOption[ ]

Options on the item that customer needs to provide


positionnumberA zero based counter that is simply a number associated with each item in the cart. It feigns uniqueness.Only available to REST API
preorderboolean

True if the item is on pre-order. 

If any of your items are on pre-order your checkout should not allow PayPal or Amazon Payments as a payment option.


quantity

number

Quantity


schedulesstring[ ]If the cart item is configured for auto orders, this array will contain all of the possible re-order frequencies the customer may choose. These should be displayed to the customer in a select box allowing them to decide.

totalCost

totalCostLocalized

totalCostLocalizedFormatted

number

number

string

unit cost * quantity

the main purpose this field was added was to allow multi-currency carts to display the total cost in a formatted manner without having to do currency conversions.


totalCostWithDiscount

totalCostWithDiscountLocalized

totalCostWithDiscountLocalizedFormatted

number

number

string

unit cost * quantity with discounts figured into the price.

the main purpose this field was added was to allow multi-currency carts to display the discounted total cost in a formatted manner without having to do currency conversions.


unitCost

unitCostLocalized

unitCostLocalizedFormatted

number

number

number

Unit cost of item


unitCostWithDiscount

unitCostWithDiscountLocalized

unitCostWithDiscountLocalizedFormatted

number

number

string

Unit cost of item after discounts (because of a coupon or mix and match groups)


upsell

boolean

True if this item was added to the cart as part of an upsell


variations

Associative Array (Hash)

key=string, value=string

A hashmap of variations. This is only populated when passing a CartItem to addItems or updateItems. It is never populated on cart.items. See discussion below.

Added Oct 2011, available to versions 2.0.9+

weight

Weight

Weight of the item


width

Distance

Width of the item


A note about variations. The variations property above is not an array of ItemVariations. It is a simple hash map of name=value for each variation. It is only populated by the client and passed to addItems or updateItems (legacy) or when the cart is passed to the REST POST to /rest/cart. Here's why: When a item is passed in with variations(s), ultracart uses the variations to look up the child item, and that item id is used in place of the provided item id. For example, in the online variations example, The item 'SHIRT' is passed in with variations (Size=Large,Color=Black). The actual item added to the cart is 'SHIRT_BLACK_LARGE'. That item doesn't have any variations attached to it, only it's parent item. So if I example the cart.items array and look at the newly added object, item.variations will be empty.

For the rest, a new item with variations will look like this (h/t to russel at augimo):

cart.items.push({itemId:'example',quantity:1,variations:{color:'Blue',flavor:'Vanilla'}});


The reason why a simple hash map is used instead of a list of ItemVariation objects is because a CartItem contains choices made, while an Item object contains available choices. The former represents a selected product, the latter is made for product displays.

CartItemOption

This object represents an option on one of the items in the shopping cart.  See item configuration for details on managing items.

Local currency fields are only available to the REST API.

Field

Type

Description

Required when adding an item to cart

name

string

Option name

YES

selectedValue

string

Seleted value on the option

YES

 

costPerLetter

costPerLetterLocalized

costPerLetterLocalizedFormatted

number

number

string

Fee per letter specified in a single or multiline option

NO

costPerLine

costPerLineLocalized

costPerLineLocalizedFormatted

number

Fee per line of text specified in a multiline option

NO

costIfSpecified

costIfSpecifiedLocalized

costIfSpecifiedLocalizedFormatted

number

Fee if specified

NO

ignoreIfDefault

boolean

True if option will be ignored on the order if the default value is selected

NO

label

label

Option display label

NO

oneTimeFee

boolean

True if the fee is only applied once (irregardless of quantity)

NO

optionOid

integer

A unique option object identifier. This is provided to easy debugging with UltraCart premium support.

NO

required

boolean

True if required

NO

type

string

Type of option. See OPTION_TYPE_ constants in the checkoutapi.js for a list of valid values.

NO

values

CartItemOptionValue[ ]

Values that the customer can select from for radio or drop down style options

NO

 

Short Example of creating a CartItem with options:

      // create my cart item.  just the bare required properties: itemId, quantity.
      // see: http://docs.ultracart.com/display/ucdoc/CartItem
      var item = {'itemId': myItem.itemId, 'quantity': 1};
      item.options = []; // create the (initially empty) options placeholder.
      var opt = {'name': 'Option1', 'selectedValue': 'Large'};
      item.options.push(opt);
      opt = {'name': 'Option2', 'selectedValue': 'Skittles'};
      item.options.push(opt);
      // add items takes an array.  I've only got one item, so I'll surround it by brackets to create a single element array.
      ultraCart.addItems([item]);

Full example of downloading an item from the server, creating select boxes for it, and then adding an item with options to a cart:
(You may download this example as a zip file. See this page's attachments.)

Item Options Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script type='text/javascript' src='js/jquery-1.7.2.js'></script>
  <script type='text/javascript' src='js/jquery.json-2.2.min.js'></script>
  <script type='text/javascript' src='js/checkoutapi-2.1.2.js'></script>

  <style type='text/css'>
    #log{
      font-family: Courier, Serif;
      font-size: 0.7em;
    }
  </style>

  <script type='text/javascript'>

    if (typeof String.prototype.trim === 'undefined') {
      String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
      };
    }

    var myItem = null; // this will hold a reference to my item after it is loaded.

    var merchantCartConfig =
    {
      merchantId: "DEMO",
      isCheckoutPage: false,
      checkoutSite: 'secure.ultracart.com',
      // remoteApiUrl: 'http://staging.moraicecream.com/wp-content/themes/minimatica/ultracart-scripts/' + 'proxy.php',
      remoteApiUrl: location.protocol + "//" + location.hostname + "/proxy.php",
      debugMode: true,
      verboseAjax: true
    };

    jQuery(document).ready(function() {
      ultraCart.init(merchantCartConfig);

      loadShirtOptions();

//      ultraCart.clearItems();
//      var Options = [
//        {name: "Michael Flavor", label: "Michael Label"},
//        {name:
//            "Michael Flavor", label: "Michael Label"},
//        {name: "Michael Flavor", label:
//            "Michael Label"},
//        {name: "Michael Flavor", label: "Michael Label"}
//      ];
//      var itemToAdd = {itemId: '001', quantity: 1, options:Options};
//      var errors = ultraCart.addItems([itemToAdd]);
//      console.log(errors);
//      var cart = ultraCart.getCart();
//      console.log(jQuery.toJSON(cart.items));

    });


    function sortOptionValues(a, b) {
      // I'm sorting option values on their displayOrder property.
      // see: http://docs.ultracart.com/display/ucdoc/ItemOptionValue
      return (a.displayOrder - b.displayOrder);
    }


    function loadShirtOptions() {
      var shirt = ultraCart.getItem('TSHIRT', {async:true,onComplete:function(result) {

            // when the shirt item returns, load up some options with it.
            if (result) {
              myItem = result;
              log('Loading options for item [' + result.itemId + ']');

              // see: http://docs.ultracart.com/display/ucdoc/Item
              var shirtOptions = result.options;
              if (shirtOptions && shirtOptions.length) {

                // loop through each option and create a row in the table containing a drop down box with options
                var html = '';
                for (var i = 0; i < shirtOptions.length; i++) {
                  // see: http://docs.ultracart.com/display/ucdoc/ItemOption
                  var opt = shirtOptions[i];
                  log("&nbsp;&nbsp;&nbsp;Loading item option: [" + opt.name + "], label: [" + opt.label + "]");

                  html += '<tr><td>' + opt.label + '<\/td>';
                  html += '<td><select class="item_option" name="' + opt.name + '">';

                  opt.values.sort(sortOptionValues);
                  for (var j = 0; j < opt.values.length; j++) {
                    // see: http://docs.ultracart.com/display/ucdoc/ItemOptionValue
                    var val = opt.values[j];
                    log("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Loading option value: [" + val.value + "], is default: [" + val.defaultValue + "]");
                    html += '<option value="' + val.value + '"' + (val.defaultValue ? " selected='selected'" : "") + '>' + val.value + '<\/option>';
                  }

                  html += "<\/select>";
                  html += '<\/td><\/tr>';

                } // end of for-each-option-loop

                jQuery('#options_table').html(html);

              } // end of if-result-has-options
            } // end of if-result-is-value
          } // end of onComplete
          } // end of opts hash
      );
    }

    function addShirt() {

      // Pay Attention Here!  We're adding to the cart.
      // The cart item objects are different from regular items.  The regular items are concerned about displaying
      // information.  The cart item objects are concerned about maintain cart state.
      // So we've switched from Item => CartItem.
      // ItemOption => CartItemOption


      // create my cart item.  just the bare required properties: itemId, quantity.
      // see: http://docs.ultracart.com/display/ucdoc/CartItem
      var item = {'itemId': myItem.itemId, 'quantity': 1};
      item.options = []; // create the (initially empty) options placeholder.

      // get all the options and add the selected values to my item.
      // each select field has a class of 'item_option'.  Use that to find them all.
      jQuery('.item_option').each(function(idx, el){

        // the *only* things we care about with the items are the name and the selected value.
        // the server doesn't care about the label, etc.
        // step 1. get the name of the element.
        // step 2. get the selected value (jQuery makes this easy)
        // add the item to the array.
        var $el = jQuery(el); // wrap the element in a jQuery object for easy value retrieval.

        // see: http://docs.ultracart.com/display/ucdoc/CartItemOption
        var opt = {'name': el.name, 'selectedValue': $el.val()};
        item.options.push(opt);
      });

      // add items takes an array.  I've only got one item, so I'll surround it by brackets to create a single element array.
      ultraCart.addItems([item]);

      log("Item was added to the cart.");
      log("run this in your browser console: ultraCart.getCart().items");
    }

    function log(msg) {
      jQuery('#log').append(msg).append("<br />");
    }

  </script>
</head>
<body>

<h4>Add a T-SHIRT to Your Cart</h4>
<table id='options_table'>
  <tr>
    <td colspan='2'><em>loading options...please wait.</em></td>
  </tr>
</table>
<br />
<input type='button' value='Add Shirt' onclick='addShirt()'/>

<div id='log' style='margin-top:20px;'>
  <div style='font-weight:bold'>Log Events Will Appear Below:</div>
</div>


</body>
</html>

CartItemMultimedia

This object represents a multimedia file that is configured on an item.

Field

Type

Description

code

string

Code

description

string

Description

excludeFromGallery

boolean

True if the file should be excluded from gallery displays

imageHeight

integer

Height if this is an image.

imageWidth

integer

Width if this is an image.

isDefault

boolean

True if this is the default multimedia object for it's type. Please note there can be a default image, default video, default PDF file, etc. all on the same item.

thumbnails

CartItemMultimediaThumbnail[ ]

Thumbnails available for this image.

type

string

Type of multimedia file. See the ITEM_MULTIMEDIA_TYPE_ constants in the checkoutapi.js file for a list of valid values.

viewUrl

string

URL to view the multimedia file.

CartKitComponentOption

This object represents an option on one of the kit components of a kit item in the shopping cart.

Field

Type

Description

name

string

Option name

selectedValue

string

Seleted value on the option

 

costIfSpecified

number

Fee if specified

costPerLetter

number

Fee per letter specified in a single or multiline option

costPerLine

number

Fee per line of text specified in a multiline option

ignoreIfDefault

boolean

True if option will be ignored on the order if the default value is selected

itemId

string

Item id of the kit component item that this option belongs to.

itemOid

integer

Item oid of the kit component item that this option belongs to. This is an internal field that you'll probably never have need to use.

label

string

Option display label

optionOid

integer

A unique option object identifier. This is provided to easy debugging with UltraCart premium support.

oneTimeFee

boolean

True if the fee is only applied once (irregardless of quantity)

required

boolean

True if required

type

string

Type of option. See OPTION_TYPE_ constants in the checkoutapi.js for a list of valid values.

values

CartItemOptionValue[ ]

Values that the customer can select from for radio or drop down style options

CheckoutTerms

This object is returned from the getCheckoutTerms method.

Field

Type

Description

text

string

The text of the checkout terms

html

boolean

True if the text is HTML, otherwise it's plain text that should be formatted accordingly.

CheckoutRequest

This is the object submitted to the REST API when the cart is done and ready to be turned into an order.

FieldTypeDescription
cartCartThe cart object
errorParameterNamestring

The name of the http query parameter that should be used to denote errors. There are two places for errors. During the API call, and after the page has changed. This name is used for the latter. Once the location has handed off to the Background Processor for credit card validations, the user is shown the "Please Wait" screen. If there are errors at this point, the customer is redirected to an error page (denoted by errorReturnToUrl). The error page is typically the checkout page, and the page contains code to look for any errors in the url and display them appropriately.

errorReturnToUrlstringThe page that is called when there are second-stage errors with the checkout.
secureHostNamestring

If the site is not running under secure.ultracart.com, this is the server name. While it might seem like this is something that UltraCart could figure out based on the Merchant ID, some merchants have dozens of sites with feeds coming from numerous locations. This string defines the server name explicitly. It may be null.

Requirements:

Any host name passed in via secure host name must be a registered host name with your account. This means you'll need to have the host name registered and a valid SSL certificate on file with UltraCart for that host name to be accepted. If the host name doesn't exist on your account, your default host name will be used. We make this requirement to avoid security issues that might arise from accepting any host name provided.

What secureHostName does:

Passing in a secureHostName will affect the checkout handoff url. It be will used like this: "https://" + secureHostName + "/cgi-bin/UCCheckoutHandoff? The handoff is the portion of the checkout experience where UltraCart takes over and handles things like shipping estimate timeouts, long payment gateway transaction times, retries, etc.

What secureHostName does not:

The secure host name does NOT affect the receipt page. The receipt page is handled by the screen branding theme. It's like that for many legacy reasons, so you'll just need to manage the receipt page separately. If you need a custom receipt page served with a different host name, configure it in your screen branding section set the cart.screenBrandingThemeCode to the screen branding code.

For reference, see:

Screen Branding Themes and Custom Thank You Page URL

payPalBillMeLaterbooleanset this to true if you wish to use PayPal Bill Me Later. The cart.paymentMethod must be equal to "PayPal" for the server to even look at this flag.
payPalMaximumUpsellRevenuedecimal

If you are implementing a custom upsell gauntlet and the payment method is PayPal, you need to specify the maximum amount of upsell revenue possible.

Added January 2014

payPalReturnUrlstring

This is the full url of your first custom upsell page. Need the info below for details.

Only set this value if you are doing a custom upsell from a third party javascript checkout. If you are not doing a custom upsell, do NOT set this. And do NOT ever set this value to your 'thank you' page. This is not a thank you page. It is an upsell page and you must then call /cart/checkout again when finished with your upsell guantlet.

Custom thank you pages are managed above by the secureHostName variable. The secureHostName variable should point to your StoreFront. And within your StoreFront you must specify a custom thank you page on the Conversion Tracking page.


Added January 2014

forceFinalizeOrderboolean

Scope: PayPal checkout with custom upsell gauntlet.

This flag needs to be set to true during the second call to checkout after a custom upsell using PayPal. That's the only time it needs to be set. When set, it avoids sending the customer to the PayPal authentication screen again.

  1. 1st call of /rest/cart/checkout
  2. Redirects to PayPal.com
  3. Customer completes process a PayPal
  4. Redirects back to UltraCart
  5. Redirects customer to the custom return URL
  6. Customer completes a custom upsell gauntlet
  7. 2nd call of /rest/cart/checkout  (important that they set checkoutRequest.forceFinalizeOrder = true) for the call

Using PayPal with a custom upsell gauntlet:

When a checkout has upsells configured, and a PayPal payment method is chosen, the maximum amount of the upsell guantlet is used when authorizing funds. By doing this, the checkout is able to offer upsells and capture funds without having the customer login to PayPal again. Some merchants have need to implement their own upsell gauntlet. To provide a custom gauntlet and accept PayPal, you will need to supply two additional fields in your CheckoutRequest object.

  1. payPalMaximumUpsellRevenue - the maximum upsell gauntlet $$. This should NOT include the current cart total.
  2. payPalReturnUrl - this is the first page of your custom upsell gauntlet.  

Your guantlet pages are responsible for loading up the cart again, displaying offers, adding them to the cart, and then doing another "checkout" call at the end of the guantlet. This will again submit the cart to the UltraCart checkout service, finalize the order, and present the customer with a receipt.


Only set this value if you are doing a custom upsell from a third party javascript checkout. If you are not doing a custom upsell, do NOT set this. And do NOT ever set this value to your 'thank you' page. This is not a thank you page. It is an upsell page and you must then call /cart/checkout again when finished with your upsell guantlet.

Custom thank you pages are managed above by the secureHostName variable. The secureHostName variable should point to your StoreFront. And within your StoreFront you must specify a custom thank you page on the Conversion Tracking page.





CheckoutResponse

This is the object returned from the REST API when the cart is submitted to be an order.

FieldTypeDescription
cartCartThe cart object. It is usually updated during the checkout, so be sure to update your local copy with this one when it returns if there were errors.
redirectToUrlstringIf errors is empty or zero length, use this value to do a location.href = response.redirectToUrl
errorsstring[ ]any errors should be displayed to the user, giving them a chance to fix any problems before checking out again.


CityStateZip

This object contains the result a zip to city/state inquiry.

Field

Type

Description

city

string

City

state

string

State (two letter abbreviation)

validZip

boolean

True if the zip was translated successfully into a city and state. False otherwise.

zip

string

Zip Code, either 5 digit or zip+4. Examples: 30041, 30041-7436

 

See Also:
getCityState - Checkout API Method

Availability:

Version

Comment

1.1

Available

1.2

Available

2.0

Available

CustomerProfile

This object represents a customer profile.

Field

Type

Description

address1

string

Address line 1

address2

string

Address line 2

allow3rdPartyBilling

boolean

True if the customer is allowed to bill the shipping to their 3rd party account number.

allowCod

boolean

True if the customer is allowed to use a COD

allowPurchaseOrder

boolean

True if the customer is allowed to use a purchase order

autoApproveCod

boolean

True if the COD will automatically be approved

autoApprovePurchaseOrder

boolean

True if the purchase order will automaticall be approved

billingAddresses

CustomerProfileAddress [ ]

Addresses in this customer's billing address book

city

string

City

creditCardsCustomerProfileCreditCard [ ]

An array of credit cards belonging to the customer.

Only available in version 3+ (REST based) javascript checkout.

company

string

Company

country

string

Country

customerProfileOid

integer

The customer profile object id. This is provided to make debugging easier by UltraCart premium support.

dayPhone

string

Day phone

dhlAccountNumber

string

3rd party account number to bill the DHL shipping to

email

string

Email address associated with the customer profile

eveningPhone

string

Evening phone

exemptShippingHandlingCharge

boolean

True if the customer is exempt from shipping and handling charges

fax

string

Fax

fedexAccountNumber

string

3rd party account number to bill the FedEx shipping to

firstName

string

First name

freeShipping

boolean

True if the customer receives free shipping

freeShippingMinimum

number

Amount required to qualify for free shipping. Value will be null if there is no threshold specified

lastName

string

Last Name

minimumItemCount

integer

Minimum item count the customer is required to purchase. Wil be null if no threshold is specified.

minimumSubtotal

number

Minimum subtotal the customer is required to purchase. Will be null if no threshold is specified

noCoupons

boolean

True if the customer is not allowed to use coupons

noFreeShipping

boolean

True if the customer is prevented from standard retail customer free shipping

noRealtimeCharge

boolean

True if the customer credit card will not be charged real-time during the checkout process.

password

string

New password for the customer profile. Can only be set before a call to updateCustomerProfile.

postalCode

string

Postal Codew

pricingTiers

string [ ]

Array of all the pricing tiers this customer has been granted

shippingAddresses

CustomerProfileAddress [ ]

Addresses in this customer's shipping address book

taxExempt

boolean

True if the customer is tax exempt

taxId

string

Tax ID

title

string

Title

upsAccountNumber

string

3rd party account number to bill the UPS shipping to

CustomerProfileAddress

This object represents an address in the customer profile's address book.

Field

Type

Description

address1

string

Address line 1

address2

string

Address line 2

city

string

City

company

string

Company

country

string

Country

dayPhone

string

Day Phone

eveningPhone

string

Evening phone

fax

string

Fax

firstName

string

First name

lastName

string

Last name

postalCode

string

Postal code

state

string

State

taxCounty

string

Tax county

title

string

Title

CustomerProfileCreditCard

This object represents a credit card in the customer profile's stored credit cards.

This object is only available in version 3+ of the javascript checkout. Version 3 is the REST based checkout.

Field

Type

Description

merchantId

StringMerchant ID

 

customerProfileId

integer

Unique identifier for the customer who owns this card

id

integer

Unique identifier for this card.

THIS IS IT! This is the value you want to put into cart.customerProfileCreditCardId in order to use a stored credit card during a purchase.

Typically, the credit cards are gathers from cart.customerProfile.creditCards and iterated into a select box. This id is then the option value.

cardType

String

VISA, MasterCard, etc.

cardExpMonth

integer

Expiration Month (1-12)

cardExpYear

integer

Expiration Year

cardNumber

String

This will always be masked except for the last four numbers.

lastUsedDate

String

ISO8601 formatted date string of the last time the card was used.

lastUsedDateFormatted

String

Pretty formatted (long) string of the last time the card was used. Very handy for using in javascript templates.

FinalizeOrderRequest

This is the object submitted to the REST API when the cart is done and ready to be turned into an order.   This is different from /rest/cart/checkout.  checkout is the beginning of a handoff to the order processing screens.  It is the call that should be used ALWAYS when creating a javascript checkout.   This object exists for server side applications such as call centers that are not running in a client browser to use when calling /cart/rest/finalizeOrder.



 NEVER USE THIS OBJECT IN A CLIENT BROWSER.  This object requires a back end login (username/password). It is never safe to supply that to a client browser.


FieldTypeDescription
cartCartThe cart object
credentialsCredentials

Credentials has three fields:

  1. merchantId
  2. login
  3. password

The merchant id is your 3-5 character merchant id.

The login and password are valid username/password credentials for access secure.ultracart.com.

DO NOT USE A NORMAL LOGIN FOR THIS, AND NEVER EVER USE THE OWNER LOGIN FOR THIS CALL.

  1. Create a new user.
  2. Remove all permissions for the user except API Access.
  3. In the Edit User screen, when you click "API Access", enter the IP addresses that your server will be running on to further prevent misuse.
optionsFinalizeOrderOptionsoptional hash of processing options. See FinalizeOrderOptions for specifics.



FinalizeOrderResult

This object is the return value for a successful call to /rest/cart/finalizeOrder. 


FieldTypeDescription
successfulbooleantrue if the order was created, else false
orderIdstring

The order id of the newly created order

receiptTextFinalizeOrderOptionsThe preformatted plain text order receipt. It's not very pretty. It's recommended you display it in a fixed screen like a <pre> tag, etc.
errorMessagesstring Arraya list of errors that might have occurred
orderOrderADDED Aug-2013: a json object representing the order. useful for extracting fields without have to parse receiptText.
nextCartCartADDED Mar-12-2015 A new cart object with the customer already logged in. This will be null unless the FinalizeOrderOptions.setupNextCart is true and the customer was successfully logged in for the order being currently finalized.

FinalizeOrderOptions

FieldTypeDescription
noRealtimePaymentProcessingbooleanif true, validates the credit card information, but does not authorize or capture funds at the time of order.
skipPaymentProcessingbooleanif true, skips payment processing and places the order in Accounts Receivable
autoApprovePurchaseOrderbooleanautomatically approves any PO provided
storeIfPaymentDeclinesbooleanif true, the order is placed in Accounts Receivable if payment declines. If false, an error is returned and the order is not completed.
creditCardAuthorizationReferenceNumberstringIf the credit card was already authorized in a different system, the next three fields provide all the information needed to capture funds
creditCardAuthorizationAmountnumberthe amount the card was authorized for
creditCardAuthorizationDatestring

ISO8601 format string

20130603T170226-0400
year 2013

month 06

day 03

 "T"

hour 17 (5 pm)

minute 02

second 26

TZ -0400 (EST with daylight savings)

channelPartnerOidnumberIf this order is originating with a specific call center, enter its UltraCart identifier here to correlate the order in the UltraCart system
channelPartnerOrderIdstringThe external channel partner order id
setupNextCartboolean

If true, AND IF the customer is logged in, a new cart is created with the customer already logged in. This was created so that a logged in customer could place an order and then be redirected to the MyAccount pages seamlessly. The next cart will be part of the FinalizeOrderResult.

(Added March 12, 2015)

storeCompletedbooleanIf true, the order skips Accounts Receivable and the Shipping Department and is marked Completed.



Distance

An object that represents distance in a specific unti of measure.

Field

Type

Description

uom

string

The unit of measure. This is a string constant.

Inches = IN

centimeters = CM

value

number

The value of the distance in the specified unit of measure.

 

 


Gift Settings

All the settings about gift giving that are available during the checkout to the customer.

Field

Type

Description

allowGifts

boolean

True if the customer is allowed to give a gift

giftCharge

number

Charge for sending the order as a gift

maxMessageLength

integer

Maximum length of the gift message

giftWraps

GiftWrap[ ]

Wrapping papers that are available to the customer


Gift Wrap

Represents a gift wrap that is available for the customer to select

Field

Type

Description

Comment
baseCurrencyCodestringThe default currency code of the merchant. 

cost

costLocalized

costLocalizedFormatted

number

number

string

Cost to the customer if they select this gift wrap

local currency fields only avaiable to REST API.
currencyCodestringThe current currency code of the shopping cart. 

title

string

Title of the gift wrap

 

url

string

URL to the image of the gift wrap

 

Item

This object represents an item. This is a different object than the CartItem which represents the item after it's been added to the cart.

Why two items? Item and CartItem are mostly the same, but CartItem contains pricing information relative to the cart. For example, coupons added to the cart could affect the price of an item, etc. So you want to an Item object to display an item on a product page or list, and use the CartItem when displaying an item contained in a cart. This shouldn't be a real issue, as the CartItem objects are only found with the items array property of the Cart itself.

Also, please note that Item and CartItem have different 'variations' properties. See CartItem for a discussion why.

Field

Field Type

Description

Comments

itemId

string

Item ID

 

 

allowBackorder

boolean

True if this item can be back ordered

 

attributes

ItemAttribute[ ]

Array of Attributes on the item

 

autoOrderablebooleanTrue if the item can be auto ordered, false otherwise, see schedules property for the auto order schedules if this is trueAdded June 2015, available to REST API only.

availableQuantity

integer

The quantity of this item in stock and available for immediate shipment

 

baseCurrencyCodestringThe default currency code of the merchant. 

cost

costLocalized

costLocalizedFormatted

number

number

string

Cost

 local currency fields are only availabe in REST API.

currencyCodestringThe currency code of the current shopping cart. 
defaultImageSslstringThe full url for the item's default image using SSL protocol (will likely be // instead of https://)Added Jan 2014, available to REST API only.

defaultImageUrl

string

The full url for the item's default image.

Added June 2011, available to versions 1.1+

defaultThumbnailSslstring

The full url for the item's default thumbnail using SSL protocol (will likely be // instead of https://)

the thumbnail urls are relative. please prepend //secure.ultracart.com/thumbs/ to the front of the relative url.

Really, I (Perry) don't know why they're relative. They've been around for a decade and we can't change them or we break decade old shopping carts...

Added Jan 2014, available to REST API only.

defaultThumbnailUrl

string

The full url for the item's default thumbnail.

the thumbnail urls are relative. please prepend //secure.ultracart.com/thumbs/ to the front of the relative url.

Added June 2011, available to versions 1.1+

description

string

Description

 

extendedDescription

string

Extended description

 

height

Distance 

Height

 

inactivebooleantrue if the item is inactiveAdded Dec 2013, available to REST API only.

inStock

boolean

True if this item is instock

 

inventoryTracked

boolean

True if this item is tracking inventory levels

 

itemOid

integer

Unique item object identifier. Provided to make debugging easier by UltraCart premium support. You probably won't ever use this in a meaningful way.

 

length

Distance

Length

 

manufacturerSuggestedRetailPrice

manufacturerSuggestedRetailPriceLocalized

manufacturerSuggestedRetailPriceLocalizedFormatted

number

number

string

The MSRP of the item.

  local currency fields are only availabe in REST API .

maximumQuantiy

number

The maximum quantity the customer can purchase.

 

minimumQuantity

number

The minimum quantity the customer must purchase.

 

multimedias

ItemMultimedia[ ]

Array of Multimedia on the item

 

options

ItemOption[ ]

The options that are available on this item.

 

preorder

boolean

True if this item is on pre-order

 

schedulesString[]If autoOrderable is true, this will contain an array of the different re-ship frequencies.Added June 2015, available to REST API only.

variations

ItemVariation[ ]

Array of Variations on the item

Added June 2011, available to versions 2.0.9+

weight

Weight

Weight

 

width

Distance 

Width

 

ItemAttribute

An object representing an attribute configured on the item.

Field

Type

Description

name

string

Name of the attribute

type

string

Type of the attribute

value

string

Value of the attribute

ItemMultimedia

This object represents a multimedia file that is configured on an item.

Field

Type

Description

code

code

The code is used mostly by the product categories. Images can be retrieved by code. For example, a line of t-shirts may have a "back side" image. Each item could have that image with the code "backside". The catalog page could then display the back side image in a smaller image next to the front of the image by simply requesting the image with the code 'backside' instead of having to know the name of the image or require a fixed image name.

description

description

Description

excludeFromGallery

boolean

True if the file should be excluded from gallery displays

imageHeight

integer

Height if this is an image.

imageWidth

integer

Width if this is an image.

isDefault

boolean

True if this is the default multimedia object for it's type. Please note there can be a default image, default video, default PDF file, etc. all on the same item.

viewSslstring

URL to view the multimedia file using SSL. Note: This url will probably be prefixed with // instead of https:// so that it will use the same protocol of the page. So, it is actually appropriate to use for both secure and non-secure pages and still provide a fast browsing experience.

Note: Only available in Checkout REST Api

viewUrl

string

URL to view the multimedia file.

thumbnails

ItemMultimediaThumbnail [ ]

Array of Thumbnails available for this image.

type

string

Type of multimedia file. See the ITEM_MULTIMEDIA_TYPE_ constants in the checkoutapi.js file for a list of valid values.

ItemMultimediaThumbnail

This object represents a thumbnail of a multimedia image.

Field

Type

Description

height

integer

Height of the thumbnail in pixels

httpsUrl

string

Secure URL to view the thumbnail

httpUrl

string

URL to view the thumbnail

width

integer

Width of the thumbnail in pixels

ItemOption

This object represents an option on an item.  See item configuration for details about options.

Local currency fields are only available to the REST API.

Field

Type

Description

name

string

Option name

selectedValue

string

Seleted value on the option

 

costIfSpecified

costIfSpecifiedLocalized

costIfSpecifiedLocalizedFormatted

number

number

string

Fee if specified

costPerLetter

costPerLetterLocalized

costPerLetterLocalizedFormatted

number

number

string

Fee per letter specified in a single or multiline option

costPerLine

costPerLineLocalized

costPerLineLocalizedFormatted

number

number

string

Fee per line of text specified in a multiline option

ignoreIfDefault

boolean

True if option will be ignored on the order if the default value is selected

optionOid

integer

A unique option object identifier. This is provided to easy debugging with UltraCart premium support.

oneTimeFee

boolean

True if the fee is only applied once (irregardless of quantity)

label

string

Option display label

required

boolean

True if required

type

string

Type of option. See OPTION_TYPE_ constants in the checkoutapi.js for a list of valid values.

values

ItemOptionValue[ ]

Values that the customer can select from for radio or drop down style options

ItemOptionValue

This object represents an option value on one of the items in the shopping cart.  Option values are usually used to provide a dropdown list of choices for the customer to select when choosing item options.  See item configuration for instruction on setting up item options.

Local currency fields are only available in the REST API.

Field

Type

Description

value

string

Value of the option

 
baseCurrencyCodestringThe default currency of the merchant.

additionalCost

additionalCostLocalized

additionalCostLocalizedFormatted

number

Additional cost the customer will pay if they select this option

additionalWeight

Weight

Additioanl weight included in the order if they select this option

currencyCodestringThe current currency of the shopping cart.

defaultValue

boolean

True if this option value should be the default

displayOrder

integer

Order in quick the options should be displayed. Lower display orders should come first.

Order

The Order is returned as part of FinalizeOrderResult.

Every money field below is a number value. The number field has a corresponding string field with the suffix of 'Formatted'. These formatted fields contain the currency sign and decimal places. You should use the formatted fields wherever possible. Doing currency conversions of past orders is extremely complicated.

FieldTypeComment
labelshashthis hash contains all the labels for the various fields below. This hash is powerful because it contains the mappings you specify in the back end "screen branding' section. See the order labels section for individual listings.
merchantIdstringyour merchant id
customerProfileIdintcustomer's internal identifier
orderIdstringorder id
rejectedbooleantrue if the order was rejected
themeCodestringthe theme code applied to this order. See screen branding. This code is often used when creating buy links to apply the proper look and feel to an order page. Some merchants only have one theme. Some merchants have 50.
creationDatestringISO-8601 format. When the order was created
creationDateFormattedstringDD-MMM-YYYY format. When the order was created
shipOnDatestringISO-8601 format. When the order was requested to ship on.
shipOnDateFormattedstringDD-MMM-YYYY format. When the order was requested to ship on.
saturdayDeliverybooleantrue if the order is set for Saturday delivery
rejectedDatestringISO-8601 format. When the order was rejected (null if it hasn't been)
rejectedDateFormattedstringDD-MMM-YYYY format of when the order was rejected, if it was.
quoteExpirationDatestringISO-8601 format. If this order is a quote, when the quote expires.
quoteExpirationDateFormattedstringDD-MMM-YYYY format. If this order is a quote, when the quote expires.
statusstringCompleted, Rejected, Quote Sent, Quote Requested, Pre-Order Item, Pending
testOrderbooleantrue if this order was a test
shippingMethodstring a bare bones description of the shipping method
shippingMethodNamestring a friendly version of the shipping method. This should be preferred for display over shippingMethod
shippingMethodDetailedstringan elaborate string contain shippingMethodName and any features such as lift gates and ship to residential,  
shippingMethodCompanystringUPS, FedEx, etc. 
shipping3rdPartyAccountNumberstring
emailstring
ccEmailsstring[ ]an array of email addresses who were cc'd on the order.  
giftEmailstringthe gift recipient's email address 
billToCompanystring
billToTitlestring
billToFirstNamestring
billToLastNamestring
billToAddress1string
billToAddress2string
billToCitystring
billToStatestring
billToPostalCodestring
billToCountrystring
billToDayPhonestring
billToEveningPhonestring
shipToCompanystring
shipToTitlestring
shipToFirstNamestring
shipToLastNamestring
shipToAddress1string
shipToAddress2string
shipToCitystring
shipToStatestring
shipToPostalCodestring
shipToCountrystring
shipToDayPhonestring
shipToEveningPhonestring
giftbooleantrue if the order is a gift
liftGatebooleantrue if the order requires a lift gate to deliver.
shipToResidentialbooleantrue if the delivery is a residence
hidePaymentInformationbooleanwhether or not to show payment information. Imagine the scenario where the cost is zero and/or gift certificates were used.
refundPresentbooleanduplicate of hasRefund. Use hasRefund, as this field is deprecated and will be removed without warning.
taxShippingbooleanis shipping taxed? this affects the display of subtotal information (tax before subtotal or subtotal before tax).
taxCountystring
referralCodestring
advertisingSourcestring
paymentMethodstring

Credit Card, PayPal Order, etc.

Supported payment methods as of 6/2013 (list may change):

Check
Credit Card
Credit Card Fax In
PayPal
eCheck
Purchase Order
Unknown
Money Order
Wire Transfer
COD
CASH
SafetyPay
Amazon SC
SkyMall
Smart Bargains
Quote Request

paymentNotestringA friendly working of the paymentMethod. For display purposes, use this value instead of paymentMethod. It will always read the same or better.
cardTypestringThe type of credit card used. VISA, MasterCard, etc.
cardNumberstringmasked. last four digits.
couponsCouponThe coupon class contains two simple fields: code and description
itemsItem[ ]The items for this order
giftWrapTitlestringthe name of the gift wrap
giftWrapCost / giftWrapCostFormattednumber / string
hasDiscountbooleantrue if a discount was made somewhere (often useful for adding an extra table column, etc.)
hasRefundbooleantrue if a refund was made somewhere (often useful for adding an extra table column, etc.)
subtotalBeforeDiscount / subtotalBeforeDiscountFormattednumber / string
discount / discountFormattednumber / string
subtotal / subtotalFormattednumber / stringsubtotal with any discounts and refunds already applied
subtotalRefunded / subtotalRefundedFormattednumber / string
taxRate / taxRateFormattednumber / string
shippingHandlingDiscount / shippingHandlingDiscountFormattednumber / string
shippingHandlingTotal / shippingHandlingTotalFormattednumber / stringtotal with any discounts and refunds already applied.
shippingHandlingRefunded / shippingHandlingRefundedFormattednumber / string
tax / taxFormattednumber / stringtax with any refund already applied
taxRefunded / taxRefundedFormattednumber / string
giftCharge / giftChargeFormattednumber / string
surcharge / surchargeFormattednumber / string
showInsureShipboolean

true if this order used InsureShip and the amounts should be shown.

InsureShip is no longer available. This would only apply to old legacy orders. It's doubtful you need to consider this field.

insureShipCost / insureShipCostFormattednumber / stringinsure ship cost
insureShipRefunded / insureShipRefundedFormattednumber / stringvalue of any insure ship refunded
total / totalFormattednumber / stringgrand total
totalRefunded / totalRefundedFormattednumber / stringof the total, this amount was refunded
showCurrencyWarningbooleantrue if the currency warning (next line) should be shown.
currencyWarningstringthis is the standard currency warning if the order was placed in a different currnency. It contains a nicely formatted message to show to the customer.
giftCertificateCodestringthe gift certificate code. If the gift certificate was a credit card type, the code will be masked.
giftCertificateAmount / giftCertificateAmountFormattednumber / stringthe amount used of the gift certificate
giftMessagestring[ ]

array of gift message lines

when this field was entered, newlines were captured to preserve the look. so this field is an array of strings broken by newlines. You may join them or iterate them as desired.

specialInstructionsstring[ ]

array of special instructions text

when this field was entered, newlines were captured to preserve the look. so this field is an array of strings broken by newlines. You may join them or iterate them as desired.

commentsstring[ ]

array of comments

when this field was entered, newlines were captured to preserve the look. so this field is an array of strings broken by newlines. You may join them or iterate them as desired.

trackingNumbersstring[ ]array of tracking numbers
orderCaseCaseSee the case object above. If there is a case (customer feedback) associated with this order, it will be populated in this value.

Order Labels

The order labels are formatted labels for use when displaying an order.  They should be used whenever possible.

The default value is what is used if you have not configured anything custom in your Checkout Text section of the Configuration area.

Hash KeyDefault

quoteRequestIdField

Quote Request ID

requestDateField

Request Date

expirationDateField

Quote Expiration Date

orderIdField

Order ID

sbtField

SBT

orderDateField

Order Date

billToHeader

Bill To

shipToHeader

Ship To

jobTitleField

Job Title

titleField

Title

nameField

Name

companyField

Company

addressField

Address

cityField

City

stateField

State

zipField

Zip

countryField

Country

emailField

Email

ccEmailField

CC Email

giftEmailField

Gift Email

giftField

Gift

phoneField

Phone

eveningPhoneField

Evening Phone

taxCountyField

Tax County

shippingMethodField

Shipping Method

residential

Residential

liftGate

Lift Gate

shipOnDateField

Ship on Date

deliveryDateField

Delivery Date

shipOnAccountField

Ship on Account

advertisingSourceField

Advertising Source

wrappingPaperField

Wrapping Paper

itemHeader

Item

quantityHeader

Quantity

descriptionHeader

Description

amountHeader

Amount

refundedHeader

Refunded

subtotalBeforeDiscountsField

Subtotal before discounts

discountsField

Discounts

subtotalField

Subtotal

shippingHandlingField

Shipping/Handling

taxRateField

Tax Rate

taxField

Tax

giftChargeField

Gift Charge

surchargeField

Surcharge

giftCertificateField

Gift Certificate

totalField

Total

yourActualMessage

Your actual financial statement may vary due to actual currency conversion.

ShippingEstimate

This object represents the estimate for a shipping method on a cart.

Local currency fields are only available to the REST API.

This method is usually called in a separate ajax call from the main cart since shipping estimates are slower.

Field

Type

Description

name

string

Name of the shipping method. If this method is selected by the customer than this is the method name that should be set on the cart.shippingMethod field.

 
baseCurrencyCodestringThe base currency code for the merchant.

comment

string

Comment associated with the shipping method.

cost

costLocalized

costLocalizedFormatted

number

number

string

Cost of the shipping method

costBeforeDiscount

costBeforeDiscountLocalized

costBeforeDiscountLocalizedFormatted

number

number

string

The shipping cost before any discounts.
currencyCodestringThe currency of the shipping estimate.
defaultMethodbooleanTrue if this is the default shipping method for this cart, else false.

discount

discountLocalized

discountLocalizedFormatted

number

number

string

The shipping discount due to pricing tiers or coupons

discounted

boolean

True if this method has been discounted because of a coupon.

displayName

string

Name of this method that should be displayed to the customer.

estimatedDelivery

string

Estimated delivery time. Should be displayed beside the method if it's available.

tax

taxLocalized

taxLocalizedFormatted

number

number

string

The tax for this shipping method.

totalTax

totalTaxLocalized

totalTaxLocalizedFormatted

number

number

string

The total tax for the shopping cart if this shipping method is selected. This is a convenience value so you can update the total cart tax if a shipping method is selected.

Weight

An object that represents weight in a specific unti of measure.

Field

Type

Description

uom

string

The unit of measure.

Pounds = LB

Kilograms = KG

value

number

The value of the weight in the specified unit of measure.

Cart REST API


/rest/cart

MethodGETComments
Descriptiongets an existing cart, creating one if none is found

Cookies

UltraCartMerchantID - Merchant ID

UltraCartShoppingCartID - Cart ID


Path ParameterscartIdExample: /rest/cart/ASDBSD12415DFA12451
Query Parameters

_mid - Merchant ID

_cid - Cart ID

returnCode - "return email" return code

optional, but Merchant ID must be specified by either cookie, header, or this parameter.

one of three ways to specify a cart id

returnCode is an optional parameter. The UltraCart Auto Responder has the ability to send out "Return Emails" to abandoned carts. The return emails contain a parameter than may be parsed and submitted as this parameter. If present, it will load up a previously abandoned cart (minus credit card information).

Example: http://secure.ultracart.com/rest/cart?_mid=DEMO&returnCode=3443CE4491C11A0141561F0F541E1B01 (this won't actually load up a cart, it's just a syntax example)

Headers

X-UC-Merchant-Id - Merchant ID

X-UC-Shopping-Cart-Id - Cart ID

X-UC-Return-Code Email Campain Return Code

Merchant ID


Cart ID


The return code is a long sequence generated within the UltraCart Auto Responder. It's used to send out emails to customers with a link to an abandoned shopping cart. See UltraCart Objects available to Auto Responder Scripts for an example of how the return code is generated (see the $cart object). Although the returnCode is already available as a query parameter above, we've added it as a header to make using it with backbone.js easier.

Receives Jsonnone
Returns JsonCartIf no cart is found, one is created.

The GET method requires a Merchant ID and accepts a Cart ID.  

Notice above there are three ways to provide the Merchant ID:  Query Parameter, Header, and Cookie.   The order of precedence is  Query Parameter > Header > Cookie.

There are four ways to provide a Cart ID: Path Parameter, Query Parameter, Header, and Cookie.   The order of precedence is  Path Parameter > Query Parameter > Header > Cookie.

Examples:

function createCart() {
  jQuery.ajax({
    url: '/rest/cart',
    headers: {'X-UC-Merchant-Id': 'DEMO',
      "cache-control": "no-cache"}, // could also pass merchant id as query parameter named '_mid' or cookie named 'UltraCartMerchantID'
    dataType: 'json'
  }).done(function (cart) {
        jQuery('#createCartResults').html('<pre>' + JSON.stringify(cart, null, '  ') + '</pre>');
      });
}
 
jQuery(document).ready(function () {
  jQuery('#createCartButton').on('click', createCart);
});

MethodPOST/PUTComments
Descriptioninserts or updates a cart. technically, the PUT does an update, and the POST does an insert, but both methods are smart enough to insert if needed, else update

Cookies

none


Path ParameterscartId

Example: /rest/cart/ASDBSD12415DFA12451

The server will not regard the path parameter. It is there only to allow frameworks like backbone.js to operate correctly. The only Cart ID the server regards is the one in the Cart itself (cart.cartId)

Query Parameters

none


Headers

none


Receives JsonCart
Returns JsonCart
function updateCart() {
  // it's okay to have an empty cartId initially, but the property merchantId *must* be present and explicit.
  var cart = {
    'merchantId': 'DEMO',
    'cartId': '',
    'email': 'demo@demo.com' // pick any random field.  email will suffice for this demonstration
  };
 
  jQuery.ajax({
    url: '/rest/cart',
    type: 'PUT', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(cart),
    dataType: 'json'
  }).done(function (updatedCart) {
        jQuery('#updateCartResults').html('<pre>' + JSON.stringify(updatedCart, null, '  ') + '</pre>');
      });
}
 
jQuery(document).ready(function () {
  jQuery('#updateCartButton').on('click', updateCart);
});


/rest/cart/estimateShipping


MethodPOSTComments
Descriptionreturns shipping methodsThis call should be executed asychronously. It takes a few seconds to query the various shippers and get their rates.

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCart
Returns JsonShippingEstimate[ ]
function estimateShipping() {
  var cart = {
    'merchantId': 'DEMO',
    'cartId': '', // will be populated by call
    'items': [
      {'itemId': 'PDF', 'quantity': 1},
      {'itemId': 'Baseball', 'quantity': 2},
      {'itemId': 'BONE', 'quantity': 5}
    ]
  };
 
  jQuery.ajax({
    url: '/rest/cart',
    type: 'PUT', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(cart),
    dataType: 'json'
  }).done(function (updatedCart) {
 
        jQuery.ajax({
          url: '/rest/cart/estimateShipping',
          type: 'POST', // Notice
          headers : { "cache-control": "no-cache" },
          contentType: 'application/json; charset=UTF-8',
          data: JSON.stringify(updatedCart),
          dataType: 'json'
        }).done(function (availableShippingMethods) {
 
              var txt = JSON.stringify(availableShippingMethods, null, '  ');
              var pre = jQuery('<pre>');
              pre.text(txt);
              jQuery('#estimateShippingResults').html('').append(pre);
 
            });
      });
}
 
jQuery(document).ready(function () {
  jQuery('#estimateShippingButton').on('click', estimateShipping);
});

/rest/cart/checkout (this is NOT the last step)


MethodPOSTComments
Descriptionfinalizes an orderThis is the last method called. This is NOT the end of the checkout. The handoff is the end of the checkout. If you do not pass the browser off to the redirect url, no order will be placed.

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCheckoutRequest
Returns JsonCheckoutResponse

There are 3 main types of checkouts: 1) credit card, and 2) PayPal. The force a checkout down one of these paths, set the cart.paymentMethod property.

Credit Card: cart.paymentMethod = "Credit Card";

PayPal: cart.paymentMethod = "PayPal";

(If you wish to use PayPal Bill Me Later, you must also set a flag on the CheckoutRequest object. CheckoutRequest.payPalBillMeLater = true).

case matters, space matters. It must appear exactly as shown above.

The cart will be part of the CheckoutRequest object.

function checkout() {
  var cart = {
    'merchantId': 'DEMO',
    'cartId': '', // will be populated by call
 
    "customField1": 'blah blah blah',
    "customField2": 'perhaps an affiliate id here?',
    "coupons": [
      {couponCode: '10OFF'}
    ], // here is a coupon for $10 off the order
    "advertisingSource": "Radio",
    "screenBrandingThemeCode": "CSTM", // The demo account has a second them set up using the code CSTM
    "shippingMethod": "FedEx: 2-Day",
    "shipToFirstName": "Testy",
    "shipToLastName": "Testerson",
    "shipToTitle": "Sir",
    "shipToCompany": "Ultra Trains",
    "shipToAddress1": "55 Main Street",
    "shipToAddress2": "Suite 101",
    "shipToCity": "Duluth",
    "shipToState": "GA",
    "shipToPostalCode": "30097",
    "shipToCountry": "United States",
    "shipToPhone": "555-555-1212",
    "shipToEveningPhone": "5555553434", // notice the different format?
    "billToDayPhone": "555-555-1212",
    "billToEveningPhone": "5555551212",
    "billToFirstName": "Smith",
    "billToLastName": "Joe",
    "billToTitle": "Chief",
    "billToCompany": "Widgets, INC",
    "billToAddress1": "2000 Montana Dr",
    "billToAddress2": "",
    "billToCity": "Duluth",
    "billToState": "GA",
    "billToPostalCode": "30097",
    "billToCountry": "United States",
    "email": "test@test.com",
    "emailConfirm": "test@test.com",
    "paymentMethod": "Credit Card",
    "creditCardType": "VISA",
    "creditCardNumber": "4444333322221111",
    "creditCardExpirationMonth": 12,
    "creditCardExpirationYear": 2028,
    "creditCardVerificationNumber": "123",
    'items': [
      {'itemId': 'PDF', 'quantity': 1},
      {'itemId': 'Baseball', 'quantity': 2},
      {'itemId': 'BONE', 'quantity': 5}
    ]
  };
 
  // Notice: The checkout call does not take a cart.  It takes a CheckoutRequest which contains a cart.
  // Since the checkout process hands of to UltraCart to handle upsells, etc., we must also provide the
  // return point.
  var checkoutRequest = {
    'cart': cart,
    errorParameterName: 'error', // if there are errors after the handoff, the redirect page will receive those errors using this http parameter
    errorReturnUrl: document.URL, // this same page.
    secureHostName: null // can be null.  defaults to secure.ultracart.com if null.  could also be www.mystore.com if that was your url.
    //
 the secureHostName is where the checkout finishes on (receipt).  many 
merchants have dozens of sites.  So, if this isn't secure.ultracart and
    // you have more than one, you must specify it.
  };
 
 
  jQuery.ajax({
    url: '/rest/cart/checkout',
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(checkoutRequest),
    dataType: 'json'
  }).done(function (checkoutResult) {
 
 
        var txt = JSON.stringify(checkoutResult, null, '  ');
        var pre = jQuery('<pre>');
        pre.text(txt);
 
        var resultsDiv = jQuery('#checkoutResults');
        if (checkoutResult && checkoutResult.redirectToUrl) {
          resultsDiv.append("<div><a target='_blank' href='" + checkoutResult.redirectToUrl + " '>" + checkoutResult.redirectToUrl + "</a></div>");
        }
        resultsDiv.html('').append(pre);
      });
}
 
jQuery(document).ready(function () {
  jQuery('#checkoutButton').on('click', checkout);
});




/rest/cart/finalizeOrder


MethodPOSTComments
Descriptionfinalizes an orderThis is the last method called. It is a SERVER SIDE ONLY call. Do not use this method in a javascript application. If you're looking for a way to complete an order, see /rest/cart/checkout. This method is probably NOT what you're looking for.

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonFinalizeOrderRequest
Returns JsonFinalizeOrderResult

 NEVER USE THIS CALL IN A CLIENT BROWSER.  This call requires a back end login (username/password). It is never safe to supply that to a client browser.

This method call cannot be used with Google or PayPal because those payment methods require a handoff in a browser, which does not happen with this call.

// okay, so we've provided you with a javascript example.  that's just to be consistent with the other examples.
// here's the warning again:  DO NOT USE THIS CALL IN A REAL JAVASCRIPT APPLICATION
 
  function finalizeOrder() {
    var cart = {
      'merchantId': 'DEMO',
      'cartId': '', // will be populated by call
      "customField1": 'blah blah blah',
      "customField2": 'perhaps an affiliate id here?',
      "coupons": [
        {couponCode: '10OFF'}
      ], // here is a coupon for $10 off the order
      "advertisingSource": "Radio",
      "screenBrandingThemeCode": "CSTM", // The demo account has a second them set up using the code CSTM
      "shippingMethod": "FedEx: 2-Day",
      "shipToFirstName": "Testy",
      "shipToLastName": "Testerson",
      "shipToTitle": "Sir",
      "shipToCompany": "Ultra Trains",
      "shipToAddress1": "55 Main Street",
      "shipToAddress2": "Suite 101",
      "shipToCity": "Duluth",
      "shipToState": "GA",
      "shipToPostalCode": "30097",
      "shipToCountry": "United States",
      "shipToPhone": "555-555-1212",
      "shipToEveningPhone": "5555553434", // notice the different format?
      "billToDayPhone": "555-555-1212",
      "billToEveningPhone": "5555551212",
      "billToFirstName": "Smith",
      "billToLastName": "Joe",
      "billToTitle": "Chief",
      "billToCompany": "Widgets, INC",
      "billToAddress1": "2000 Montana Dr",
      "billToAddress2": "",
      "billToCity": "Duluth",
      "billToState": "GA",
      "billToPostalCode": "30097",
      "billToCountry": "United States",
      "email": "test@test.com",
      "emailConfirm": "test@test.com",
      "paymentMethod": "Credit Card",
      "creditCardType": "VISA",
      "creditCardNumber": "4444333322221111",
      "creditCardExpirationMonth": 12,
      "creditCardExpirationYear": 2028,
      "creditCardVerificationNumber": "123",
      'items': [
        {'itemId': 'PDF', 'quantity': 1},
        {'itemId': 'Baseball', 'quantity': 2},
        {'itemId': 'BONE', 'quantity': 5}
      ]
    };
    // Notice: The checkout call does not take a cart.  It takes a CheckoutRequest which contains a cart.
    // Since the checkout process hands of to UltraCart to handle upsells, etc., we must also provide the
    // return point.
    var finalizeOrderRequest = {
      'cart': cart,
      'credentials':{
        'merchantId':'DEMO',
        'login':'demo',
        'password':'DoNotRunInBrowser'
      },
      'options':{
        noRealtimePaymentProcessing:true, // boolean
        skipPaymentProcessing:false, // boolean
        autoApprovePurchaseOrder:true, // boolean
        storeIfPaymentDeclines:true, // boolean (store the order even if payment declines -- goes into Accounts Receivable)
        creditCardAuthorizationReferenceNumber:'1234565', // string, if CC auth was already done elsewhere
        creditCardAuthorizationAmount:45.45, // decimal/float
        creditCardAuthorizationDate: '20130603T170226-0400' // string, ISO8601 format.
        // channelPartnerOid: 54, // integer, channel partner identifier
        // channelPartnerOrderId: 'CP-12345', // string, the order id the channel partner is using.
        // storeCompleted: true // boolean, if true, the order is marked as 'completed' -- bypassing Accounts Receivable and Shipping
      }
    };

    jQuery.ajax({
      url: '/rest/cart/finalizeOrder',
      type: 'POST', // Notice
      headers : { "cache-control": "no-cache" },
      contentType: 'application/json; charset=UTF-8',
      data: JSON.stringify(finalizeOrderRequest),
      dataType: 'json'
    }).done(function (finalizeOrderResult) {

          var txt = JSON.stringify(finalizeOrderResult, null, '  ');
          var pre = jQuery('<pre>');
          pre.text(txt);
          var resultsDiv = jQuery('#finalizeOrderResults');
          resultsDiv.html('').append(pre);
        });
  }
  jQuery(document).ready(function () {
    jQuery('#finalizeOrderButton').on('click', finalizeOrder);
  });


/rest/cart/validate

MethodPOSTComments
Descriptionvalidates an orderchecks all the required fields. This is also done during checkout, so this method is rarely called before checkout. It's value lies in multi-page checkouts. You may pass in options for what fields to validate and they will be checked. This allows you to show errors on the same page where they happened.

Cookies

none


Path Parametersnone


Query Parameters

check

(multiple checks allowed)

The following strings should be passed literally to enabled a check.

Example: /rest/cart/validate?check=Item%20Quantity%20Valid&check=Billing%20Address%20Provided

  • Item Quantity Valid
  • Billing Address Provided
  • Billing State Abbreviation Valid
  • Billing Phone Numbers Provided
  • Email provided if required
  • Billing Validate City State Zip
  • Tax County Specified
  • Shipping Method Provided
  • Advertising Source Provided
  • Referral Code Provided
  • Shipping Address Provided
  • Shipping State Abbreviation Valid
  • Gift Message Length
  • Shipping Validate City State Zip
  • Shipping Destination Restriction
  • One per customer violations
  • Credit Card Shipping Method Conflict
  • Payment Information Validate
  • Payment Method Provided
  • Quantity requirements met
  • Items Present
  • Options Provided
  • CVV2 Not Required
  • Electronic Check Confirm Account Number
  • Customer Profile Does Not Exist.
  • Valid Ship On Date
  • Pricing Tier Limits
  • Shipping Needs Recalculation
  • Merchant Specific Item Relationships
  • All
Headers

none


Receives JsonCart
Returns JsonString[ ]Returns back an array of errors, if any. If none, everything passed validation.

This example is best understood by viewing it in the demo.  It uses form fields to set values.

function validate() {
  var cart = {
    'merchantId': 'DEMO'
  };
 
  // grab the field values and add them to the cart.
  jQuery('.validation-fields input').each(function (idx, el) {
    cart[el.name] = jQuery.trim(el.value);
  });
 
 
  // validations are query parameters.
  var checks = [];
  jQuery('.validation-checkbox:checked').each(function (idx, el) {
    checks.push(encodeURIComponent(el.value));
  });
 
  jQuery.ajax({
    url: '/rest/cart/validate?check=' + checks.join("&check="),
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(cart),
    dataType: 'json'
  }).done(function (validationErrors) {
 
        var txt = null;
        if (validationErrors && validationErrors.length == 0) {
          txt = "No Errors Reported.";
        } else {
          txt = JSON.stringify(validationErrors, null, '  ');
        }
 
        var pre = jQuery('<pre>');
        pre.text(txt);
        jQuery('#validateResults').html('').append(pre);
      });
}
 
jQuery(document).ready(function () {
  jQuery('#validateButton').on('click', validate);
});

/rest/cart/setFinalizeAfter

MethodPOSTComments
Descriptionfinalized the order with a time waitThis method is used for upsells. When the order is complete, call this method. After that, you may show the user additional upsells. These upsells can be added to the cart without issue. This method is used to protect an order in case the customer closes the browser during the navigation. When finalizeAfter

Cookies

none


Path Parametersnone


Query Parameters

minutes

an integer for how long to wait before finalizing the order. If absent, the default is 30 minutes.
Headers

none


Receives JsonCart
Returns Jsonnothing.If successful, the call will return back status code 204 which signifies "no content", but "all is well"
// since this demonstration has both a set and a clear, I'll need some state.
// so I'm going to use a global variable to store a cart reference.  Don't hate me.
var finalizeCart = null;
 
function finalizeAfter() {
 
  if (!finalizeCart) {
    jQuery.ajax({
      url: '/rest/cart',
      headers: {'X-UC-Merchant-Id': 'DEMO',
        "cache-control": "no-cache"}, // could also pass merchant id as query parameter named '_mid' or cookie named 'UltraCartMerchantID'
      dataType: 'json',
      async: false // for the demonstration, I'm keeping it simple with an synchronous call...
    }).done(function (cart) {
          finalizeCart = cart;
        });
  }
 
  jQuery.ajax({
    url: '/rest/cart/setFinalizeAfter?minutes=20', //minutes is optional.  default is 30
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(finalizeCart),
    dataType: 'json'
  }).done(function (data, textStatus, jqXHR) {
 
        var txt = jqXHR.status == 204
            ? "Server returned 204 'No Content', so the setFinalizeAfter was successful"
            : "Error. setFinalizeAfter failed with this: " + textStatus;
        var pre = jQuery('<pre>');
        pre.text(txt);
        jQuery('#finalizeResults').html('').append(pre);
 
 
      });
}
 
 
function clearFinalizeAfter() {
  if (!finalizeCart) {
    alert('Please click the finalizeAfter button before attempting to clear it.');
    return;
  }
 
  jQuery.ajax({
    url: '/rest/cart/clearFinalizeAfter',
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(finalizeCart),
    dataType: 'json'
  }).done(function (data, textStatus, jqXHR) {
 
        var txt = jqXHR.status == 204
            ? "Server returned 204 'No Content', so the clearFinalizeAfter was successful"
            : "Error. clearFinalizeAfter failed with this: " + textStatus;
        var pre = jQuery('<pre>');
        pre.text(txt);
        jQuery('#finalizeResults').html('').append(pre);
 
      });
}
 
 
jQuery(document).ready(function () {
  jQuery('#finalizeAfterButton').on('click', finalizeAfter);
  jQuery('#finalizeClearButton').on('click', clearFinalizeAfter);
});

/rest/cart/clearFinalizeAfter

MethodPOSTComments
Descriptionclears any finalizeAfter callThis method cancels a finalizeAfter call (see above)

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCart
Returns Jsonnothing.If successful, the call will return back status code 204 which signifies "no content", but "all is well"


For an example, see the code for setFinalizeAfter above.

/rest/cart/subscribeToAutoResponder

MethodPOSTComments
Descriptionsubscribes a customer to a mail listIt goes without saying, but I'll say it. Please test out your configuration and mail list to make sure everything's in order. Your customers are not the ones you should test things out with.

Cookies

none


Path Parametersnone


Query Parameters

lists

autoResponderName

lists is an array of mailing lists. Example: ?lists=list1&lists=coupons&lists=survey

The name of the auto responder should be one of the following:

  • icontact
  • madmimi
  • silverpop
  • mailchimp
  • lyris
  • lyrishq
  • campaignMonitor
  • getResponse
Headers

none


Receives JsonCart
Returns JsonCart


/rest/cart/login


MethodPOSTComments
Descriptionlogs a customer inThis activiates the customer profile associated with the email address

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCartThe cart.email and cart.password must be set for the login to work 
Returns JsonCartConsult cart.errors for invalid login response. 

This example uses form fields.  It's best understood by running the demo.

var customerCart = null; // another global variable.  I need to keep state for this demonstration
 
function register() {
 
  // any cart passed to register must have a valid merchant id AND cart id, so I'm creating a cart here.
  if (!customerCart) {
    jQuery.ajax({
      url: '/rest/cart',
      headers: {'X-UC-Merchant-Id': 'DEMO',
        "cache-control": "no-cache"}, // could also pass merchant id as query parameter named '_mid' or cookie named 'UltraCartMerchantID'
      dataType: 'json',
      async: false // for the demonstration, I'm keeping it simple with an synchronous call...
    }).done(function (cart) {
          customerCart = cart;
        });
  }
 
  customerCart.email = jQuery.trim(jQuery('.customer-section input[name=email]').val());
  customerCart.password = jQuery.trim(jQuery('.customer-section input[name=password]').val());
 
  jQuery.ajax({
    url: '/rest/cart/register',
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(customerCart),
    dataType: 'json'
  }).done(function (loggedInCart) {
        customerCart = loggedInCart;
 
        var txt = JSON.stringify(customerCart, null, '  ');
        var pre = jQuery('<pre>');
        pre.text(txt);
        jQuery('#customerResults').html('').append(pre);
 
      });
}
 
function logout() {
  if (!customerCart || !customerCart.loggedIn) {
    alert('Please login first.');
    return;
  }
 
  jQuery.ajax({
    url: '/rest/cart/logout',
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(customerCart),
    dataType: 'json'
  }).done(function (loggedOutCart) {
        customerCart = loggedOutCart;
 
        var txt = JSON.stringify(customerCart, null, '  ');
        var pre = jQuery('<pre>');
        pre.text(txt);
        jQuery('#customerResults').html('').append(pre);
 
      });
}
 
 
function login() {
 
  // any cart passed to register must have a valid merchant id AND cart id, so I'm creating a cart here.
  if (!customerCart) {
    alert('Please register first to create a cart');
    return;
  }
 
  customerCart.email = jQuery.trim(jQuery('.customer-section input[name=email2]').val());
  customerCart.password = jQuery.trim(jQuery('.customer-section input[name=password2]').val());
 
  jQuery.ajax({
    url: '/rest/cart/login',
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(customerCart),
    dataType: 'json'
  }).done(function (loggedInCart) {
        customerCart = loggedInCart;
 
        var txt = JSON.stringify(customerCart, null, '  ');
        var pre = jQuery('<pre>');
        pre.text(txt);
        jQuery('#customerResults').html('').append(pre);
 
      });
}
 
 
function resetPassword() {
 
  // any cart passed to register must have a valid merchant id AND cart id, so I'm creating a cart here.
  if (!customerCart) {
    alert('Please register first to create a cart');
    return;
  }
 
  customerCart.email = jQuery.trim(jQuery('.customer-section input[name=email3]').val());
 
  jQuery.ajax({
    url: '/rest/cart/resetPassword',
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(customerCart),
    dataType: 'text' // Notice - plain text response.  no json
  }).done(function (response) {
 
        var pre = jQuery('<pre>');
        pre.text(response);
        jQuery('#customerResults').html('').append(pre);
 
      });
}
 
 
jQuery(document).ready(function () {
  jQuery('#registerButton').on('click', register);
  jQuery('#logoutButton').on('click', logout);
  jQuery('#loginButton').on('click', login);
  jQuery('#resetPasswordButton').on('click', resetPassword);
});


/rest/cart/logout

MethodPOSTComments
Descriptionlogs a customer out

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCart
Returns JsonCart


see the example for login above

/rest/cart/register

MethodPOSTComments
Descriptioncreates a CustomerProfile for the customer

Cookies

none


Path Parametersnone


Query Parameters

useAddress

Optional parameter to determine which address (shipping or billing) should be used to set the base address for the customer.

The default is to use the biling address. If this parameter contains anything other than 'shipping', the billing address is used.

If this parameter is missing, the default is billing.

(New Parameter added 10/21/2013)

Headers

none


Receives JsonCart
Returns JsonCart


see the example for login above

/rest/cart/resetPassword


MethodPOSTComments
Descriptionemails the customer a temporary password and link to reset their password.

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCart
Returns TEXTNotice: This returns plain text. Look for success.

see the example for login above

/rest/cart/checkoutTerms

MethodPOSTComments
DescriptionReturns the checkout terms This is a separate call because many merchants have extremely long checkout terms and we don't want to pass them back and forth multiple times.

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCart The cart must be passed in because the checkout terms may vary by cart items.
Returns JsonCheckoutTerms
function checkoutTerms() {
 
  var cart = {
    'merchantId': 'DEMO',
    'cartId': '', // will be populated by call
    'items': [
      {'itemId': 'PDF', 'quantity': 1},
      {'itemId': 'Baseball', 'quantity': 2},
      {'itemId': 'BONE', 'quantity': 5}
    ]
  };
 
  jQuery.ajax({
    url: '/rest/cart',
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(cart),
    dataType: 'json'
  }).done(function (updatedCart) {
 
        jQuery.ajax({
          url: '/rest/cart/checkoutTerms',
          type: 'POST', // Notice
          headers : { "cache-control": "no-cache" },
          contentType: 'application/json; charset=UTF-8',
          data: JSON.stringify(updatedCart),
          dataType: 'json'
        }).done(function (terms) {
 
              var txt = JSON.stringify(terms, null, '  ');
              var pre = jQuery('<pre>');
              pre.text(txt);
              jQuery('#checkoutTermsResults').html('').append(pre);
 
            });
      });
}
 
jQuery(document).ready(function () {
  jQuery('#checkoutTermsButton').on('click', checkoutTerms);
});


/rest/cart/relatedItems

MethodPOSTComments
DescriptionReturns items related to the cart items

Cookies

none


Path Parametersnone


Query Parameters

thumbnailSize

optional integer: one of these values: 80, 100, 200, 220, 250, 500. This is an optional parameter. The default is 80px. Thumbnails are always square.

Headers

none


Receives JsonCart
Returns JsonArray of ItemsNotice that this returns back Items, not CartItems. There is a difference. You should not add an Item to your cart. Create a new CartItem instead. The server will not like Item json appears where CartItem is expected.

/rest/cart/relatedItems/{itemId}

MethodPOSTComments
DescriptionReturns items related to a single item id

This differs from the method call directly above. The method above considers the entire shopping cart and returns a list related to the cart. The call above is useful on a checkout page. This method returns related items for a single items. Its useful is for a single item page where you wish to show related items for it.


This information is not contained in the normal item information because it would triple/quadrulple the item size easily. So we keep this as a separate call to keep things fast.

Cookies

none


Path Parametersnone


Query Parameters

thumbnailSize

optional integer: one of these values: 80, 100, 200, 220, 250, 500. This is an optional parameter. The default is 80px. Thumbnails are always square.

Headers

none


Receives JsonCartEven though the cart items are not considered, the cart is still necessary as a parameter for the underlying query. A new cart is fine to pass in. However, most of the time, the customer will already have a cart in progress, so this shouldn't be a problem to pass in.
Returns JsonArray of ItemsNotice that this returns back Items, not CartItems. There is a difference. You should not add an Item to your cart. Create a new CartItem instead. The server will not like Item json appears where CartItem is expected.

/rest/cart/taxCounties


MethodPOSTComments
DescriptionReturns a list of possible tax counties

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCart
Returns JsonArray of StringsIf your cart collects tax, this call is useful to determine if a taxable county is applicable. Some cities span counties, so this list could be used to have the customer select which county they live in to collect applicable taxes.

/rest/cart/giftSettings

MethodPOSTComments
DescriptionReturns gift settingsSince most merchants do not use gift settings, this is a separate call to keep the bulk of transactions fast. 

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCart
Returns JsonGiftSettings

/rest/cart/validateGiftCertificate

MethodPOSTComments
Descriptionvalidates a gift certificate

Cookies

none


Path Parametersnone


Query Parameters

giftCertificate

The gift certificate code.

Headers

none


Receives JsonCart
Returns JsonArray of StringsReturns a list of any issues found. No news is good news.
MethodPOSTComments
Descriptionlinks multiple sitesThis call is useful for sites with multiple urls. This call links them all together on the back end. This is an advanced call and will not be used by many. 

Cookies

none


Path Parametersnone


Query Parameters

secureHostName

Notice! This is a POST that also has a query parameter. The secureHostName should point to the checkout site. For example, if your catalog/product site is hosted on your own server named www.rainglobes.com, and your UltraCart checkout is using the url secure.rainglobes.com, then you should pass in secureHostName=secure.rainglobes.com as the parameter here.

Headers

none


Receives JsonCart
Returns JsonStringReturns a list of urls that you should call (embed as img, use ajax, etc). Each url called will set cookies on that url so that a cart session can jump domains.

/rest/cart/cityState

MethodPOSTComments
Descriptionvalidates the city, state, and zipCompares to the zip to the city and state. If they don't match, it returns back the correct city and state. This method is useful for prepopulating city and state when the user enters a zip code.

Cookies

none


Path Parametersnone


Query Parameters

none


Headers

none


Receives JsonCart
Returns JsonCityStateZip
function cityState() {
 
  var cart = {
    'merchantId': 'DEMO',
    'cartId': '', // will be populated by call
    'shipToPostalCode': '44233'
  };
 
  jQuery.ajax({
    url: '/rest/cart',
    type: 'POST', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(cart),
    dataType: 'json'
  }).done(function (updatedCart) {
 
        jQuery.ajax({
          url: '/rest/cart/cityState',
          type: 'POST', // Notice
          headers : { "cache-control": "no-cache" },
          contentType: 'application/json; charset=UTF-8',
          data: JSON.stringify(updatedCart),
          dataType: 'json'
        }).done(function (cityStateZip) {
 
              var txt = JSON.stringify(cityStateZip, null, '  ');
              var pre = jQuery('<pre>');
              pre.text(txt);
              jQuery('#cityStateResults').html('').append(pre);
 
            });
      });
}
 
jQuery(document).ready(function () {
  jQuery('#cityStateButton').on('click', cityState);
});




/rest/cart/share/email

MethodGETComments
Descriptionemails the cart items

Sends an email of the cart items to a desired receipient. The email is formatted via the Email Notifications (Home → Configuration →Email Notifications).

For security, only the cart items are available to the email template.

The cart must be a valid shopping cart with at least one item in it.

Cookies

UltraCartMerchantID - Merchant ID

UltraCartShoppingCartID - Cart ID

Optional cookies. cart id and merchant id must be provided by either cookie, header, or query parameter.
Path Parametersnone


Query Parameters

_cid

_mid

fromEmail

fromName

toEmail

Optional cart id (The cart id must be provided by either cookie, header, or query parameter.

Optional merchant id (merchant id must be provided by either cookie, header, or query parameter.

Email address who is sharing cart. This may come from a customer profile or submitted by the end customer.

The name of the person sending the email.

The target. The person who will receive the email.

Note: The fromEmail, fromName, and toEmail are heavily filtered for html injection attacks.

Headers

X-UC-Merchant-Id - Merchant ID

X-UC-Shopping-Cart-Id - Cart ID


Receives Jsonnone
Returns Json

204 No Content on Success.

400 Bad Request if there's an issue with incoming parameters.

500 Server Error for unforseen errors


function shareCart() {
 
 
  jQuery.ajax({
    url: '/rest/cart/share/email',
    type: 'GET', // Notice
    headers : { "cache-control": "no-cache" },
    contentType: 'application/json; charset=UTF-8',
    data: {'_cid': my_cart_id, '_mid': 'DEMO', 'fromEmail': 'joe@aol.com', 'fromName': 'Joe Smith', 'toEmail': 'larray@aol.com' },
    dataType: 'json'
  }).done(function (data, textStatus, jqXHR) {
     // check for 204, 400, or 500.
      });
}
 


Server Side Logging

Detailed logs for errors may be captured on the UltraCart system.  Optionally, the last 100 calls made may be captured as well.   

To use: 

  • Ensure the login used to access secure.ultracart.com has "API Access".  This may be granted by the account owner here:  Configuration  Manage Users  Edit User.
  • Once permission is granted, navigate to Developer Tools  Call History Log.  It's a link in the Javascript Checkout API section.