• Stars
    star
    121
  • Rank 293,924 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

BigCommerce Checkout JavaScript SDK

@bigcommerce/checkout-sdk

Checkout JS SDK provides you with the tools you need to build your own checkout solution for a BigCommerce store.

The SDK has a convenient application interface for starting and completing a checkout flow. Behind the interface, it handles all the necessary interactions with our Storefront APIs and other payment SDKs. So you can focus on creating a checkout experience that is unique to your business.

Table of contents

Features

The Checkout JS SDK is a client-side JavaScript library for our Storefront Checkout API. It provides all the methods that are required to complete a checkout process, for example:

  • Sign in a customer and begin the checkout process
  • Set shipping, billing and other required information
  • Pay for the order and complete the checkout process

The library also provides integrations with all the payment methods supported by Optimized One Page Checkout, such as:

  • PayPal Express
  • Braintree
  • Square
  • Amazon
  • Klarna
  • AfterPay

Using this library in conjunction with your favorite UI framework, it is possible to build a bespoke checkout UI for a store, that can be augmented with additional features. With Bigcommerce's Open Checkout, we provide Checkout JS as our reference implementation of a checkout written in React to get you started.

Getting started

The Checkout JS SDK is the easiest way to build a bespoke checkout into your store’s theme. We have created the following tutorials to help you get started.

  • Open Checkout Quick Start - In this quick start tutorial, we’ll configure our development environment and make a code change to a fork of BigCommerce’s Open Checkout.
  • Installing Custom Checkouts - This article will outline how to package a custom checkout file, and install a custom checkout via the control panel.

Installation

Using NPM package

You can install this library using npm.

npm install --save @bigcommerce/checkout-sdk

Using CDN URL

You can also use this library by referencing a CDN URL.

https://checkout-sdk.bigcommerce.com/v1/loader.js

The main benefit of using the script URL above is that your application can automatically receive backward compatible updates and bug fixes from us, without having to manually perform an upgrade.

Once the above script is loaded, checkoutKitLoader instance will be available in the window and you can use it to load the module that you need for your application. i.e.:

const module = await checkoutKitLoader.load('checkout-sdk');
const service = module.createCheckoutService();

Currently, there are three modules available for public use:

  • checkout-sdk: This is the main module that contains all the public exports of the package.
  • checkout-button: This sub-module can be used to initialize checkout buttons in the storefront once a cart is created (i.e.: cart page).
  • embedded-checkout: This sub-module can be used to embed our Optimized One-Page Checkout in non-native storefronts (i.e.: Wordpress).

Please refer to the usage guide below for more information on each of them.

Requirements

Browser support

We release the library in ES5 so you don't have to do additional transpilation in order to use it. However, you do require the Promise polyfill if you need to support older browsers, such as IE11.

On the other hand, the CDN version already contains the necessary polyfill for it to work in IE11.

Framework

The library is framework agnostic. In other words, you can use it with any UI framework or library you want.

CORS

As our Storefront Web APIs currently don't support CORS, you will not be able to use the library outside of a BigCommerce store.

Usage

Below is a guide on how to use this library.

Initialize instance

First, you have to create a CheckoutService instance.

import { createCheckoutService } from '@bigcommerce/checkout-sdk';

const service = createCheckoutService();

Load checkout

Once you have the instance, you should load the current checkout and present the information to the customer.

const checkoutId = '0cfd6c06-57c3-4e29-8d7a-de55cc8a9052';
const state = await service.loadCheckout(checkoutId);

console.log(state.data.getCheckout());

The checkout object contains various information about the checkout process, such as the cart, the grand total etc... Once the data is loaded, you can retrieve it by calling the getters provided by the state object.

console.log(state.data.getCart());
console.log(state.data.getBillingAddress());
console.log(state.data.getShippingAddress());

In addition, you can also access the store's checkout configuration. The configuration object contains information about various settings related to checkout, such as the default currency of the store etc...

console.log(state.data.getConfig());

Sign in customer

