Using Store Builder Library (SBL), you can optionally create a button that launches PayPal directly. The goal is to bypass the initial Popup Storefront or Web Storefront interface altogether. However, this approach is only available under certain conditions. Using this method streamlines the purchase process for customers who frequently make purchases using PayPal. It may also make the process more familiar to such customers and should improve conversion rates for them.

 Note

To pre-select PayPal as the payment method, your page must load SBL version 0.8.0 or later.

 

Conditions Required to Pre-Select PayPal

Under certain circumstances, pre-selecting PayPal still results in the standard checkout flow (with a Popup Storefront or a Web Storefront). When this happens with a Popup Storefront, PayPal is selected as the payment method.

The FastSpring Storefront cannot be skipped in any of the following circumstances:

 

Methods of Pre-Selecting PayPal

To create a button that attempts to skip the FastSpring Storefront and directs the customer straight to the PayPal login, use one of the following approaches:

 Note

If you attempt any of these approaches when the cart is empty, the behavior is the same as the normal checkout process. SBL returns a silent response code 400, and nothing further happens.

 

Determining When to Display a Separate PayPal Button

 Important

If you attempt to pre-select PayPal as the payment method when PayPal is not available, SBL returns a silent response of 400 – invalid payment method.

There are two ways you can identify whether or not PayPal is currently available for the order session. Using either of the following methods, you can hide or show a dedicated "Pay with PayPal" button, according to PayPal's actual current availability.

 

Using the smartdisplay Directive

If you plan to create a button using the markup directive data-fsc-action="PaypalCheckout", you can add a couple of directives to the button so that it only appears when PayPal is currently available.

Adding both data-fsc-order-paypal-available and data-fsc-smartdisplay to your button causes the element to be hidden when PayPal is not available, and to be displayed when it is available. Here is an example of a basic button (you could adjust the style using CSS):

<button data-fsc-action="PaypalCheckout" data-fsc-order-paypal-available data-fsc-smartdisplay>Check Out with PayPal</button>

 

Parsing the Order Object Response

The order object response includes an array named availablePaymentMethods that lists each of the payment methods that are currently available. The response includes a single value for each available payment method, as in the following example:

   "availablePaymentMethods":[  
      "wire",
      "paypal",
      "card",
      "purchaseorder",
      "amazon"
   ],

If "paypal" is in the array, you can display a button that launches PayPal directly. If "paypal" is not in the array, you may choose to suppress/hide the button.

FastSpring's Store Builder Library (SBL) allows you to provide customer details (such as name and email address) before initiating the checkout process. There are three ways to provide pieces of customer information using SBL:

 Note

If you need a back-end means of providing customer information—i.e., without using SBL at all–consider POSTing to the /accounts endpoint of the FastSpring API and then using /sessions to create the store session.

 

Using fastspring.builder.recognize() OR the paymentContact Object within the SBL Session

During checkout preparation (before launching the checkout process), you can provide customer details using the fastspring.builder.recognize() call, or within the paymentContact object of session data that you may push to SBL (e.g., using fastspring.builder.push()). Either way, the data you provide is used to pre-fill checkout fields with the information.

The fastspring.builder.recognize() call and the paymentContact object in an SBL session require at least an email address; other fields are optional. All the data provided through these methods is visible and editable during the checkout.

 Tip

If you use either of these methods to supply the email address of a customer who already has an account in your FastSpring Store, any other customer details (e.g., name or address) that you do not specify by these methods may be automatically filled in from the customer account record.

The purpose of these methods is to allow you to provide "potential" customer details. For example, if a customer lands on your page from a link in an email message and your page is designed to parse the URL parameters, the email address can be "recognized" so the customer does not have to enter it again. Here is a full list of fields that can be provided through the "recognize" call or in the paymentContact object within an SBL session:

In addition to using fastspring.builder.recognize() to pass in the fields above, you can use the following methods to pass specific pieces of customer data when not using a secure payload:

