---
title: SDK Reference 3.x
slug: oms/sdk-reference-3x
docTags: 
createdAt: 2022-11-07T21:29:48.000Z
---

:::hint{type="info"}
**Version 4 is now available! Check out the&#x20;**[Release Notes](docId\:UOfiIJHJr_f4OEYWghc26)**&#x20;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](https://www.gatsbyjs.com/docs/themes/what-are-gatsby-themes/):

:::BlockQuote
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()`&#x20;

```javascript
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()`&#x20;

```javascript
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**

```javascript
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()`&#x20;

```javascript
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**

```javascript
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()`&#x20;

```javascript
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**

```jsx
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()`&#x20;

```javascript
trackViewCart()
```

The `trackViewCart` function fires a `Cart Viewed` event to Segment. You should call this function when the cart page is viewed.

**Example**

```jsx
import { useAnalytics } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { trackViewCart } = useAnalytics()
  
  useEffect(() => {    
    trackViewCart()  
  }, [])
  
  // return cart page
}
```

### `trackProductViewed()`

```Text
trackProductViewed({ product })
```

The `trackProductViewed` function fires a `Product Viewed` event to Segment. You should call this function when a product page is opened.

**Example**

```javascript
import { useAnalytics } from '@chordcommerce/gatsby-theme-autonomy'

export default (product) => {
  const { trackProductViewed } = useAnalytics()

  useEffect(() => {
    trackProductViewed({ product })
  }, [product])

  // return product page
}
```

## `useAuth()`&#x20;

```jsx
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&#x20;

`isLoggedIn` is a boolean indicating whether the user is currently logged in.

**Example**

```jsx
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy`

const { isLoggedIn } = useAuth()

if (isLoggedIn) {  
    // return component
}
```

### isFetching&#x20;

`isFetching` is a boolean indicating whether the user's authentication status is currently being fetched.

**Example**

```jsx
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy`

const { isFetching } = useAuth()

if (isFetching) {  
    // return loading animation
}
```

### token&#x20;

`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()&#x20;

```javascript
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()&#x20;

```Text
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**

```jsx
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()&#x20;

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**

```jsx
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()&#x20;

```Text
logout()
```

The `logout` function terminates the user's current session.

**Example**

```jsx
import { useAuth } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { logout } = useAuth()
  
  return <button onClick={() => logout()}>Logout</button>
}
```

## `useCart()`&#x20;

```jsx
import { useCart } from '@chordcommerce/gatsby-theme-autonomy`

// inside a function component
const { cart, addToCart } = useCart()
```

### `cart`&#x20;

**Example**

```jsx
import { useCart } from '@chordcommerce/gatsby-theme-autonomy`

const { cart } = useCart()
const { lineItems } = cart.data
```

### `addPromoCode()`&#x20;

```Text
addPromoCode(promoCode)
```

**Example**

```jsx
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { addPromoCode } = useCart()
  const onSubmit = ({ promoCode }) => {    
    addPromoCode(promoCode)  
  }
}
```

### `addReferralIdentifier()`&#x20;

```javascript
addReferralIdentifier(referralIdentifier)
```

**Example**

```jsx
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { addReferralIdentifier } = useCart()
  const onSubmit = ({ referralIdentifier }) => {    
    addReferralIdentifier(referralIdentifier)  
  }
}
```

### `addToCart()`&#x20;

```Text
addToCart(sku, quantity)
```

**Example**

```jsx
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { addToCart } = useCart()
  const onSubmit = ({ sku, quantity }) => {    
    addToCart(sku, quantity)  
  }
}
```

### `checkout()`&#x20;

```Text
checkout()
```

**Example**

```jsx
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()`&#x20;

```Text
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**

```jsx
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()`&#x20;

`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**

```javascript
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { forgetCart } = useCartuth()
  
  return <button onClick={() => forgetCart()}>Clear order</button>
}
```

### `loadCart()`&#x20;

```Text
loadCart()
```

### `modifyCart()`&#x20;

```javascript
modifyCart({ lineItems: [] })
```

### `modifyQuantity()`&#x20;

```Text
modifyQuantity(lineItemId, quantity)
```

### `modifyLineItem()`

Updates a line item in the current order.

```javascript
const lineItemId = '123'

// update line item quantity
await modifyQuantity(lineItemId, {
  quantity: 2,
})