Before you can collect other checkout information from the customer, you should first ask them to sign in. Once they are signed in, the checkout state will be populated with their personal details, such as their addresses.

const state = await service.signInCustomer({ email: '[email protected]', password: 'password123' });

console.log(state.data.getCustomer());

Alternatively, you can ask the customer to continue as a guest. Note that in this scenario, the email is stored as part of the billing address, but is also accessible via the cart object.

const state = await service.continueAsGuest({ email: '[email protected]' });

console.log(state.data.getCart().email);
console.log(state.data.getBillingAddress().email);

Passwordless Sign-in

Customers could sign in using a single-use link sent to their email address. Once they click on the link, they will be redirected back to the store as a signed-in user.

Learn more about it at CheckoutService#sendSignInEmail

Continue as guest

If your checkout settings allow it, your customers could continue the checkout as guests (without signing in).

const state = await service.continueAsGuest({ email: '[email protected]' });

console.log(state.data.getBillingAddress());
console.log(state.data.getCustomer());

Learn more about it at CheckoutService#continueAsGuest

Set shipping details

Set shipping address

To set a shipping destination for the checkout, you should ask the customer to provide an address. To do that, you need to render a set of form fields for collecting their details. The set of fields also includes all the custom fields configured by the merchant.

const fields = state.data.getShippingAddressFields();

fields.forEach(field => {
    console.log(field);
});

To set the shipping address, you can collate all the address fields and construct a request payload.

const address = {
    firstName: 'Test',
    lastName: 'Tester',
    address1: '12345 Testing Way',
    city: 'Some City',
    stateOrProvinceCode: 'CA',
    postalCode: '95555',
    countryCode: 'US',
    phone: '555-555-5555',
    email: '[email protected]'
};

const state = await service.updateShippingAddress(address);

console.log(state.data.getShippingAddress());
console.log(state.data.getShippingOptions());

Set shipping option

Once the address is provided, you can get a list of shipping options available for the address and the cost for each option.

Then, you can ask the customer to select a shipping option from the list.

const address = state.data.getShippingAddress();
const options = state.data.getShippingOptions();
const state = await service.selectShippingOption(options[address.id].id);

console.log(state.data.getSelectedShippingOption());

Set billing details

In order to complete the checkout process, you also need to collect a billing address from the customer.

const state = await service.updateBillingAddress(address);

console.log(state.data.getBillingAddress());

Apply coupon or gift certificate

You may also want to accept any coupon code or gift certificate provided by the customer.

const state = await service.applyCoupon('COUPON');

console.log(state.data.getOrder().coupon);
const state = await service.applyGiftCertificate('GIFT');

console.log(state.data.getOrder().giftCertificate);

You can also allow the customer to remove any coupon code or gift certificate previously applied.

await service.removeCoupon('COUPON');
await service.removeGiftCertificate('GIFT');

Execute spam protection check

You can also enable bot protection to prevent bots and other types of automated abuse from creating orders. Note that enabling this feature increases checkout friction, which may affect conversions. As such, we recommend leaving this feature out if your store is not encountering bots.

await service.executeSpamCheck();

Learn more about it at CheckoutService#executeSpamCheck.

Submit payment and order

Load payment methods

Before you can place the order, you need to collect payment details from the customer. In order to do that, you must first load and present a list of available payment methods to the customer.

const state = await service.loadPaymentMethods();

console.log(state.data.getPaymentMethods());

Initialize payment method

After that, you should initialize the payment method so they are ready to accept payment details.

await service.initializePayment({ methodId: 'braintree' });

Some payment methods require you to provide additional initialization options. For example, Amazon requires a container ID in order to initialize their payment widget. Otherwise, they will not work properly.

await service.initializePayment({
    methodId: 'amazon',
    amazon: {
        container: 'walletWidget',
    },
});

Submit order

And then, you can ask the customer to provide payment details required by their chosen payment method. If the method is executed successfully, you will create an order and thereby complete the checkout process.

We may require human verification to be completed before payment can be processed, which will be handled during this step.