fastspring.builder.language('') Pass in the two-character ISO language code (e.g., "de" for German or "fr" for French).
fastspring.builder.taxId(") For customers in locations where FastSpring accepts a tax I.D. to prevent the collection of VAT or GST.

Likewise, when using the SBL session object, the order language and the customer's tax I.D. can be supplied but must be passed outside the paymentContact object, using "language": "<2-character ISO language code>" and "taxId": "<id>", respectively.

 

Example 1: Three methods called separately to pass in data for a customer in Germany who wants to order in English and is exempt from paying VAT

Example: Three separate methods to pass in customer details
fastspring.builder.recognize({"email":"ne1@all.com","firstName":"Leeroy","lastName":"Jenkins","country":"DE"})

fastspring.builder.language("en")

fastspring.builder.taxId("DE1234567")

 

Example 2: Using the session object to pass in product and quantity plus data for a customer in France who wants to order in English and is exempt from paying VAT

 Note

When the product's Quantity field has a behavior of "Locked" or "Hidden", you cannot override the default quantity using the session object. Consider using a secure payload instead.
Example: Using the session object to pass in product, quantity and customer data
var s = {
  "reset": true,
  "products" : [
    {
      "path":"example-product-1",
      "quantity": 1
    }
  ],
  "paymentContact": {
    "email":"ne1@all.com",
    "firstName":"Leeroy",
    "lastName":"Jenkins",
    "country":"FR"
  },
  "language":"en",
  "taxId":"FR123456789"
}


fastspring.builder.push(s)

 

Using a Secure Payload

Data provided inside the contact object of a secure payload is validated when submitted and is only stored if it is valid. It goes through the same validation process it would have gone through when the customer attempted to checkout, but this happens upon submission instead of waiting for the checkout. If such data passes validation, all the corresponding fields are hidden during the checkout, and only payment details will be collected. Here is a full list of fields that you can provide through the secure payload and their validation rules:

firstName These three fields are always required in the secure payload. For example, you cannot provide a customer's address without providing his or her name and email address. First and last names need to be at least 1 character long, and email must be a valid email address.
lastName
email
company Optional, not validated
addressLine1

Required if enabled on the store. However, you can always provide the address, and it will be validated even if not required when creating or updating an account using a secure payload or /account call.

Fields in bold are required. Additionally, for U.S. addresses, the region must have a valid value for the supplied postalCode. For example, if the region is "US-CA," meaning California, the postalCode value must be a valid California ZIP code. If the postalCode provided does not correspond to the region, the address will not pass validation.

region format = "<2-character ISO country code><2-character ISO U.S. state code>", e.g., "region":"US-TX" for Texas

addressLine2
city
region (required for U.S.)
country
postalCode

phoneNumber

Required if enabled on the store
country If not provided, assumed during checkout based on geo I.P. location

 Note

Specifying the customer's country in a secure payload also sets the language automatically, overriding order language selection based on the browser's default language. You can also set the language separately in the secure payload using "language", outside the contact object.

Important:  If details in the contact object of a secure payload do not pass validation, FastSpring treats those details in the same way as a fastspring.builder.recognize() call; i.e., the data will be pre-filled, but fields will be visible during the checkout. This behavior allows customers to correct the mistakes. However, in the case of address fields, if your Storefront is not configured to display those fields, the customer does not see the fields and cannot correct the problem. Therefore, if address validation is vital to your business, we encourage you to do one of the following:

 Note

For assistance with validating the data via Store Builder Library, check out the Field Validation section of Accessing the Library from JavaScript.

In addition to the contact object of a secure payload, there are two other pieces of customer information you can pass separately in the payload:

language Pass in the two-character ISO language code (e.g., "de" for German or "fr" for French)
taxId For customers in locations where FastSpring accepts a tax I.D. to prevent the collection of VAT or GST

 

Example 1: Passing in Data for a U.S. Customer Via the Contact Object of a Secure Payload

Example:  Passing in Data for a U.S. Customer Via the Contact Object of a Secure Payload
{  
   "contact":{  
      "email":"ne1@all.com",
      "firstName":"Leeroy",
      "lastName":"Jenkins",
      "region":"US-CA",
      "postalCode":"93101"
   }
}

Example 2: Passing in Language and Tax ID for an E.U. Customer Via a Secure Payload

Example 2: Passing in Language and Tax ID for an E.U. Customer Via a Secure Payload
{  
   "contact":{  
      "email":"ne1@all.com",
      "firstName":"Leeroy",
      "lastName":"Jenkins",
      "country":"DE"
   },
   "language":"en",
   "taxId":"DE1234567"
}

 

Data Precedence

If FastSpring receives customer data from more than one source for the same session, FastSpring uses the following logic to decide which customer data applies to the order:

In simple form, the order of precedence is as follows:

  1. Secure Payload 
  2. Data entered during checkout
  3. Recognized / paymentContact data
  4. Data from the payment method

When designing your web pages to use Store Builder Library (SBL), you may want to create a full shopping cart experience. In that case, you should take into account the possible taxes, such as VAT, GST, and sales tax, that may apply to each order. This article provides a strategy for handling the various tax scenarios in your SBL shopping cart.

 

The Order Object Response

Each time the order details are updated (e.g., by adding an item to the cart), the library immediately returns a response containing all details of the current order session. This is called the order object response. You can find an example of the order object response here. You should design your page to parse the order object response each time the order details are updated.

The order object response contains several fields that may be helpful for you in handling and displaying taxes:

Field Data Type Description
taxExemptionAllowed Boolean based on order country, indicates whether or not it is possible to supply an ID (e.g., VAT ID, GST ID) and remove tax from the order
taxExempt Boolean indicates whether or not the current order is exempt from tax
total String the order total; may or may not include tax (see taxPriceType)
totalValue* Number the order total, without the currency symbol
tax String the amount of tax currently applied to the order
taxValue* Number the amount of tax currently applied to the order, without the currency symbol
totalWithTax String the order total, including tax
totalWithTaxValue* Number the order total, including tax, without the currency symbol
taxPriceType String "included" or "added"; indicates whether tax is included in the subtotal or added to the subtotal
taxType String "US" (US state/local sales tax) | "VAT" (Value Added Tax, e.g. in the EU) | "GST" (Goods and Services Tax, e.g. in Australia) | "JP" (Japan's Consumption Tax)
taxRate String the tax rate applied to the current order if taxExempt is false, expressed as a percentage; "0%" if unknown (e.g., country/postal code have not been supplied)
priceWithoutTax String the total price of the current item before any applicable taxes; only included in the order object response for Stores using net pricing mode
priceValueWithoutTax Number the total price of the current item before any applicable taxes, without the currency symbol; only included for Stores using net pricing mode
priceWithoutTaxAndDiscount String unit price of the current item, before tax and any coupon discounts; only included for Stores using net pricing mode
priceValueWithoutTaxAndDiscount Number unit price of the current item, before tax and any coupon discounts, without the currency symbol; only included for Stores using net pricing mode

 Note

*Fields with "Value" in the name are alternative versions of the corresponding fields. They are provided in case you want to render only the numeric values or format the data differently (e.g., with no currency symbol).

 

Supplying Required Details to the Session

To retrieve accurate tax details from the library, you must first collect the following transaction details and update the session with them. Since non-U.S. taxes are assessed nationally, and U.S. sales taxes depend on the customer's postal code, the requirements can differ depending on the customer's country.

 Demonstration Video

Check out this quick demonstration video showing one method of applying the customer's tax ID to the SBL session.

 

Data Purpose Method(s)
when country != "US"
country used to determine whether or not VAT, GST, or Japanese consumption tax apply, and at what rate
taxID for customers who have exempt or deferred status (usually organizations), in countries where taxExemptionAllowed is true,
taxID is used to validate the string supplied by the customer and set taxExempt to true when applicable, removing tax from the order
when country == "US"
postalCode determines whether or not sales tax applies, and at what rate

 

Displaying Tax Information to the Customer In Your Cart

If taxExempt = true:

If taxExempt = false and taxPriceType == "added":

If taxExempt = false and taxPriceType == "included":

 

Displaying Pre-Tax Price Information to the Customer In Your Cart (for Stores Using Net Pricing)

For Stores using net pricing mode, Store Builder Library's order object response includes two fields you can use to display item-level pre-tax prices to your customers:

In the context of an itemized shopping cart, you could then use either tax or taxValue from the order object response to render the total tax amount. Also, you could use totalWithTax or totalWithTaxValue to show the grand total with sales tax.

If you use the Store Builder Library (SBL) on your website, you can optionally populate certain pieces of transaction data via URL parameters. 

Parameters are values passed as part of the URL that customers use to access the store page. By adding JavaScript code to parse the URL and apply the parameter values to SBL functions, you can pass transaction data right in the URL. This approach is possible for any transaction data that can be applied via SBL functions, including:

Here is an example that you could implement near the bottom of your page, just after the closing </body> tag.

 Note

The following example is provided "as is" and is intended for illustration purposes. You may need to adjust the code provided in the example to meet your needs or work with your specific implementation.
Example of populating transaction data via URL parameters
<script>
    var QueryString = function () {
  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = decodeURIComponent(pair[1]);
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(decodeURIComponent(pair[1]));
    }
  } 
  return query_string;
}();
</script>
    <script>
        $( document ).ready(function() {

			var s = {};
			
            if(QueryString.product) {
                s = {
                    'products' : [
                        {
                            'path':QueryString.product,
                            'quantity':1
                        }
                    ]
                }
            }
 
            if(QueryString.email && QueryString.fname && QueryString.lname) {
				s.paymentContact = {};
				s.paymentContact.email = QueryString.email;
				s.paymentContact.firstName = QueryString.fname;
				s.paymentContact.lastName = QueryString.lname;
			}
 
            if(QueryString.coupon) {
				s.coupon = QueryString.coupon;
            }
            
			if (s) fastspring.builder.push(s);
        });
    </script>

