Chord OMS
...
Developer Tools
Gatsby
SDK Reference 3.x
72min
version 4 is now available! check out the release notes docid\ uofiijhjr f4oeywghc26 to read about its exciting new features, and v3 x to v4 x migration guide docid\ mnqv6 ugqfwtnxfakc e4 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 https //magic link/ 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 privateroute login() 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 data addpromocode() 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" "test\@chord co", "giftmessage" "hi!", "sendemailat" "2021 11 15", "id" "49" }, { "recipientemail" "admin\@chord co", "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() the pausesubscription function calls the chord api to pause a subscription paused subscriptions will not be processed until manually resumed or the actionable date is reached subscriptions can be either paused until a specified actionable date by sending an optional actionable date param or paused indefinitely by not passing any params the minimum date to which actionable date can 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() the resumesubscription function calls the chord api to resume a subscription paused subscriptions will not be processed until manually resumed or the actionable date is reached subscriptions can be resumed at a specified actionable date by sending an optional actionable date param or resumed the next day (the minimum to which actionable date can 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() the updatesubscription 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 https //www gatsbyjs com/plugins/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 create a cart and add items into it with the usecart module attach an email address to the order using modifycart({ email "your\@email com" }) 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 add a shipping address to the order using the updateorderaddresses () function pick a delivery method using the updateorderdelivery() function attempt a payment via square using the updateorderpayment() function after retrieving the square token client side, using the square web payment sdk https //developer squareup com/docs/web payments/overview finalize the order with finalizecheckout() 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 https //en wikipedia org/wiki/iso 3166 1 alpha 2 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 https //developer squareup com/docs/web payments/overview 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