const payment = {
    methodId: 'braintree',
    paymentData: {
        ccExpiry: { month: 10, year: 20 },
        ccName: 'BigCommerce',
        ccNumber: '4111111111111111',
        ccType: 'visa',
        ccCvv: 123,
    },
};

const state = await service.submitOrder({ payment });

console.log(state.getOrder());

window.location.assign('/order-confirmation');

If the submission is successful, you should redirect the customer to the order confirmation page.

Finalize order

Also, for some payment methods, the customer may be asked to enter their payment details on an external website. For these methods, you must finalize the order when the customer is redirected back to the checkout page in order to complete the checkout flow. This should be done in the background before you present any checkout information to the customer.

await service.loadCheckout();

try {
    await service.finalizeOrderIfNeeded();

    window.location.assign('/order-confirmation');
} catch (error) {
    if (error.type !== 'order_finalization_not_required') {
        throw error;
    }
}

// Render the checkout view

Similarly, if the order finalization is successful, you should redirect the customer to the order confirmation page.

Load order

Once the order is created, you can make a call to retrieve it. This should be done on the order confirmation page so that you can present the final order to the customer.

const orderId = 123;
const state = await service.loadOrder(orderId);

console.log(state.data.getOrder());

Subscribe to changes

Your UI should react to changes to the checkout state. When there is a change, you should present the latest information to the customer. You can do that by subscribing to the checkout state.

The subscriber gets triggered every time there is a change in the state. If the change affects your view, you should re-render it in order to reflect the latest update. The subscriber provides a state object which you can use to get specific checkout information. It also provides meta information such as loading statuses, error details etc...

service.subscribe(state => {
    // Return the current checkout
    console.log(state.data.getCheckout());

    // Return an error object if unable to load checkout
    console.log(state.errors.getLoadCheckoutError());

    // Return `true` if in the process of loading checkout
    console.log(state.statuses.isLoadingCheckout());
});

If you are only interested in certain parts of the state, you can filter out irrelevant changes by providing a filter function to the subscriber.

const filter = state => state.data.getCart();

service.subscribe(state => {
    console.log(state.data.getCart())
}, filter);

You can retrieve the same state object outside of a subscriber if there is a need for it.

const state = service.getState();

console.log(state);

Cancel requests

If you need to cancel a request before it is complete, you can provide a Timeout object when making the request. An example use case might be to implement a UI that updates the shipping address whenever there is a change - so you want to abort any pending requests and only take the latest one.

import { createTimeout } from '@bigcommerce/checkout-js-sdk';

const address = { countryCode: 'US' };
const timeout = createTimeout();

service.updateShippingAddress(address, { timeout });
timeout.complete(); // Aborts the update

API reference

We provide an extensive API reference.

The functions provided by the SDK are:

See also

  • Checkout JS - This is our reference implementation of a checkout built using the Checkout JS SDK.
  • Storefront APIs - The documentation for Storefront Checkout & Cart Web APIs.

Notes

  • If you are using this library on the checkout page of a Stencil theme, you must have Optimized One Page Checkout enabled. Otherwise, you will not be able to preview your changes.
  • You should only use this library on a HTTPS page unless you are developing locally.
  • In order to keep up to date on the latest changes, please subscribe to this repository by clicking on the watch button.

Contribution

We actively maintain and add new features to the library in order to support our official checkout (Optimized Checkout). But we also accept contributions from the community.

If you want to contribute, please refer to the contribution guide.

License

MIT

More Repositories

1

gruf

gRPC Ruby Framework
Ruby
561
star
2

cornerstone

The BigCommerce Cornerstone theme
HTML
282
star
3

sass-style-guide

Sass coding guidelines for BigCommerce themes
CSS
280
star
4

storefront-data-hooks

Hooks for React Storefront UI Components
TypeScript
166
star
5

bigcommerce-api-php

Connect PHP applications with the Bigcommerce Platform
PHP
143
star
6

gatsby-bigcommerce-netlify-cms-starter

