Checkout functions
This topic provides the details and instructions you need to use the functions provided by the Checkout drop-in component.
authenticateCustomer
The authenticateCustomer function manages the authentication state of a customer, either by fetching customer data using the getCustomer function when authenticated or resetting the customer data when not authenticated.
export const authenticateCustomer = async (authenticated = false);Returns
The function does not return any value explicitly; it performs side effects by fetching data and logging errors.
Usage
See the following example for usage details:
async function authenticate() { try { await authenticateCustomer(true); console.log('Customer authenticated successfully.'); } catch (error) { console.error('Error authenticating customer:', error); }}estimateShippingMethods
The estimateShippingMethods function fetches and displays available shipping methods based on a customer’s address information. If no information is provided, it takes the default country configured by default. It can take a combination of fields as input criteria: country, region, region identifier, and postal code.
It uses a utility function to call an estimateShippingMethods mutation.
export interface ShippingEstimationCriteria { country_code: string; region_name?: string; region_id?: string | number; zip?: string;}
export type EstimateShippingInput = { criteria: ShippingEstimationCriteria;};
export const estimateShippingMethods = async ( input?: EstimateShippingInput): Promise<ShippingMethod[] | undefined>;Returns
Returns a promise that resolves to an array of ShippingMethod objects (or undefined if no shipping methods are available) fetched from the API.
export type ShippingMethod = { amount: Price; carrier: Carrier; code: Code; title: Title; value: string; amountExclTax?: Price; amountInclTax?: Price;};Usage
See the following example for usage details:
// By country code and region nameconst input = { criteria: { country_code: 'US', region_name: 'FL', },};const estimateShippingMethods = await estimateShippingMethods(input);
// By country code and region IDconst input = { criteria: { country_code: 'US', region_id: 18, },};const estimateShippingMethods = await estimateShippingMethods(input);
// By country code and postal codeconst input = { criteria: { country_code: 'US', zip: '80000', },};const estimateShippingMethods = await estimateShippingMethods(input);
// By country code, region and postal codeconst input = { criteria: { country_code: 'US', region_name: 'FL', zip: '80000', },};const estimateShippingMethods = await estimateShippingMethods(input);
// By country code, region, region id and postal code// This scenario is specific for those regions which have more than a region ID// associated (i.e. Armed Forces region 'AE' with some regions IDs); if the region has// just a region ID,const input = { criteria: { country_code: 'US', region_name: 'FL', region_id: 18, zip: '80000', },};const estimateShippingMethods = await estimateShippingMethods(input);getCart
The getCart function fetches the cart details for either a guest user or an authenticated customer.
export const getCart = async ();Returns
Returns a promise that resolves to the transformed cart data fetched from the API.
export interface Cart { availablePaymentMethods?: PaymentMethod[]; billingAddress?: Address; email?: string; id: string; isEmpty: boolean; isGuest: boolean; isVirtual: boolean; selectedPaymentMethod?: PaymentMethod; shippingAddresses?: ShippingAddress[];}Usage
See the following example for usage details:
async function fetchCartData() { try { const cartData = await getCart(); console.log('Cart Data:', cartData); } catch (error) { console.error('Error fetching cart data:', error); }}
// Call the function to fetch and log the cart datafetchCartData();getCheckoutAgreements
The getCheckoutAgreements function fetches the list of terms and conditions configured in the Admin Panel using the checkoutAgreements query.
export const getCheckoutAgreements = async (): Promise<CheckoutAgreement[]>Returns
The function returns a promise that resolves to an array of checkout agreements or an empty array if none are enabled.
export enum AgreementMode { MANUAL = 'manual', AUTO = 'auto',}
type AgreementContent = { value: string; html: boolean; height: string | null;};
export interface CheckoutAgreement { content: AgreementContent; id: number; mode: AgreementMode; name: string; text: string;}Usage
See the following example for usage details:
async function fetchAndLogTermsAndConditions() { try { const agreements = await getCheckoutAgreements(); console.log('List of Terms and Conditions:', agreements); } catch (error) { console.error('Error fetching terms and conditions:', error); }}
// Call the function to fetch and log the list of Terms and ConditionsfetchAndLogTermsAndConditions();getCustomer
The getCustomer function fetches customer details for an authenticated user using the customer query.
export const getCustomer = async (): Promise<Customer | null>Returns
The function returns a promise that resolves to the transformed customer data fetched from the API or null if the user is not authenticated.
export interface Customer { firstName: string; lastName: string; email: string;}Usage
See the following example for usage details:
async function fetchAndLogCustomer() { try { const customer = await getCustomer(); if (customer) { console.log('Customer:', customer); } else { console.log('No customer data found.'); } } catch (error) { console.error('Error fetching customer data:', error); }}
// Call the function to fetch and log the customer datafetchAndLogCustomer();getStoreConfig
The getStoreConfig function fetches information about a store’s configuration settings using the storeConfig query.
You can query a non-default store by changing the header in your GraphQL request.
export const getStoreConfig = async ();Returns
The function returns a promise that resolves to the transformed store configuration data fetched from the API.
If the API call fails, it returns the default store configuration settings (STORE_CONFIG_DEFAULTS).
export interface StoreConfig { defaultCountry: string; agreementsEnabled: boolean; shoppingCartDisplaySetting: { shipping: TaxDisplay; };}Usage
See the following example for usage details:
async function fetchAndLogStoreConfig() { try { const storeConfig = await getStoreConfig(); console.log('Store Config:', storeConfig); } catch (error) { console.error('Error fetching store config:', error); }}
// Call the function to fetch and log the store configurationfetchAndLogStoreConfig();initializeCheckout
The initializeCheckout function initializes the checkout process by fetching necessary configuration and data from various Adobe Commerce GraphQL APIs using the following functions:
getStoreConfiggetCartsynchronizeCheckout
import { Cart } from '@adobe/event-bus';
export const initializeCheckout = async (cart: Cart | null): Promise<void>Returns
The function does not return any value explicitly; it performs some initializations and finally emits the checkout/initialized event containing the initial cart data.
Usage
See the following example for usage details:
await initializeCheckout(null);isEmailAvailable
The isEmailAvailable function checks whether the specified email has already been used to create a customer account using the isEmailAvailable query.
A value of true indicates that the email address is available and the customer can use the email address to create an account. As of Adobe commerce 2.4.7, the default value is true.
export const isEmailAvailable = async ( email: string): Promise<EmailAvailability>Returns
A promise that resolves to an EmailAvailability object indicating whether the email is available.
export type EmailAvailability = boolean;Usage
See the following example for usage details:
await isEmailAvailable('test@example.com');resetCheckout
The resetCheckout function resets the checkout process to its initial state by clearing the cart data.
export const resetCheckout = ();Returns
The function does not return any value explicitly; it performs some initializations and finally emits the checkout/updated event containing null data.
Usage
See the following example for usage details:
resetCheckout();setBillingAddress
The setBillingAddress function sets the billing address for a specific cart using the setBillingAddressOnCart Adobe Commerce GraphQL mutation.
export const setBillingAddress = async (input: BillingAddressInput);The input parameter accepts a BillingAddressInput object with the following structure:
interface BillingAddressInput { address?: CartAddress; customerAddressId?: number; sameAsShipping?: boolean; useForShipping?: boolean;}Where CartAddress has the following properties:
interface CartAddress { city: string; company?: string; countryCode: string; customAttributes: CustomAttribute[]; firstName: string; lastName: string; postcode?: string; region?: string; regionId?: number; saveInAddressBook?: boolean; street: string[]; telephone?: string; vatId?: string; prefix?: string; suffix?: string; middleName?: string; fax?: string;}And CustomAttribute is defined as:
interface CustomAttribute { attribute_code: string; value: string;}Returns
The function returns a promise that resolves to the transformed cart data fetched from the API.
export interface Cart { availablePaymentMethods?: PaymentMethod[]; billingAddress?: Address; email?: string; id: string; isEmpty: boolean; isGuest: boolean; isVirtual: boolean; selectedPaymentMethod?: PaymentMethod; shippingAddresses?: ShippingAddress[];}Usage
To set the billing address as the same as the shipping address:
await setBillingAddress({ sameAsShipping: true,});To set a specific billing address:
await setBillingAddress({ address: { firstName: 'John', lastName: 'Doe', street: ['123 Main St', 'Apt 1'], city: 'New York', postcode: '10001', countryCode: 'US', telephone: '555-555-5555', }, sameAsShipping: false,});setGuestEmailOnCart
The setGuestEmailOnCart function sets the email address for a guest user on the cart using the setGuestEmailOnCart mutation.
export const setGuestEmailOnCart = async (email: string);Returns
The function returns a promise that resolves to the transformed cart data fetched from the API.
export interface Cart { availablePaymentMethods?: PaymentMethod[]; billingAddress?: Address; email?: string; id: string; isEmpty: boolean; isGuest: boolean; isVirtual: boolean; selectedPaymentMethod?: PaymentMethod; shippingAddresses?: ShippingAddress[];}Usage
See the following example for usage details:
await setGuestEmailOnCart('test@example.com');setPaymentMethod
The setPaymentMethod function sets the provided payment method for the current cart using the setPaymentMethodOnCart mutation.
/** Defines the payment method. */export type PaymentMethodInput = { /** The internal name for the payment method. */ code: Scalars['String']['input'];};
export const setPaymentMethod = async (paymentMethod: PaymentMethodInput);Returns
The function returns a promise that resolves to the transformed cart data fetched from the API.
export interface Cart { availablePaymentMethods?: PaymentMethod[]; billingAddress?: Address; email?: string; id: string; isEmpty: boolean; isGuest: boolean; isVirtual: boolean; selectedPaymentMethod?: PaymentMethod; shippingAddresses?: ShippingAddress[];}Usage
See the following example for usage details:
await setPaymentMethod({ code: 'braintree' });setShippingAddress
The setShippingAddress function sets the shipping address for a specific cart using the setShippingAddressesOnCart mutation.
export const setShippingAddress = async (input: ShippingAddressInput);The input parameter accepts a ShippingAddressInput object with the following structure:
interface ShippingAddressInput { address?: CartAddress; customerAddressId?: number; pickupLocationCode?: string;}Where CartAddress has the following properties:
interface CartAddress { city: string; company?: string; countryCode: string; customAttributes: CustomAttribute[]; firstName: string; lastName: string; postcode?: string; region?: string; regionId?: number; saveInAddressBook?: boolean; street: string[]; telephone?: string; vatId?: string; prefix?: string; suffix?: string; middleName?: string; fax?: string;}And CustomAttribute is defined as:
interface CustomAttribute { attribute_code: string; value: string;}Returns
The function returns a promise that resolves to the transformed cart data fetched from the API.
export interface Cart { availablePaymentMethods?: PaymentMethod[]; billingAddress?: Address; email?: string; id: string; isEmpty: boolean; isGuest: boolean; isVirtual: boolean; selectedPaymentMethod?: PaymentMethod; shippingAddresses?: ShippingAddress[];}Usage
See the following example for usage details:
await setShippingAddress({ address: { firstName: 'John', lastName: 'Doe', street: ['123 Main St', 'Apt 1'], city: 'New York', postcode: '10001', countryCode: 'US', telephone: '555-555-5555', },});setShippingMethodsOnCart
The setShippingMethodsOnCart function sets the shipping methods for a specific cart using the setShippingMethodsOnCart mutation.
/** Defines the shipping carrier and method. */export type ShippingMethodInput = { /** A string that identifies a commercial carrier or an offline delivery method. */ carrier_code: Scalars['String']['input']; /** A string that indicates which service a commercial carrier will use to ship items. For offline delivery methods, this value is similar to the label displayed on the checkout page. */ method_code: Scalars['String']['input'];};
export const setShippingMethodsOnCart = async ( shippingMethods: Array<InputMaybe<ShippingMethodInput>>);Returns
The function returns a promise that resolves to the transformed cart data fetched from the API.
export interface Cart { availablePaymentMethods?: PaymentMethod[]; billingAddress?: Address; email?: string; id: string; isEmpty: boolean; isGuest: boolean; isVirtual: boolean; selectedPaymentMethod?: PaymentMethod; shippingAddresses?: ShippingAddress[];}Usage
See the following example for usage details:
const shippingMethod = { carrier_code: 'flatrate', method_code: 'flatrate',};
await setShippingMethodsOnCart([shippingMethod]);synchronizeCheckout
The synchronizeCheckout function synchronizes the checkout state with the current cart information. It ensures that the checkout process is properly initialized, reset, or updated based on the cart data. It uses the following functions:
getCartinitializeCheckout
import { Cart } from '@adobe/event-bus';
export const synchronizeCheckout = async (cart: Cart | null);Returns
The function does not return any value explicitly; it performs some initializations and finally emits the checkout/updated event containing the cart data.
Usage
See the following example for usage details:
await synchronizeCheckout(cart);