The above example allows you to use URL parameters to pass information to be added to the cart session. If you specify the product in the URL, be sure to use the product path/product ID rather than the product's Display name.

For example: 

Example URL
.../cart.html?product=8675309&coupon=FALLSALE&fname=Leeroy&lname=Jenkins&email=ne1@all.com

In this example, the store page on your website would have a URL ending in cart.html. The name of the page can be whatever you need. The above adds product ID 8675309 to the cart, applies coupon FALLSALE, and applies the customer's first name, last name, and email address to the order.

If you only want to pass the product:

Example URL
.../cart.html?product=8675309

If you only want to pass the product and the coupon code:

Example URL
.../cart.html?product=8675309&coupon=FALLSALE

If you pass in the customer name or email address, then currently, the first name, last name, and email address must all be passed for any of them to work. For example:

Example URL
.../cart.html?fname=Leeroy&lname=Jenkins&email=ne1@all.com

An advanced alternative to using HTML Markup directives is to access the Store Builder Library directly from Javascript utilizing available public methods

Store Builder Library is a wrapper around a set of private APIs that allow you to manipulate the cart contents for a given visitor. All calls made to the Library are converted into API requests and published to the backend expecting a response with current cart contents and order parameters – the "order object." Given sophisticated cart population logic, various cross-sell and upsell scenarios, and other features of the platform, each request might result in significant changes to the order object. We recommend that you rely on the most current data after each request and avoid caching responses. 

All requests to the Library are made in the form of the Session Object. The library converts the Session Object to internal API directives. Use the Session Object for passing order details to the Store without requiring the use of a secure payload.

For interactive examples, see FastSpring Examples.

Session Object

The Session Object is a standard Javascript object which contains directives for the Store Builder Library. The Session Object may contain the following fields:

Once created, the Session Object is usually passed to the Library by utilizing the fastspring.builder.push() method:

var s = {
	'reset': true, // reset the cart and session (will remove everything added to the cart or passed to the session prior to this)
	'products' : [
					{
						'path':'example-product',
						'quantity': 1 // add product "example-product" to the cart with quantity "1".
					}
	],
	'coupon': 'YOUR10OFF', // apply coupon to the order
	'checkout': true // once all of the above is done redirect to checkout
}

fastspring.builder.push(s); // call Library "Push" method to apply the Session Object. 
If the product specified in the Path has a default quantity behavior set to locked or hidden, you cannot override the quantity using the session object. However, you can override it using a secure payload. You can change the Product’s default quantity behavior by clicking Pricing in the product details page,  or by posting to the /product endpoint of the FastSpring API.

Initialize the Library with the Session Object

The Store Builder Library makes an initial request to the FastSpring backend as soon as it’s initialized. Sometimes your website flow requires you to pass data to the Library before making the initial request. 
To enable this behavior, place a Session Object into the variable named "fscSession" before initializing the Library:

<script>
var fscSession = {
	'reset': true,
	'products' : [
					{
						'path':'example-product',
						'quantity': 1
					}
	],
	'coupon': 'YOUR10OFF'
}
</script>
<script
	id="fsc-api"
	src="https://d1f8f9xcsvx3ha.cloudfront.net/sbl/0.8.3/fastspring-builder.min.js"" type="text/javascript" 
...

If you define the "fscSession" variable before the API is loaded, the contents will be executed with first priority. In this example, the session will be reset (breaking continuous mode), the "example-product" product will be added to the cart, and a coupon will be applied immediately upon loading the library.
 

If the product specified in the Path has a default quantity behavior set to locked or hidden, you cannot override the quantity using the session object. However, you can override it using a secure payload. You can change the Product’s default quantity behavior by clicking Pricing in the product details page,  or by posting to the /product endpoint of the FastSpring API

Public Methods Exposed by the Library