Example Gatsby, BigCommerce and Netlify CMS project meant to jump start JAMStack ecommerce sites.
CSS
118
star
7

bigcommerce-for-wordpress

A headless commerce integration for WordPress, powered by BigCommerce
PHP
106
star
8

checkout-js

Optimized One-Page Checkout
TypeScript
102
star
9

catalyst

Catalyst - for Composable Commerce
TypeScript
100
star
10

stencil-cli

BigCommerce Stencil emulator for local theme development
JavaScript
100
star
11

bigcommerce-api-python

Python client library for Bigcommerce API
Python
83
star
12

bigcommerce-api-ruby

Connect Ruby applications with the Bigcommerce Platform
Ruby
77
star
13

laravel-react-sample-app

Sample BigCommerce App Using Laravel and React
PHP
69
star
14

gruf-demo

A demonstration Rails application utilizing gruf, a gRPC Rails framework.
Ruby
57
star
15

bc-nuxt-vue-starter

A starter site for Vue + Nuxt based storefronts that uses Divante's Storefront UI and BC's GraphQL API
Vue
51
star
16

sample-app-nodejs

A reference implementation of a BigCommerce single-click app, in Node.JS + Next.js/React
TypeScript
43
star
17

big-design

Design system that powers the BigCommerce ecosystem.
TypeScript
42
star
18

dev-docs

This repo contains the markdown files and static assets powering developer.bigcommerce.com. https://developer.bigcommerce.com/
41
star
19

api-specs

OpenAPI Specifications, Swagger, and JSON schema used to generate the human-readable BigCommerce API Reference.
Python
34
star
20

stencil-utils

Utility library for the Stencil theme framework.
JavaScript
33
star
21

hello-world-app-python-flask

Hello World sample app in Python and Flask
Python
31
star
22

b2b-buyer-portal

B2B Buyer Portal - BigCommerce B2B Edition
TypeScript
25
star
23

grphp

PHP gRPC Framework
PHP
24
star
24

hello-world-app-php-silex

Hello World sample app in PHP and Silex
PHP
23
star
25

gruf-rspec

RSpec helper suite for gruf
Ruby
20
star
26

script-loader-js

A library for loading JavaScript files asynchronously
TypeScript
17
star
27

channels-app

TypeScript
13
star
28

omniauth-bigcommerce

OmniAuth Bigcommerce Strategy
Ruby
13
star
29

storefront-api-examples

Example of using the GraphQL Storefront API to power a static site using Bootstrap and VanillaJS
HTML
12
star
30

paper

Paper assembles templates and translations and renders pages using backend template engines
JavaScript
11
star
31

subscription-foundation

Foundation for building custom subscription applications w/ BigCommerce
TypeScript
11
star
32

net-http

A basic HTTP client.
PHP
11
star
33

ai-app-foundation

TypeScript
10
star
34

widget-builder

TypeScript
10
star
35

hello-world-app-ruby-sinatra

Hello World sample app with Ruby, Sinatra and DataMapper
Ruby
10
star
36

paper-handlebars

Paper plugin for rendering via Handlebars.js
JavaScript
9
star
37

docs

The open source docs home for BigCommerce, including API specifications in OAS YAML and narrative docs in MDX
MDX
9
star
38

gruf-circuit-breaker

Circuit breaker support for gruf
Ruby
8
star
39

bigcommerce-api-node

A node module for authentication and communication with the BigCommerce API
TypeScript
7
star
40

gruf-newrelic

New Relic tracing for gruf services
Ruby
7
star
41

point-of-sale-foundation

Foundation for building custom POS applications w/ BigCommerce
TypeScript
7
star
42

gruf-prometheus

Gruf plugin for Prometheus support
Ruby
5
star
43

gruf-profiler

Profiler for gruf-backed gRPC requests
Ruby
5
star
44

gruf-zipkin

Zipkin tracing plugin for Gruf
Ruby
5
star
45

gruf-commander

Command/Request library for Gruf request validation
Ruby
5
star
46