// update line item options
await modifyQuantity(lineItemId, {
  options: {
    price: 8.5,
  },
})
```

### `modifyGiftCards()`&#x20;

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.

```Text
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()`&#x20;

```Text
removeFromCart(lineItemId)
```

### `removePromoCode`&#x20;

```Text
removePromoCode(promoCode)
```

### `subscribeProduct()`&#x20;

```Text
subscribeProduct({ sku, quantity, interval, endDate })
```

Note: `endDate` is optional. The subscription will renew indefinitely if `endDate` is not specified.

**Example**

```jsx
import { useCart } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { subscribeProduct } = useCart()
  const onSubmit = ({ sku, quantity, interval, endDate }) => {    
    subscribeProduct({ sku, quantity, interval, endDate })  
  }
}
```

## `useProduct()`&#x20;

```jsx
import { useProduct } from '@chordcommerce/gatsby-theme-autonomy'

// inside a function component
const { createStockRequest } = useProduct()
```

### createStockRequest()&#x20;

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.&#x20;

:::hint{type="warning"}
For kits, you will need to pass both `sku` and `slug` as options to the `createStockRequest` hook method.
:::

**Example**

```javascript
import { useProduct } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { createStockRequest } = useProduct()
  await createStockRequest({ email, sku, slug })
} 
```

## `useSubscription()`&#x20;

```jsx
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`&#x20;

The `subscription` object represents a subscription. You will need to explicitly call `loadSubscription` before this object will be populated.

**Example**

```jsx
import { useSubscription } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { subscription } = useSubscription()
  
  return (    
    <p>Your subscription will be renewed on {subscription.actionableDate}</p>  
  )
}
```

### `loadSubscription()`&#x20;

```Text
loadSubscription()
```

The `loadSubscription` function loads information about the subscription from the Chord API.

**Example**

```jsx
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()`&#x20;

```Text
skipSubscription()
```

The `skipSubscription` function calls the Chord API to skip the next subscription delivery.

**Example**

```jsx
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()`&#x20;

```Text
cancelSubscription()
```

The `cancelSubscription` function calls the Chord API to cancel a subscription.

**Example**

```jsx
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()`&#x20;

```Text
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.

```jsx
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()`&#x20;

```Text
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.

```jsx
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()`&#x20;

```Text
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.

```jsx
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`&#x20;

```jsx
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**

```jsx
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:

```javascript
// /src/intl/en-US.json

{  
  "site": {    
    "title": "My Site"  
  }
}
```

## `useUser()`&#x20;

```jsx
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`&#x20;

The `user` object represents the current user. You will need to explicitly call `loadUser` or `loadUserReferralIdentifier` before this object will be populated.

**Example**

```jsx
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()`&#x20;

```Text
loadUser()
```

The `loadUser` function loads information about the current order's associated user from the Chord API.

**Example**

```jsx
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()`&#x20;

```Text
loadUserReferralIdentifier(email)
```

The `loadUserReferralIdentifier` function loads the referral identifier information for a user with the given email address from the Chord API.

**Example**

```jsx
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()`&#x20;

The `modifyUser` function is used to update the user's profile information.

**Example**

```jsx
import { useUser } from '@chordcommerce/gatsby-theme-autonomy'

export default () => {  
  const { modifyUser } = useUser()
  const onSubmit = ({ email }) => {    
    modifyUser({ email })  
  }
  
  // return profile edit form
}
```

## `useSquareCheckout`

```Text
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()`

```Text
updateOrderAddresses(shipAddressAttributes)
```

The `updateOrderAddresses()` function is used to update the order's ship address. A valid ship address has the following format:

```Text
{
  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**

```Text
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()`

```Text
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.&#x20;

**Example**

```Text
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'

const { getStates } = useSquareCheckout()

getStates('US')
```

### `updateOrderDelivery()`

```Text
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.&#x20;

:::hint{type="info"}
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.&#x20;
:::

**Example**

```Text
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'

const { updateOrderDelivery } = useSquareCheckout()

updateOrderDelivery()
```

### `updateOrderPayment()`

```Text
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. &#x20;

:::hint{type="info"}
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.
:::

:::hint{type="info"}
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.&#x20;
:::

**Example**

```Text
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'

const { updateOrderPayment } = useSquareCheckout()

const paymentAttributes = {
  payment_method_type: 'square',
  source_attributes: {
    nonce: 'your-token'
  }
}
updateOrderPayment(paymentAttributes)
```

### `finalizeCheckout()`

```Text
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.&#x20;

**Example**

```Text
import { useSquareCheckout } from '@chordcommerce/gatsby-theme-autonomy'

const { finalizeCheckout } = useSquareCheckout()

finalizeCheckout()
```

:::hint{type="info"}
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.
:::

