SDK Reference 3.x
Version 4 is now available! Check out the Release Notes to read about its exciting new features, and v3.x to v4.x Migration Guide for details on how to upgrade.
Introduction
The Chord client-side Javascript SDK can be installed via a Gatsby theme. It's available as an npm package, @chordcommerce/gatsby-theme-autonomy, via GitHub Packages.
Despite the name, this package does not provide a visual theme. To quote from the Gatsby documentation:
Gatsby themes are plugins that include a gatsby-config.js file and add pre-configured functionality, data sourcing, and/or UI code to Gatsby sites. You can think of Gatsby themes as separate Gatsby sites that can be put together and allow you to split up a larger Gatsby project!
gatsby-theme-autonomy includes the Chord SDK, a set of methods you can import and use in your React components to do things like add items to a cart and check out. The theme also preconfigures your Gatsby site with a number of useful ecommerce features like product feeds and internationalization support.
useAnalytics()
import { useAnalytics } from '@chordcommerce/gatsby-theme-autonomy`
// inside a function componentconst { trackViewCart } = useAnalytics()The useAnalytics hook returns a series of functions that fire a tracking event to Segment, our integrated analytics platform.
Many Segment events are fired automatically by the @chordcommerce/gatsby-theme-autonomy theme. However, some events need to be closely tied to the UI, like click tracking. These events are available via the useAnalytics hook and listed below.
trackClickCollection()
trackClickCollection(title, slug, url)The trackClickCollection function fires a Collection Clicked event to Segment. You should call this function when the user clicks on a link to a collection.
Example
import { Link } from 'gatsby'
import { useAnalytics } from '@chordcommerce/gatsby-theme-autonomy'
export default ({ title, slug, children }) => {
const { trackClickCollection } = useAnalytics()
const url = `/shop/?collection=${slug}`
return (
<Link to={url} onClick={() => trackClickCollection(title, slug, url)}>
{children}
</Link>
)
}trackClickProduct()
trackClickProduct(slug)The trackClickProduct function fires a Product Clicked event to Segment. You should call this function when the user clicks on a link to a product.
Example
import { Link } from 'gatsby'
import { useAnalytics } from '@chordcommerce/gatsby-theme-autonomy'
export default ({ slug, children }) => {
const { trackClickProduct } = useAnalytics()
const url = `/products/${slug}/`
return (
<Link to={url} onClick={() => trackClickProduct(slug)}>
{children}
</Link>
)
}trackCreateStockRequest()
trackCreateStockRequest(email, sku)The trackCreateStockRequest function fires a Stock Request Created event to Segment. You should call this function when a product waitlist form is submitted.
Example
import { useAnalytics } from '@chordcommerce/gatsby-theme-autonomy'
export default ({ sku }) => {
const { trackCreateStockRequest } = useAnalytics()
const onSubmit = ({ email, sku }) => {
trackCreateStockRequest(email, sku)
}
// return sign up form
}trackViewCart()
trackViewCart()The trackViewCart function fires a Cart Viewed event to Segment. You should call this function when the cart page is viewed.
Example
import { useAnalytics } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { trackViewCart } = useAnalytics()
useEffect(() => {
trackViewCart()
}, [])
// return cart page
}trackProductViewed()
trackProductViewed({ product })The trackProductViewed function fires a Product Viewed event to Segment. You should call this function when a product page is opened.
Example
import { useAnalytics } from '@chordcommerce/gatsby-theme-autonomy'
export default (product) => {
const { trackProductViewed } = useAnalytics()
useEffect(() => {
trackProductViewed({ product })
}, [product])
// return product page
}useAuth()
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy`
// inside a function component
const {
isLoggedIn,
isFetching,
token,
getToken,
handleCallback,
login,
logout
} = useAnalytics()The useAuth hook returns information about the current authentication session and functions for logging in and logging out. Chord supports passwordless authentication with Magic.
isLoggedIn
isLoggedIn is a boolean indicating whether the user is currently logged in.
Example
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy`
const { isLoggedIn } = useAuth()
if (isLoggedIn) {
// return component
}isFetching
isFetching is a boolean indicating whether the user's authentication status is currently being fetched.
Example
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy`
const { isFetching } = useAuth()
if (isFetching) {
// return loading animation
}token
token is a string representing the user's authentication token. This token is automatically appended to Chord API requests when the user has an active session.
handleCallback()
handleCallback()The handleCallback function completes the login process, when the user is redirected back to the site after clicking a link in their email. The SDK calls this function automatically when the Magic url parameter is detected on page load, so you are unlikely to need to call this function.
getToken()
getToken()The getToken function retrieves an authentication token for the current user session. While you are unlikely to need the token directly, since the SDK automatically appends it to relevant Chord API requests, you can use this function to check whether the user's session is still active. If the user's session has expired, getToken will throw an error.
You may choose to call getToken on page load or when a user visits a protected route (like an account page) to check that their session has not expired since the last time you checked.
Example
import { useEffect, useState } from 'react'
import { navigate } from 'gatsby'
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy'
const PrivateRoute = () => {
const { getToken } = useAuth()
const [isLoggedIn, setIsLoggedIn] = useState(false)
useEffect(() => {
const checkStatus = async () => {
try {
await getToken()
setIsLoggedIn(true)
}
catch (error) {
navigate('/account/login')
}
}
checkStatus()
}, [getToken])
if (!isLoggedIn) return null
// return protected page
}
export default PrivateRoutelogin()
The login function should be called when a user submits a login form. It will trigger an email to the user for verification.
The showUI option controls whether Magic's default UI will display from when login is called until the user clicks the link they've received in an email.
Example
import { navigate } from 'gatsby'
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { login } = useAuth()
const onSubmit = async ({ email }) => {
try {
await login({ email })
navigate('/some-private-route')
}
catch (error) {
console.error(error)
}
}
// return login form
}logout()
logout()The logout function terminates the user's current session.
Example
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { logout } = useAuth()
return <button onClick={() => logout()}>Logout</button>
}useCart()
import { useCart } from '@chordcommerce/gatsby-theme-autonomy`
// inside a function component
const { cart, addToCart } = useCart()cart
Example
import { useCart } from '@chordcommerce/gatsby-theme-autonomy`
const { cart } = useCart()
const { lineItems } = cart.dataaddPromoCode()
addPromoCode(promoCode)Example
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { addPromoCode } = useCart()
const onSubmit = ({ promoCode }) => {
addPromoCode(promoCode)
}
}addReferralIdentifier()
addReferralIdentifier(referralIdentifier)Example
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { addReferralIdentifier } = useCart()
const onSubmit = ({ referralIdentifier }) => {
addReferralIdentifier(referralIdentifier)
}
}addToCart()
addToCart(sku, quantity)Example
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { addToCart } = useCart()
const onSubmit = ({ sku, quantity }) => {
addToCart(sku, quantity)
}
}checkout()
checkout()Example
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'
import { loadStripe } from '@stripe/stripe-js'
const stripePromise = loadStripe(process.env.GATSBY_STRIPE_PK_KEY, { stripeAccount: process.env.GATSBY_STRIPE_CONNECTED_ACCOUNT })
export default () => {
const { checkout } = useCart()
const onSubmit = async () => {
const cart = await checkout()
const stripe = await stripePromise
stripe.redirectToCheckout({ sessionId: cart.checkoutSessionId })
}
}finalizeCheckout()
finalizeCheckout()This function should be called on the order confirmation page, when the user is redirected back to the site from checking out via Stripe.
Example
import { setState } from 'react'
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { finalizeCheckout } = useCart()
const [cart, setCart] = useState(null)
useEffect(() => {
finalizeCheckout().then(cart => { setCart(cart) })
}, [finalizeCheckout, loadUser])
}forgetCart()
forgetCart()
This function can be called at any time to clear the current order from the session. It is called automatically by finalizeCheckout and logout, so no need to call it in those cases.
Example
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { forgetCart } = useCartuth()
return <button onClick={() => forgetCart()}>Clear order</button>
}loadCart()
loadCart()modifyCart()
modifyCart({ lineItems: [] })modifyQuantity()
modifyQuantity(lineItemId, quantity)modifyLineItem()
Updates a line item in the current order.
const lineItemId = '123'
// update line item quantity
await modifyQuantity(lineItemId, {
quantity: 2,
})
// update line item options
await modifyQuantity(lineItemId, {
options: {
price: 8.5,
},
})modifyGiftCards()
The giftCardsDetails object is returned in the lineItem object if the lineItem is a gift card. Additionally, newly redeemed gift cards are available in the user object for indicating to the user that they have received a gift.
The gift cards can be updated by including the gift card id along with any of the following params: recipientName, recipientEmail, giftMessage, purchaserName, sendEmailAt.The recipient email is a required field as that will be the account used to redeem the gift cards.
modifyGiftCards({
"giftCardsDetails": [
{
"recipientEmail": "[email protected]",
"giftMessage": "Hi!",
"sendEmailAt": "2021-11-15",
"id": "49"
},
{
"recipientEmail": "[email protected]",
"giftMessage": "",
"sendEmailAt": "2021-11-16",
"id": "50"
}
]
})removeFromCart()
removeFromCart(lineItemId)removePromoCode
removePromoCode(promoCode)subscribeProduct()
subscribeProduct({ sku, quantity, interval, endDate })Note: endDate is optional. The subscription will renew indefinitely if endDate is not specified.
Example
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { subscribeProduct } = useCart()
const onSubmit = ({ sku, quantity, interval, endDate }) => {
subscribeProduct({ sku, quantity, interval, endDate })
}
}useProduct()
import { useProduct } from '@chordcommerce/gatsby-theme-autonomy'
// inside a function component
const { createStockRequest } = useProduct()createStockRequest()
The createStockRequest adds the customer to a product variant wait list in the OMS. When the variant is marked back in stock, customers on the wait list will automatically receive an email notification.
For kits, you will need to pass both sku and slug as options to the createStockRequest hook method.
Example
import { useProduct } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { createStockRequest } = useProduct()
await createStockRequest({ email, sku, slug })
} useSubscription()
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'
// inside a function component
const { subscripion, loadSubscription } = useSubscription()The useSubscription hook returns the current loaded subscription and functions for managing the subscription.
subscription
The subscription object represents a subscription. You will need to explicitly call loadSubscription before this object will be populated.
Example
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { subscription } = useSubscription()
return (
<p>Your subscription will be renewed on {subscription.actionableDate}</p>
)
}loadSubscription()
loadSubscription()The loadSubscription function loads information about the subscription from the Chord API.
Example
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'
export default subscriptionId => {
const { subscription, loadSubscription } = useSubscription()
useEffect(() => {
loadSubscription(subscriptionId)
}, [])
return (
<p>Your subscription will be renewed on {subscription.actionableDate}</p>
)
}skipSubscription()
skipSubscription()The skipSubscription function calls the Chord API to skip the next subscription delivery.
Example
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'
export default subscriptionId => {
const { subscription, skipSubscription } = useSubscription()
useEffect(() => {
skipSubscription(subscriptionId)
}, [])
return (
<p>Your subscription will be renewed on {subscription.actionableDate}</p>
)
}cancelSubscription()
cancelSubscription()The cancelSubscription function calls the Chord API to cancel a subscription.
Example
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'
export default subscriptionId => {
const { subscription, cancelSubscription } = useSubscription()
useEffect(() => {
cancelSubscription(subscriptionId)
}, [])
return <p>Your subscription was canceled</p>
}pauseSubscription()
pauseSubscription()ThepauseSubscription function calls the Chord API to pause a subscription.
Paused subscriptions will not be processed until manuallyresumedor theactionable_dateis reached.Subscriptions can be either paused until a specifiedactionable_dateby sending an optionalactionable_dateparam or paused indefinitely by not passing any params. The minimum date to whichactionable_datecan be set is the next day.
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { pauseSubscription } = useSubscription(subscription.id)
const onSubmit = async data => {
try {
let response = await pauseSubscription({
'actionable_date': '2030-08-18'
})
console.log(response)
} catch (error) {
console.error(error)
}
}
}resumeSubscription()
resumeSubscription()TheresumeSubscriptionfunction calls the Chord API to resume a subscription.
Paused subscriptions will not be processed until manuallyresumedor theactionable_dateis reached.Subscriptions can be resumed at a specifiedactionable_dateby sending an optionalactionable_dateparam or resumed the next day (the minimum to which actionable_datecan be set) by not passing any params.
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { resumeSubscription } = useSubscription(subscription.id)
const onSubmit = async data => {
try {
let response = await resumeSubscription({
'actionable_date': '2030-08-18'
})
console.log(response)
} catch (error) {
console.error(error)
}
}
}updateSubscription()
updateSubscription()TheupdateSubscription function calls the Chord API to update a subscription.
To update the addresses, all fields need to be sent even if only a single field is updated. The two addresses that can be updated are shipAddressAttributes and billAddressAttributes.
In addition, the interval_unit('day'/'week'/'month'/'year'), interval_length, actionable_date and the end_date(null for no end date ) can be updated.
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { updateSubscription } = useSubscription(subscription.id)
const onSubmit = async data => {
try {
let response = await updateSubscription({
'shipAddressAttributes': data.addressAttributes,
'billAddressAttributes': data.addressAttributes,
'interval_units': 'month',
'interval_length': '2',
'end_date': '2021/12/31',
'actionable_date': '2030-08-18'
})
console.log(response)
} catch (error) {
console.error(error)
}
}
}
/*
Default Form Values:
const address = subscription['shipAddress']
const addressAttributes = {
name: address.name,
address1: address.address1,
address2: address.address2,
city: address.city,
state_name: address.state.abbr,
country_iso: address.country.iso,
zipcode: address.zipcode
}
*/useTranslate
import { useTranslate } from '@chordcommerce/gatsby-theme-autonomy`
// inside a function component
const translate = useTranslate()The useTranslate hook provides support for internationalization, powered by gatsby-plugin-intl.
To localize the text in your React components, use the translate function returned by the useTranslate hook. translate will load the specified string from your language resource file.
We recommend using translate even if your site currently only supports one language. It's easier to edit your website text if it's all in a single configuration file, and it makes it trivial to add multi-language support in the future.
Example
import { useTranslate } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { translate } = useTranslate()
return <h1>{translate('site.title')}</h1>
}The component above assumes there is a file at /src/intl/<language>.json that looks like this:
// /src/intl/en-US.json
{
"site": {
"title": "My Site"
}
}useUser()
import { useUser } from '@chordcommerce/gatsby-theme-autonomy`
// inside a function component
const { user, loadUser } = useUser()The useUser hook returns the current user and functions for loading data about the user. At the moment, the only user information Chord supports is the user's referral identifier and personalized referral url.
user
The user object represents the current user. You will need to explicitly call loadUser or loadUserReferralIdentifier before this object will be populated.
Example
import { useUser } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { user } = useUser()
const referralPurl = user.referralIdentifier && user.referralIdentifier.purl
return (
<p>Refer your friends with your personal referral link: {referralPurl}</p>
)
}loadUser()
loadUser()The loadUser function loads information about the current order's associated user from the Chord API.
Example
import { useUser } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { cart } = useCart()
const { user, loadUser } = useUser()
useEffect(() => {
loadUser()
}, [])
return <p>Welcome, {user.data.email}!</p>
}loadUserReferralIdentifier()
loadUserReferralIdentifier(email)The loadUserReferralIdentifier function loads the referral identifier information for a user with the given email address from the Chord API.
Example
import { useUser } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { user, loadUserReferralIdentifier } = useUser()
const referralPurl = user.referralIdentifier && user.referralIdentifier.purl
useEffect(() => {
loadUserReferralIdentifier()
}, [])
return (
<p>Refer your friends with your personal referral link: {referralPurl}</p>
)
}modifyUser()
The modifyUser function is used to update the user's profile information.
Example
import { useUser } from '@chordcommerce/gatsby-theme-autonomy'
export default () => {
const { modifyUser } = useUser()
const onSubmit = ({ email }) => {
modifyUser({ email })
}
// return profile edit form
}useSquareCheckout
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy`
// inside a function component
const { updateOrderAddresses, getStates, updateOrderDelivery } = useSquareCheckout()This module allows to checkout using Square, the typical flow is:
- Attach an email address to the order using modifyCart({ email: "[email protected]" }). This is only needed for guest checkouts, if the user is logged in, this is not needed and the user's email will be used.
- Attempt a payment via Square using the updateOrderPayment() function after retrieving the Square token client-side, using the Square Web Payment SDK.
updateOrderAddresses()
updateOrderAddresses(shipAddressAttributes)The updateOrderAddresses() function is used to update the order's ship address. A valid ship address has the following format:
{
name: 'Jane Doe', # string
address1: '2191 Calico Drive', # string
address2: 'Apt. 3', # string, optional
city: 'Phoenix', # string
country_id: 233, # integer
state_id: 3438, # integer
zipcode: '85022', # string
phone: '509-644-9988', # string
company: 'Acme Inc.' # string
}To retrieve the available states and the country id, please use getStates().
Example
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'
const { updateOrderAddresses } = useSquareCheckout()
const shipAddressAttributes = {
name: 'Jane Doe',
address1: '2191 Calico Drive',
city: 'Phoenix',
country_id: 233,
state_id: 3438,
zipcode: '85022',
phone: '509-644-9988',
company: 'Acme Inc.'
}
updateOrderAddresses(shipAddressAttributes)getStates()
getStates(iso)The getStates() function is used to retrieve information about countries and states available in the system to be used when we need to update the order's address. It takes the ISO code of the country and returns the list of states along with other information related to the country itself.
Example
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'
const { getStates } = useSquareCheckout()
getStates('US')updateOrderDelivery()
updateOrderDelivery()The updateOrderDelivery() function allows choosing the shipping option for the current order. At the moment we do not support multiple delivery options, so this function is only needed to move the checkout from the delivery step to the payment step. During this process, shipping costs and taxes will be added to the order.
This function should be called only when the order is in the delivery state, meaning that a valid address has been added to the order previously. This way it will be able to correctly pick the right delivery option based on the shipping address and to correctly compute taxes based on the shipment route.
Example
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'
const { updateOrderDelivery } = useSquareCheckout()
updateOrderDelivery()updateOrderPayment()
updateOrderPayment()The updateOrderPayment() function allows completing the payment step of the checkout. Before using this function, the client should retrieve a token using the Web Payments SDK provided by Square. When the order is successfully completed, the payment source will be added to the user's wallet (for authenticated users only), allowing to re-use the payment token later, without having to input the credit card information again.
This function should be called only when the order is in the payment state, meaning that a valid delivery option has been added to the order previously. At this stage the order is updated with shipping costs and taxes, allowing to complete the payment with the right amount.
For now, this endpoint doesn't support the ability to pay with an existing token. In the future we will provide this support, allowing to re-use a previously saved credit card from the user wallets.
Example
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'
const { updateOrderPayment } = useSquareCheckout()
const paymentAttributes = {
payment_method_type: 'square',
source_attributes: {
nonce: 'your-token'
}
}
updateOrderPayment(paymentAttributes)finalizeCheckout()
finalizeCheckout()finalizeCheckout() is the last method that needs to be called to complete the order with Square. Call this method when you want to move the user to the thank you page and let them start a new order.
Example
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'
const { finalizeCheckout } = useSquareCheckout()
finalizeCheckout()This function should be called only when the order is in the "confirm" state, meaning that a valid payment has been added to the order already.