php-resque-pause

An addon for php-resque, php-resque-pause adds functionality to pause resque jobs.
PHP
5
star
47

data-store-js

A JavaScript library for managing application state
TypeScript
5
star
48

stencil-styles

Compiles SCSS for the Stencil Framework
HTML
5
star
49

form-poster-js

Post HTML form programmatically
TypeScript
5
star
50

netlify-nextjs-starter

TypeScript
4
star
51

mock-injector

Auto-mocking dependencies for DI components testing.
PHP
4
star
52

theme-context-object-schemas

JSON schema used to generate the human-readable BigCommerce Handlebars Reference.
4
star
53

gruf-lightstep

LightStep tracing for gruf
Ruby
4
star
54

validate-commits

Commit message validator
JavaScript
4
star
55

gruf-sentry

Sentry integration for gruf
Ruby
3
star
56

request-sender-js

HTTP request client for browsers
TypeScript
3
star
57

memoize-js

A JavaScript library for memoizing the result of a pure function
TypeScript
3
star
58

stencil-lang-validator

Validate language keys used in templates and scripts
JavaScript
3
star
59

statsd-client

Record timing, increment, and count metrics in StatsD
PHP
3
star
60

injector

Dependency Injector component built on top of Pimple container.
PHP
3
star
61

eslint-config

JavaScript
3
star
62

bigpay-client-js

Bigpay client-side library
JavaScript
3
star
63

stand-with-ukraine-backend

Stand With Ukraine is a BigCommerce application. It allows merchants to easily add a widget to their storefront with a customized message and list of Charities that the merchant would like their shoppers to visit and support.
Rust
2
star
64

bc-lightstep-ruby

Generic lightstep library for distributed tracing in ruby
Ruby
2
star
65

sample-shipping-provider

Silex based reference implementation of a Shipping Carrier Service integration
PHP
2
star
66

nomad-workload-cpu-actuals-report-generator

Groovy
2
star
67

grphp-statsd

StatsD interceptor for measuring grphp client requests.
PHP
2
star
68

tslint-config

Default TSLint configuration used at BigCommerce
2
star
69

noopraven-go

A raven-go interface with a noop implementation.
Go
2
star
70

ruby-rails-react-sample-app

BigCommerce App - Ruby on Rails + React + BigDesign
Ruby
2
star
71

nextjs-contentstack-starter

TypeScript
2
star
72

stand-with-ukraine-frontend

Stand With Ukraine is a BigCommerce application. It allows merchants to easily add a widget to their storefront with a customized message and list of Charities that the merchant would like their shoppers to visit and support.
TypeScript
2
star
73

threatDragon

This repo is for storing threat modelling of BigCommerce projects
1
star
74

gruf-balancer

Percentage-based balancing of gruf-client requests for testing
Ruby
1
star
75

bonvoy

Go utility CLI tool for Envoy and Consul Connect
Go
1
star
76

themes-lib-scroll-link

JavaScript
1
star
77

app-sdk-js

JavaScript
1
star
78

puppet-module-supervisor

Puppet module for configuring the supervisor daemon control utility
Ruby
1
star
79

themes-lib-compare

JavaScript
1
star
80

themes-lib-squid

JavaScript
1
star
81

drupal-module-clientside_validation

Fork of the Drupal clientside_validation module to fix an upstream Internet Explorer bug - http://drupal.org/node/1995314
1
star
82

data-docker-debian-runfromenv

Basic Debian image to run a user-supplied script from the environment.
Shell
1
star
83

optimized-checkout-changelog

Summarises the changes made to the Optimized One Page Checkout Angular application.
1
star
84

themes-lib-loading

JavaScript
1
star
85

themes-lib-swipe-fade

JavaScript
1
star
86

bc-prometheus-ruby

Drop-in support for prometheus metrics for Ruby apps
Ruby
1
star
87

themes-lib-modal

JavaScript
1
star
88

axfr2tf

Converts an AXFR DNS query to Terraform resources
Rust
1
star