Skip to content

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);
ParameterTypeReq?Description
authenticatedbooleanNoA boolean indicating whether the user has been authenticated or not.

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:

import { authenticateCustomer } from '@/checkout/api/authenticateCustomer';
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>;
ParameterTypeReq?Description
inputobjectNoAn object of type EstimateShippingInput, which contains a criteria object including the following fields: country_code, region_name, region_id, and zip.

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:

import { estimateShippingMethods } from '@/checkout/api/estimateShippingMethods';
// By country code and region name
const input = {
criteria: {
country_code: 'US',
region_name: 'FL',
},
};
const estimateShippingMethods = await estimateShippingMethods(input);
// By country code and region ID
const input = {
criteria: {
country_code: 'US',
region_id: 18,
},
};
const estimateShippingMethods = await estimateShippingMethods(input);
// By country code and postal code
const input = {
criteria: {
country_code: 'US',
zip: '80000',
},
};
const estimateShippingMethods = await estimateShippingMethods(input);
// By country code, region and postal code
const 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:

import { getCart } from '@/checkout/api/getCart';
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 data
fetchCartData();

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:

import { getCheckoutAgreements } from '@/checkout/api/getCheckoutAgreements';
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 Conditions
fetchAndLogTermsAndConditions();

getCustomer

The getCustomer function fetches customer details for an authenticated user using the customer query.

export const getCustomer = async (): Promise<Customer | null | undefined>

Returns

The function returns a promise that resolves to the transformed customer data fetched from the API or undefined if the user is not authenticated.

export interface Customer {
firstName: string;
lastName: string;
email: string;
}

Usage

See the following example for usage details:

import { getCustomer } from '@/checkout/api/getCustomer';
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 data
fetchAndLogCustomer();

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;
isGuestCheckoutEnabled: boolean;
isOnePageCheckoutEnabled: boolean;
shoppingCartDisplaySetting: {
shipping: TaxDisplay;
};
}

Usage

See the following example for usage details:

import { getStoreConfig } from '@/checkout/api/getStoreConfig';
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 configuration
fetchAndLogStoreConfig();

initializeCheckout

The initializeCheckout function initializes the checkout process by fetching necessary configuration and data from various Adobe Commerce GraphQL APIs using the following functions:

  • getStoreConfig
  • getCart
  • synchronizeCheckout
import { Cart } from '@adobe/event-bus';
export const initializeCheckout = async (cart: Cart | null): Promise<void>
ParameterTypeReq?Description
cartobjectYesAn object of type Cart or null.

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:

import { initializeCheckout } from '@/checkout/api/initializeCheckout';
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>
ParameterTypeReq?Description
emailstringYesA string representing the email address to check for availability.

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:

import { isEmailAvailable } from '@/checkout/api/isEmailAvailable';
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:

import { resetCheckout } from '@/checkout/api/resetCheckout';
resetCheckout();

setBillingAddress

The setBillingAddress function sets the billing address for a specific cart using the setBillingAddressOnCart Adobe Commerce GraphQL mutation.

import { BillingAddressInput } from '@/checkout/data/models';
export const setBillingAddress = async (input: BillingAddressInput);
ParameterTypeReq?Description
inputobjectYesAn object containing the billing address details.

It takes an input parameter where BillingAddressInput is an interface that contains the specific properties for the billing address:

export interface BillingAddressInput {
address?: CartAddress;
customerAddressId?: number;
sameAsShipping?: boolean;
useForShipping?: boolean;
}

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:

import { setBillingAddress } from '@/checkout/api/setBillingAddress';
await setBillingAddress({
sameAsShipping: true,
});

To set a specific billing address:

import { setBillingAddress } from '@/checkout/api/setBillingAddress';
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);
ParameterTypeReq?Description
emailstringYesA string representing the guest email to be set on the cart.

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:

import { setGuestEmailOnCart } from '@/checkout/api/setGuestEmailOnCart';
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);
ParameterTypeReq?Description
paymentMethodobjectYesAn object representing the payment method input to be set on the cart.

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:

import { setPaymentMethod } from '@/checkout/api/setPaymentMethod';
await setPaymentMethod({ code: 'braintree' });

setShippingAddress

The setShippingAddress function sets the shipping address for a specific cart using the setShippingAddressesOnCart mutation.

import { ShippingAddressInput } from '@/checkout/data/models';
export const setShippingAddress = async (input: ShippingAddressInput);
ParameterTypeReq?Description
inputobjectYesAn object containing the shipping address details.

It takes an input parameter where ShippingAddressInput is an interface that contains the specific properties for the shipping address:

export interface ShippingAddressInput {
address?: CartAddress;
customerAddressId?: number;
pickupLocationCode?: 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:

import { setShippingAddress } from '@/checkout/api/setShippingAddress';
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>>
);
ParameterTypeReq?Description
shippingMethodsarrayYesAn array of objects representing the shipping methods.

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:

import { setShippingMethodsOnCart } from '@/checkout/api/setShippingMethods';
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:

  • getCart
  • initializeCheckout
import { Cart } from '@adobe/event-bus';
export const synchronizeCheckout = async (cart: Cart | null);
ParameterTypeReq?Description
cartobjectYesAn object of type Cart or 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:

import { synchronizeCheckout } from '@/checkout/api/synchronizeCheckout';
await synchronizeCheckout(cart);