After the Library is loaded, your web page can access it using public methods. To take advantage of the latest methods, ensure that your page is using the most current Store Builder Library version. To update the version that your page uses, update the URL in the src directive of the script that loads SBL (e.g., https://d1f8f9xcsvx3ha.cloudfront.net/sbl/0.8.3/fastspring-builder.min.js )

var s = {
	'products' : [
					{
						'path':'example-product',
						'quantity': 1
					}
	],
	'coupon': 'YOUR10OFF',
	'checkout': true
}

fastspring.builder.push(s);

If the product specified in the Path has a default quantity behavior set to locked or hidden, you cannot override the quantity using the session object. However, you can override it using a secure payload. You can change the Product’s default quantity behavior by clicking Pricing in the product details page,  or by posting to the /product endpoint of the FastSpring API

Public Methods Callback Function

All public methods accept the callback function. This function is called after the primary request has been made. This approach differs from the generic "data-data-callback", which is called only once for a request chain. This means that if multiple requests are made, only the last request returns the order object. By using the callback function in conjunction with a public method, the callback function receives the order object that resulted from the call, giving you more flexibility around integration. The callback function is always passed as the last parameter. 

	 fastspring.builder.add("example-product-1", function(data){
 
	console.log("Added 'example-product-1' and it resulted in the following order object", data);
 
});
	
The fastspring.builder.checkout() method does not accept a callback function as a parameter due to its finite nature.

Errors

Some requests might result in errors received from the server. All errors are fatal – if an error occurs, processing stops, and the server returns an error response. The easiest way to handle errors is to declare an "error callback" function when initializing the Library.

In case of an error, the body of the response will contain one of the following "codes":

Add a Product

Field Validation

Starting with Store Builder Library (SBL) version 0.7.9, the payload of the order object response includes an array named fields. The "fields" array provides up-to-date validation details regarding specific fields of the order session data. You can also optionally send the field validation data to your dedicated script via the data-validation-callback.

The following order session fields are validated:

Each object in the fields array may consist of the following items:

Name Type Description
fieldName string the name of the current field in the array
required  Boolean indicates whether the field is required to process an order
provided Boolean indicates whether or not you have provided value for the current field
transport string only appears when provided is true;

indicates the method of submitting the session data via SBL:

"secure" for secure payloads; otherwise, "recognize"

valid Boolean only appears when provided is true;

indicates whether or not the provided value is valid

error object only appears when valid is false
error.code string error code regarding the current field
error.message string verbose error message regarding the current field

 

Error Codes and Messages

If an invalid country is passed via fastspring.builder.push(), fastspring.builder.recognize(), or fastspring.builder.secure(), the invalid value is discarded and geolocation is used to set the order country. However, fastspring.builder.country() can result in this field validation error. 

Example of the "fields" array

   "fields":[  
      {  
         "fieldName":"firstName",
         "required":true,
         "provided":true,
         "transport":"recognize",
         "valid":true
      },
      {  
         "fieldName":"lastName",
         "required":true,
         "provided":true,
         "transport":"recognize",
         "valid":true
      },
      {  
         "fieldName":"country",
         "required":true,
         "provided":true,
         "transport":"recognize",
         "valid":true
      },
      {  
         "fieldName":"email",
         "required":true,
         "provided":true,
         "transport":"recognize",
         "valid":true
      },
      {  
         "fieldName":"postalCode",
         "required":true,
         "provided":true,
         "transport":"recognize",
         "valid":false,
         "error":{  
            "code":"postalcode-invalid",
            "display":"Postal Code is not Valid"
         }
      },
      {  
         "fieldName":"taxId",
         "required":false,
         "provided":false
      },
      {  
         "fieldName":"language",
         "required":false,
         "provided":false
      },
      {  
         "fieldName":"coupon",
         "required":false,
         "provided":false
      },
      {  
         "fieldName":"account",
         "required":false,
         "provided":false
      }
   ],  

Order Object Response Fields

{  
   "currency":"USD",
   "country":"US",
   "taxExemptionAllowed":false,                    // based on "country", indicates whether or not it is possible to supply an ID (e.g. VAT ID, GST ID) and remove tax from the order
   "taxExempt":false,                              // indicates whether or not the current order is exempt from tax
   "total":"$6.17",                                // order total without tax
   "totalValue":6.17,                              // order total value (without the currency symbol), without tax
   "tax":"$0.45",                                  // total amount of VAT or sales tax
   "taxValue":0.45,
   "totalWithTax":"$6.62",                         // this price will be charged; it accounts for quantity, discounts and unit price.
   "totalWithTaxValue":6.62,                       // order total with tax but without the currency symbol
   "discountTotal":"$6.17",                        // total discount for the order
   "discountTotalValue":6.17,
   "discountTotalPercent":"50%",
   "discountTotalPercentValue":50.0,
   "taxPriceType":"added",                         // "included" or "added"; indicates whether tax is included in the subtotal or added to the subtotal
   "taxType":"US",                                 // "US" (US state/local sales tax) | "VAT" (Value Added Tax, e.g. in the EU) | "GST" (Goods and Services Tax, e.g. in Australia) | "JP" (Japan's Consumption Tax)
   "taxRate":"7.25%",                              // the tax rate applied to the current order if taxExempt is false, expressed as a percentage; "0%" if unknown (e.g. country / postal code have not been supplied)
   "groups":[  
      {  
         "items":[              
            {  
               "selected":true,                    // indicates whether the item is in the order
               "path":"example-product-2",         // internal product id / product path
               "pid":"example-product-2",          // internal product id (backward compatibility)
               "quantity":1,                       // quantity of the item
               "price":"$12.34",                   
               "priceValue":12.34,
               "priceTotal":"$12.34",              // quantity multiplied by item's unit price
               "priceTotalValue":12.34,
               "unitPrice":"$6.17",                // unit price of the item
               "unitPriceValue":6.17,
               "unitDiscount":"$6.17",
               "unitDiscountValue":6.17,
               "discountPercent":"50%",
               "discountPercentValue":50.0,
               "discountTotal":"$6.17",
               "discountTotalValue":6.17,
               "total":"$6.17",                    
               "totalValue":6.17,
               "priceWithoutTax":"$6.17",          // when net pricing is enabled, this string indicates the price of the current item without applicable tax
               "priceValueWithoutTax":6.17,        // when net pricing is enabled, the numeric value of the price before tax (with no currency symbol)
               "quantityEditable":true,            // indicates whether or not visitor is allowed to change the quantity of the item
               "removable":true,                   // indicates whether or not visitor is allowed to remove the item from the cart
               "image":"https://d8y8nchqlnmka.cloudfront.net/VTetZH1kQD8/r7kju5MHTRQ/example-product-2-box.png"",
               "display":"Nest",                   // product display name; show this to the visitor
               "sku":"skuex2",
               "description":{  
                  "summary":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.",
                  "full":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vel mi quam. Etiam non purus et est volutpat aliquet. Sed a urna nec nisi scelerisque maximus. Aenean vitae cursus augue. Phasellus eu finibus ex. Morbi auctor nec leo vel suscipit. Sed non condimentum elit.",
                  "action":"Buy Now"
               },
               "pricing":{  
                  "quantity":"allow"               // allow: visitor is allowed to change quantity. lock: visitor is shown quantity, but can't change. hide: visitor can't see quantity  
               },
               "discount":{  
                  "reason":"Halloween Special!",
                  "coupon":"HALFOFF",
                  "data":{  
                     "tiers":[  

                     ],
                     "discountPath":null,
                     "discountDuration":null,
                     "percentValue":50.0
                  }
               },
               "groups":[                          // if item contains upsells, options, choose-one and choose-many configuration parameters they will appear here; the format is the same as the parent item.  

               ],
               "productFormat":"digital",
               "priceWithoutTaxAndDiscounts":"$12.34",   // when net pricing is enabled, this string indicates the unit price of the current item, before tax and any coupon discounts
               "priceValueWithoutTaxAndDiscounts":12.34, // when net pricing is enabled, the numeric value of the unit price of the current item, before tax and any coupon discounts (without the currency symbol)
               "product":"example-product-2",
               "variation":"example-product-2",
               "attributes":{  
                  "ProductAttributeKey1":"ProductAttributeValue1",
                  "ProductAttributeKey2":"ProductAttributeValue2"
               }
            }
         ],
         "driver":"yourexamplstore-popup-yourexamplestore",  // explains why the group is present in the response; may list a product path if the group is a cross-sell group for a specific product, or may list the Storefront URL if the group is associated with the Storefront
         "required":false,
         "type":"add",
         "selections":true                         // indicates whether or not this group of items contains selected items
      },
      {  
         "display":"Customers also purchased...",  // some group items will have their own display names; this means that items in the group have a header (note:  this line has been added to the example for illustrative purposes)
         "items":[  
            {  
               "selected":false,
               "path":"SystemExtension.eds",
               "pid":"SystemExtension.eds",
               "quantity":1,
               "price":"$4.95",
               "priceValue":4.95,
               "priceTotal":"$4.95",
               "priceTotalValue":4.95,
               "unitPrice":"$4.95",
               "unitPriceValue":4.95,
               "unitDiscountValue":0.0,
               "discountPercentValue":0.0,
               "discountTotal":"$0.00",
               "discountTotalValue":0.0,
               "total":"$4.95",
               "totalValue":4.95,
               "priceWithoutTax":"$4.95",
               "priceValueWithoutTax":4.95,
               "quantityEditable":false,
               "removable":true,
               "image":"https://d8y8nchqlnmka.cloudfront.net/VTetZH1kQD8/vedymJXwSBY/download-icon-small.jpg"",
               "display":"Extended Download Service",
               "description":{  
                  "summary":"Extend the availability of your download today! By default, all file downloads are available for seven days from the date of the purchase. However, if you purchase EDS, all products in this order that have file downloads will be downloadable from FastSpring for one year from the date of your purchase."
               },
               "pricing":{  
                  "quantity":"hide"
               },
               "groups":[  

               ],
               "priceWithoutTaxAndDiscounts":"$4.95",
               "priceValueWithoutTaxAndDiscounts":4.95,
               "product":"SystemExtension.eds",
               "variation":"SystemExtension.eds"
            }
         ],
         "driver":"yourexamplestore-popup-yourexamplestore",
         "required":false,
         "type":"add",
         "selections":false
      }
   ],
   "coupons":[                                     // coupon applied to the order  
      "HALFOFF"
   ],
   "payments":[                                    // list of payment options available for this order; currently the selected payment method cannot be pre-populated via SBL  

   ],
   "fields":[                                      // see Errors:  Field Validation above  
      {  
         "fieldName":"firstName",
         "required":true,
         "provided":false
      },
      {  
         "fieldName":"lastName",
         "required":true,
         "provided":false
      },
      {  
         "fieldName":"country",
         "required":true,
         "provided":false
      },
      {  
         "fieldName":"email",
         "required":true,
         "provided":false
      },
      {  
         "fieldName":"postalCode",
         "required":true,
         "provided":true,
         "transport":"recognize",
         "valid":true
      },
      {  
         "fieldName":"taxId",
         "required":false,
         "provided":false
      },
      {  
         "fieldName":"language",
         "required":false,
         "provided":false
      },
      {  
         "fieldName":"coupon",
         "required":false,
         "provided":true,
         "transport":"recognize",
         "valid":true
      },
      {  
         "fieldName":"account",
         "required":false,
         "provided":false
      }
   ],
   "gift":false,
   "postalCode":"68512",
   "availablePaymentMethods":[                     // array listing which payment methods are currently available based on session detail such as cart contents and order country
      "wire",
      "paypal",
      "card",
      "purchaseorder",
      "amazon"
   ],
   "language":"en",                                // current session language (based on browser default or user selection)
   "expires":1550961521056,                        // expiration date of the current session
   "messages":[  
   ],
   "selections":true,
   "tags":{                                        // order-level custom tags
      "key1":"value1"
   },
   "creationTime":0,
   "serial":"H4sIAAAAAAAAAJWURbKE2BZFB0RUoIk0qoG7a9LD3S7wkKjB_5zCb54dp7W22KCsgF_te7fM_NhV8-Ef2VH9gyEog2AY-t_HgNSpbxvJ7Kg6ru2QOTVkmceo4nziSaKewXIuKfD8Ye3wtj-AnxWbQFUoLBRqkV0wEUdzd29qPGmYYCUtrtwwgjUz4V5aDbNnLnsTXSkH1IIS0IKv-t_nOxushE7dxQF_WWgbjSbxGm52V1hB6baDrEOfv4PS_CNGJNP7DbdCk57TbTBnUaD2pG_DTQBo_bcuSO4G_ldT4u4OnyvKLZksi1YUOdOVeP4YbbvXGYEdK44-cdD2O7vThChWMqTzKNz077biJ4peXxUvEAgixmtGxE13hCNKW1MzXYO72JvYQDWjYrOHeGBAWil3C3m8keAU7_gdqTqo28iHYHyym1XRIidKagjivHjvDpqfWsldaRayAmb5ujCWcsZdS7WaquFAUo1Ias051PBo0r4rlglcCQjOnn9xt7dcvlXTa-riakbVDoNuWCT76OHZ4mrEBeYcYUJ8OzrxJijNX7Q_P1UiXYCNvk8_f1mMNqaVoW_DbTWomx18f2xtWWdAcH45ZIbhSj4aBaXgNjhouFz9w7YU_j_4-yjOEq5zxWoZL9ZmR5KE_XHDC10ZyeC4T09G2gL3_TysAZrP5XEvraGLsGpn-AsAtmZsUicqcFWG617DPQ2uejRJlETHodyweHS7JnCPI3ZiwT8PvgEKHfWQ0AxutpddWCd7LpDipzsonRU7Lz9ne98QGZMJbiZO6LuhWj0w1dyXw1HCNQ6mQ2IvvPAuOv2cdIOQlGwvJplZLSMG_csJVgsFXev2cbuHJfMjKh70RS0EHqTSsUWPMhqIeQZJkryjKdB4TJQPd-CvwRo7GxDb1xKU9Phm-ydZSUGfBNZTbk6DGhGPBDxMOkAp-0y2EUWzU1XN1tJoc6_TawRou1JOnOSJzB_acsJkYcUzu_2VL6VGwbWCSSSu0gGDFjfjiwNF633hTLsCPLdeF7rmhXUXoAjBQyTjdIpEF35d_tq6jR8EYTr7aEjeLBHpdCbIOjzSSbyYPlaCm3lOeB7V3qVP1CTcbHIGrQBM7zncZuOiBvwDn_3gGXCUrXvA4sukx_UHueU8UY9qrcVyqjIjyrHcbxQRs_Zv7sxRdbSwnXh5llGS9IoJIeSXNQQMF1Ify1LOlkD77rGPCiEmBOH43IG-6Oge0qhXW1Ofsl53SY2qsKTEfUJQHTvW5XX3XEFVGPhDxb-bxlDD4TeNmiNGJl23rp0fNj2YFOP7CsglUptgoXRZABqxjZySIllAngOO9Zcr03UMRIyxlzuTgi7_lf0u0wp3UTwlhzr58FRxU7LuOQ7bHPDj77DvTJptfDaH-AOs4mZeXNhjN6i9Rfo2hk3L6FtcwzGqyllp9l30HTXOMc9SUvskAhHG03yGdHqHlOQgYp_1Ql6BeBP1at3yDIlJP83cIoFwHfZTNZobljT_IDpQ0fTMpSUvXN4i3n3q92QXVDAbXgANjhoiB_aQyngaagaeAz2ojFX24hs8n2hUD1OU220aU3lPJA1PRTR9MH9rv6PogJovgQNVLETLWPBiN1hYqZSwqBWmceSghMJWW0RY9G_rQo0s2-NzXQO2C0frUkmR--wuzR51NyyET-NsSChFQyN6h6Yzc743hkcq1QWb4tNuWf0BXFfo7oc1JySThqppcnxRP5DRZmS7-1kcIslK1XR1Vj2uOe4Mk9VpRtLXjHtNpIt6i14JSGZpvjVYLEekO9eKng_EWSYqRGKkVZBsUkVYpXhHwc6iL7Lwoie_oeNRUOO2HvQFV7GDyFyzs9hsIFqXEo2LIDqsZJPZApz6k1FKX61WMkTdVX-uG-HQNlUukW6fcQzHeb6hc8IJ0CG3Qu_7y2ToLIc3-czdjBP--6h3_phveaf5nOpyXQUxM0ui_Md51gR2hHqEeMiFrZQun_mQSGCahDI0CstT70PizaD0btD6zZMQ1Tfqjf1ex_6xK_kWfa-LS_6xBo3bCZ3hAM3ayVjVmnn5QS7MnDiH4v2mOLUl47w1mtPe5PEbbwnvX8qhtuBUsEqGZTVq-lu7KREt2PIp_Yaqz8G201oZpvVyMK8ukb-ljqgnGxc2ZjJo_iJC1yb5V58TSYbwllDw3ygE4wkLt0jiti7q0Z_tAmvcldeYy82j4i4ZDKVhhuLSBvTHDfIN5nSqMSXiuGM0rXx8LPBC2H8pcpgQTb5dQ-MsaileOCIHX1XSGjLF5lbBVoAbjDj_NII4YFhtPqwr5vIqmK88_Wb7tZILSablfWMOKeOK9odn2FaMCOT0gFhrOh-QQK4O_c5RSAb2VhflY5jZRQpnq5lfWc3jJCjdTiww7ttwVWMycH5jd7I2DO70cYZiKd3WmsF3dNbfO1N70KHxtEmJxy5mUbm2Rh5ahsfiWcKICR6sSO74ibFYWsuf4bK6nf39-ZuZyC7mCEuo5qmjZlk2NfUQThuotgWHLg90aIEyt5eqId7aGUzff_8HiXdKk80JAAA"
}

The easiest way to interact with the Store Builder Library once it has been placed on the website is to add "Markup directives" to HTML tags, as described in this article. 

The Library scans HTML contents of the page for markup directives. It applies corresponding data and events once directives are recognized.

Markup Basics

The markup directives allow your web page to "read" various bits of data from the Library and "set" variables or perform cart operations. Directives are available to access both product-level and order-level data.

All directives have the prefix "data-fsc-", which helps the Library to identified elements expecting interaction. There are few types of markup directives:

This example makes it easy to understand how different types of directives work with each other:

<p>Promo code: <input type="text" data-fsc-order-promocode data-fsc-promocode-value /></p>

<p>Apply promo code <input type="button" class="btn" data-fsc-action="Promocode" value="Apply Promo Code" /></p>

<p>Currently applied Promo code:</label><span data-fsc-order-promocode></span></p>

In this example: 

As you can see, "getters" and "setters" can be used on the same element – in this case, the value is placed and read from the same element. 

In general, all "data-fsc-*-value" directives tell the Library that data should be "read" from this directive.

Elements

Markup directives are "smart" and will act differently when placed to different HTML elements. For example:

Product-Level Markup Directives

 Live Interactive Examples

Check out our interactive, hands-on examples at https://www.fastspringexamples.com.

The coupon code example above shows a simple "order" level directives – only one coupon can be applied to the order. However, sometimes you will need to manipulate with specific products:

To address those cases, the Library provides support for product level markup directives:

<span data-fsc-item-path="example1" data-fsc-item-pricetotal data-fsc-smartdisplay></span>

<span data-fsc-item-path="example1" data-fsc-item-total></span>

<a href="#" data-fsc-item-path-value="example1" data-fsc-action="Add" 

data-fsc-item-path="example1" data-fsc-item-selection-smartdisplay-inverse>Add to Cart</a>

<a href="#" data-fsc-item-path-value="example1" data-fsc-action="Remove" 

data-fsc-item-path="example1" data-fsc-item-selection-smartdisplay>Remove from Cart</a>

 

Along with product-level directives this example covers advanced capabilities of the Library:

A combination of the above allows for advanced manipulation with products:

<a href="#"

 data-fsc-item-path-value="example1" data-fsc-action="Add" 

 data-fsc-item-path="example1" data-fsc-item-selection-smartdisplay-inverse

>Add to Cart</a>

The first pair (data-fsc-item-path-value="example1" data-fsc-action="Add") instructs the Library to add product "example1" to the cart when clicked – when "Add" action is invoked it will look for the "data-fsc-item-path-value" directive in the same element. 

The second pair (data-fsc-item-path="example1" data-fsc-item-selection-smartdisplay-inverse) instructs library to only show the whole element if item defined in the "data-fsc-item-path" is not in the cart. 

This flexibility allows you, for example, to show and hide elements on the page based on products in the cart. 

Here's how this combination might look like on a store without a discount applied:

And, this is how it looks with a discount applied:

Here are all available product level directives:

Order-Level Directives

In the "Markup Basics" section of this article, we analyzed an example of a "order-level" directive. Order-level directives do not require a specific product path to be defined on the element because they apply to the order in general. Here are all available order-level directives:

Actions

The data-fsc-action directive allows you to assign various cart-related actions to buttons and links. Actions can also be order or product level:

 Note

To take advantage of the latest directives and actions, ensure that your page is using the most current version of Store Builder Library (currently SBL version 0.8.3). To update the version of SBL that your page uses, update the version number within the URL in the src directive of the script that loads SBL (e.g., https://d1f8f9xcsvx3ha.cloudfront.net/sbl/0.8.3/fastspring-builder.min.js).

You can chain actions together by separating them with commas: 

<a href="#" data-fsc-action="Reset,Add,Checkout" data-fsc-item-path-value="example1">Purchase Example 1</a>

In the example above, when a customer clicks the "Purchase Example 1" link, the cart will be reset, Example 1 will be added to the cart, and the customer will be directed to checkout.

FastSpring's Store Builder Library (SBL) is a JavaScript library that advanced businesses can use to add ecommerce features to a website. For example, you can use SBL to create a complete, full-featured cart that blends with your website design. With the SBL, you can:

Get Started

Using the library is similar to using Google Analytics scripts or integrating with Facebook's SDK. You must have basic HTML and JavaScript knowledge to get started. After it it is referenced and configured on your webpage, the library provides you with two ways of interacting with data:

Whichever way you choose, you need to start by referencing the library on your page and making sure that the data is loading successfully.

For interactive examples and implementation guidance we recommend exploring fastspringexamples.com and http://fastspring.github.io/playground/

Store Builder Library must be initialized with a specific Storefront. The Storefront specified in the data-storefront attribute of the SBL script is used when the consumer is ready to check out. Products associated with the Storefront are available in the data returned by the FastSpring backend to the Store Builder Library.

Use either a Web Storefront or a Popup Storefront with the Store Builder Library. The two types of Storefronts offer the same behavior and the same types of data via SBL. The only difference is what happens when the buyer initiates checkout.

For Popup Storefronts: If you plan to use a Popup Storefront, make sure to whitelist domains where the Popup Storefront will appear. All of your domains (including those you use for testing and development) must be whitelisted.
 
Additionally, we recommend that you deploy a security certificate and use the HTTPS: protocol for your website. Otherwise, most web browsers will not display a closed padlock icon, and some may display warning messages about non-secure pages. See Popup Storefronts and Browser Security Features for more information.

Select Products that will be Accessible via the SBL

If you would like to display dynamic, localized product pricing and descriptions to your consumers, you need to configure which products SBL can access. This scope of available products directly correlates to the Storefront specified when you initialize the library. To control this scope:

For Web Storefronts:

  1. Select Storefronts > Web Storefronts.
  2. For the Web Storefront you have chosen to use with the library, click Homepage. The Homepage Products dialog appears.

If you use a Web Storefront, keep in mind that this process also controls which items appear on the Homepage of the Storefront. For more information, see Choosing Products to be Displayed on the Storefront’s Homepage. If you plan to send some consumers to the homepage of a Web Storefront separately from your SBL, create a separate Web Storefront for use with the library. 

For Popup Storefronts

  1. Select Storefronts > Popup Storefronts.
  2. For the Popup Storefront you have chosen to use with the library, click Products. The Homepage Products dialog appears.

The Popup Storefront does not include a Homepage or product catalog. However, adding products via the Popup Storefront’s Homepage Products dialog makes them available in the library’s data. This lets you reference the products when accessing the library from HTML, and while using JavaScript.
 
Adding products to the Popup Storefront is only necessary if you want to display product attributes (price, display name, icon) on your SBL page. You can initiate checkout for any product ID in the Store, regardless of whether or not you have added it via the Popup Storefront’s Homepage products dialog.

Homepage Products Dialog

In the Main Products field, begin typing the name of the first product you want to add. Repeat this process to add any additional products that you want to make available to the library. 

Initialize the Library

After choosing the Storefront and selecting available products, you can insert the library into each page where you want to use its features. For interactive examples, see FastSpring Examples.

Get the Latest Library Code

Navigate to the Storefront of your choice, then:

We recommend keeping your links to the SBL updated with the latest library URL to take advantage of the latest features and improvements.

Third-Party tools that attempt to compress, concatenate, or defer JavaScript loading interfere with initializing the SBL. For example, the Rocketscript tool from Cloudflare may modify your script that loads the SBL like:
<script id='fsc-api' data-rocketsrc="https://d1f8f9xcsvx3ha.cloudfront.net/sbl/0.8.3/fastspring-builder.min.js">.
This likely will not work since the Store Builder Library does not support data-rocketsrc. To ensure the Store Builder Library loads successfully, avoid using these tools on pages that load the library.

Use Advanced Features

The code provided via the FastSpring App is limited to a simple reference. To use advanced features, provide additional data and register callbacks:

Store Builder Library Code Example

<script
  	id="fsc-api"
	  src="https://d1f8f9xcsvx3ha.cloudfront.net/sbl/0.8.3/fastspring-builder.min.js"" type="text/javascript" 
  	  data-storefront="vendor.test.onfastspring.com"
	  data-data-callback="dataCallbackFunction"
	  data-error-callback="errorCallback"		
	  data-before-requests-callback="beforeRequestsCallbackFunction"
	  data-after-requests-callback="afterRequestsCallbackFunction"            
	  data-before-markup-callback="beforeMarkupCallbackFunction"
	  data-after-markup-callback="afterMarkupCallbackFunction"        
	  data-decorate-callback="decorateURLFunction"
	  data-popup-event-received="popupEventReceived"
	  data-popup-webhook-received="popupWebhookReceived"
	  data-popup-closed="onPopupClose"		
	  data-access-key=".. access key .."        
	  data-debug="true"    
	  data-continuous="true">
</script>

Full Code Reference

If you are providing callback functions to be called by the library, the functions must exist on the page when the library is loaded. Make sure to include the function (or the JavaScript file that contains the function) in your webpage in a place that will be loaded before the SBL calls are made.

Store Builder Library (SBL) allows a variety of Store implementation options and checkout flows. Use SBL to perform basic operations like cart manipulation, load coupon codes, or provide known customer details. SBL also allows you to generate advanced checkout sessions that might contain authenticated customer data or custom product pricing. These advanced options are useful when building customized checkout flows and they imply the use of local data encryption.

An example of how to use secure requests is to provide customers with a name your price or pay what you want option. Design your website to accept price data from your customers and use a secure payload to override the default prices. You can also enable custom pricing with the /sessions endpoint of the FastSpring API.

 

Process Overview

The process of passing data securely using SBL involves three steps:

  1. Creating a session object containing customer and product data
  2. Encrypting the session object locally to protect the data that is to be transmitted
  3. Passing the encrypted payload to FastSpring

FastSpring instantly decrypts the payload upon receipt and applies the decrypted data to the customer's session.

Since JavaScript and other client-side methods are inherently not secure, you must encrypt the sensitive data before passing it to FastSpring. Without a securely encrypted payload, SBL will not accept certain types of session data, such as product price overrides. Thus, even if an adversary were to intercept the data, they could not send FastSpring a modified payload (e.g., with a price of $0.00) without access to the encryption key.

Although you may make tests using raw/unencrypted data, live orders using the secure methods require encryption. Remember to set up encryption and pass only encrypted payloads before going live with these methods. See Passing an Encrypted Payload to the Store Builder Library, later on in this article, for more information.

 

Pass Customer Information to be Applied to the Order in the Secure Payload

Our articles Customer Information, Accounts and single sign-on and Using Store Builder Library to Provide Customer Details can help you familiarize yourself with the concept of Customer Accounts and various options around applying customer information.

When you have authenticated your customer and your backend is aware of customer details, you can pass the details to the checkout process.

Payload Example
When passing contact information via the secure payload, your payload must include emailfirstName, and lastName at a minimum. If you only have the customer's email address, and you do not need to pass sensitive data such as product price overrides, consider using the session object instead of a secure payload.

Important: When using a secure payload, FastSpring validates customer details provided inside the contact object upon submission. If the data does not pass validation, the Store treats the data in the same way as a fastspring.builder.recognize() call. In this case, the data is pre-filled, but fields are visible and editable during the checkout. This approach allows customers to correct their mistakes. However, in the case of address fields, if your Storefront is not configured to display those fields, the customer does not see the fields and so cannot correct the problem. Therefore, if address validation is important to your business, we encourage you to do one of the following:

As an alternative to encrypting the data and passing it on the frontend, you can use the /accounts endpoint of the FastSpring API to create or modify accounts from the backend. The account ID obtained in the /accounts response can then be used with the /sessions endpoint to create a complete session. However, a mixed approach is not possible. If you pass both an account ID and the contact object in your SBL payload, the Store ignores the contact object in favor of the established account details.

Pass Gift Recipient Information to be Applied to the Order in the Secure Payload

This method automatically selects the Gift Purchase checkbox in the checkout form and allows you to pass authenticated recipient information to the library, so that Recipient Information fields of the order form are pre-filled and not displayed to the customer (pending validation).

Payload Example

 

Pass Product Information in the Secure Payload

This approach is useful when you want to change a product's price for a specific customer. For example, this might be the case with special pricing or price A/B testing. To do this, you can use "tags" and "attributes" to pass experiment/variation IDs. Tags provide a way to assign arbitrary key/value pairs to the order and "capture" them later in webhooks and API responses.

When passing the pricing object for a subscription product in your payload, be sure to include trialintervalintervalLength, and intervalCount. Passing the pricing object overrides the product's existing pricing data. Therefore, if you pass the pricing object without subscription details, the product is processed as a stand-alone, single-payment product.
Payload Example

You can pass customer, recipient, and product information together in a single payload.

 

Pass Other Order Details in the Secure Payload

In addition to customer and product information, you can also optionally pass the following order details via the secure payload:

Payload Example

 

Authenticate Customers to Redirect to Account Management

If you have the customer's FastSpring account ID on record, you can generate a temporary, pre-authenticated account management URL. This process lets you create single sign-on functionality so that the customer can log on to FastSpring's account management site without an extra validation step.

Encrypt the following JSON on the backend:

Then, call the fastspring.builder.authenticate(securedData, secureKey) method, passing the secure data and the secure key as described below. The customer will be redirected to the account management page and logged on automatically.

 

Flow

  1. Generate a Private/Public key pair.
  2. Build a JSON object (as a string) that contains the required data/actions on your backend.
  3. Generate a "Secure Key" and encrypt the JSON object (as a string) using the Private key.
  4. Pass the resulting strings (the encrypted payload and the secure key) to your frontend and assign them to JavaScript variables.
  5. Make sure your webpage provides the "data-access-key" when initializing the Library; otherwise, the secure payload won't be sent. 

 

Create Encrypted Payloads

Set Up Encryption

  1. In the FastSpring App, select the Integrations menu and the Store Builder Library tab. 
  2. Copy the Access Key. This is the access key with which you will initialize the library via "data-access-key".
  3. Create a Private/Public certificate pair (see instructions below). Under File Upload, click Choose File and browse to and select the file containing your public certificate.
  4. Click Save.

 

Generate the "securePayload" and "secureKey"

One-Time-Only – Create Private and Public Keys

openssl genrsa -out privatekey.pem 2048

openssl req -new -key privatekey.pem -x509 -days 3650 -out publiccert.pem

 

Create your "Secure Key" and "Secure Payload" for Each Request

When preparing a secure request, encrypt your generated payload.

Using Node.js

 

Using Java

 

Using PHP

You can also download the working example from here: encryption.php

FastSpring uses your secureKey string and publiccert.pem to decrypt your securePayload string.

 

Pass an Encrypted Payload to the Store Builder Library

Option 1: Build the session object before the API is initialized

This method implies understanding the concept of the session object. Refer to Accessing the Library from Javascript for more information.

This method works best if a secure payload is available to the page at the moment the page loads. This way, you apply the data in the first Library call to the server.

 

Option 2: Use the fastspring.builder.secure() method after the API is initialized

 

Test Secure Payloads

To simplify the testing process, "Test" storefronts accept unencrypted payloads. Each Storefront can be used in both Live and Test modes simultaneously. For example:

To test your payload: