Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Ecommerce Plugin

Basic Usage

In the plugins array of your Payload Config, call the plugin with:

1
import { buildConfig } from 'payload'
2
import { ecommercePlugin } from '@payloadcms/plugin-ecommerce'
3
4
const config = buildConfig({
5
collections: [
6
{
7
slug: 'pages',
8
fields: [],
9
},
10
],
11
plugins: [
12
ecommercePlugin({
13
// You must add your access control functions here
14
access: {
15
adminOnly,
16
adminOnlyFieldAccess,
17
adminOrCustomerOwner,
18
adminOrPublishedStatus,
19
customerOnlyFieldAccess,
20
},
21
customers: { slug: 'users' },
22
}),
23
],
24
})
25
26
export default config

Options

Option

Type

Description

access

object

Configuration to override the default access control, use this when checking for roles or multi tenancy. More

addresses

object

Configuration for addresses collection and supported fields. More

carts

object

Configuration for carts collection. More

currencies

object

Supported currencies by the store. More

customers

object

Used to provide the customers slug. More

inventory

boolean object

Enable inventory tracking within Payload. Defaults to true. More

payments

object

Configuring payments and supported payment methods. More

products

object

Configuration for products, variants collections and more. More

orders

object

Configuration for orders collection. More

transactions

boolean object

Configuration for transactions collection. More

Note that the fields in overrides take a function that receives the default fields and returns an array of fields. This allows you to add fields to the collection.

1
ecommercePlugin({
2
access: {
3
adminOnly,
4
adminOnlyFieldAccess,
5
adminOrCustomerOwner,
6
adminOrPublishedStatus,
7
customerOnlyFieldAccess,
8
},
9
customers: {
10
slug: 'users',
11
},
12
payments: {
13
paymentMethods: [
14
stripeAdapter({
15
secretKey: process.env.STRIPE_SECRET_KEY!,
16
publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
17
webhookSecret: process.env.STRIPE_WEBHOOKS_SIGNING_SECRET!,
18
}),
19
],
20
},
21
products: {
22
variants: {
23
variantsCollection: VariantsCollection,
24
},
25
productsCollection: ProductsCollection,
26
},
27
})

Access

The plugin requires access control functions in order to restrict permissions to certain collections or fields. You can override these functions by providing your own in the access option.

Option

Type

Description

authenticatedOnly

Access

Authenticated access only, provided by default.

publicAccess

Access

Public access, provided by default.

adminOnly

Access

Limited to only admin users.

adminOnlyFieldAccess

FieldAccess

Limited to only admin users, specifically for Field level access control.

adminOrCustomerOwner

Access

Is the owner of the document via the customer field or is an admin.

adminOrPublishedStatus

Access

The document is published or user is admin.

customerOnlyFieldAccess

FieldAccess

Limited to customers only, specifically for Field level access control.

The default access control functions are:

1
access: {
2
authenticatedOnly: ({ req: { user } }) => Boolean(user),
3
publicAccess: () => true,
4
}

authenticatedOnly

Access control to check if the user is authenticated. By default the following is provided:

1
authenticatedOnly: ({ req: { user } }) => Boolean(user)

publicAccess

Access control to allow public access. By default the following is provided:

1
publicAccess: () => true

adminOnly

Access control to check if the user has admin permissions.

Example:

1
adminOnly: ({ req: { user } }) => Boolean(user?.roles?.includes('admin'))

adminOnlyFieldAccess

Field level access control to check if the user has admin permissions.

Example:

1
adminOnlyFieldAccess: ({ req: { user } }) =>
2
Boolean(user?.roles?.includes('admin'))

adminOrCustomerOwner

Access control to check if the user has admin permissions or is the owner of the document via the customer field.

Example:

1
adminOrCustomerOwner: ({ req: { user } }) => {
2
if (user && Boolean(user?.roles?.includes('admin'))) {
3
return true
4
}
5
6
if (user?.id) {
7
return {
8
customer: {
9
equals: user.id,
10
},
11
}
12
}
13
14
return false
15
}

adminOrPublishedStatus

Access control to check if the user has admin permissions or if the document is published.

Example:

1
adminOrPublishedStatus: ({ req: { user } }) => {
2
if (user && Boolean(user?.roles?.includes('admin'))) {
3
return true
4
}
5
return {
6
_status: {
7
equals: 'published',
8
},
9
}
10
}

customerOnlyFieldAccess

Field level access control to check if the user has customer permissions.

Example:

1
customerOnlyFieldAccess: ({ req: { user } }) =>
2
Boolean(user?.roles?.includes('customer'))

Addresses

The addresses option is used to configure the addresses collection and supported fields. Defaults to true which will create an addresses collection with default fields. It also takes an object:

Option

Type

Description

addressFields

FieldsOverride

A function that is given the defaultFields as an argument and returns an array of fields. Use this to customise the supported fields for stored addresses.

addressesCollectionOverride

CollectionOverride

Allows you to override the collection for addresses with a function where you can access the defaultCollection as an argument.

supportedCountries

CountryType[]

An array of supported countries in ISO 3166-1 alpha-2 format. Defaults to all countries.

You can add your own fields or modify the structure of the existing on in the collection. Example for overriding the default fields:

1
addresses: {
2
addressesCollectionOverride: ({ defaultCollection }) => ({
3
...defaultCollection,
4
fields: [
5
...defaultCollection.fields,
6
{
7
name: 'googleMapLocation',
8
label: 'Google Map Location',
9
type: 'text',
10
},
11
],
12
})
13
}

supportedCountries

The supportedCountries option is an array of country codes in ISO 3166-1 alpha-2 format. This is used to limit the countries that can be selected when creating or updating an address. If not provided, all countries will be supported. Currently used for storing addresses only.

You can import the default list of countries from the plugin:

1
import { defaultCountries } from '@payloadcms/plugin-ecommerce/client/react'

Carts

The carts option is used to configure the carts collection. Defaults to true which will create a carts collection with default fields. It also takes an object:

Option

Type

Description

cartsCollectionOverride

CollectionOverride

Allows you to override the collection for carts with a function where you can access the defaultCollection as an argument.

You can add your own fields or modify the structure of the existing on in the collection. Example for overriding the default fields:

1
carts: {
2
cartsCollectionOverride: ({ defaultCollection }) => ({
3
...defaultCollection,
4
fields: [
5
...defaultCollection.fields,
6
{
7
name: 'notes',
8
label: 'Notes',
9
type: 'textarea',
10
},
11
],
12
})
13
}

Carts are created when a customer adds their first item to the cart. The cart is then updated as they add or remove items. The cart is linked to a Customer via the customer field. If the user is authenticated, this will be set to their user ID. If the user is not authenticated, this will be null. If the user is not authenticated, the cart ID is stored in local storage and used to fetch the cart on subsequent requests. Access control by default works so that if the user is not authenticated then they can only access carts that have no customer linked to them.

Customers

The customers option is required and is used to provide the customers collection slug. This collection is used to link orders, carts, and addresses to a customer.

Option

Type

Description

slug

string

The slug of the customers collection.

While it's recommended to use just one collection for customers and your editors, you can use any collection you want for your customers. Just make sure that your access control is checking for the correct collections as well.

Currencies

The currencies option is used to configure the supported currencies by the store. Defaults to true which will support USD. It also takes an object:

Option

Type

Description

supportedCurrencies

Currency[]

An array of supported currencies by the store. Defaults to USD. See Currencies for available currencies.

defaultCurrency

string

The default currency code to use for the store. Defaults to the first currency. Must be one of the supportedCurrencies codes.

The Currency type is as follows:

1
type Currency = {
2
code: string // The currency code in ISO 4217 format, e.g. 'USD'
3
decimals: number // The number of decimal places for the currency, e.g. 2 for USD
4
label: string // A human-readable label for the currency, e.g. 'US Dollar'
5
symbol: string // The currency symbol, e.g. '$'
6
}

For example, to support JYP in addition to USD:

1
import { ecommercePlugin } from '@payloadcms/plugin-ecommerce'
2
import { USD } from '@payloadcms/plugin-ecommerce'
3
4
ecommercePlugin({
5
currencies: {
6
supportedCurrencies: [
7
USD,
8
{
9
code: 'JPY',
10
decimals: 0,
11
label: 'Japanese Yen',
12
symbol: 'Â¥',
13
},
14
],
15
defaultCurrency: 'USD',
16
},
17
})

Note that adding a new currency could generate a new schema migration as it adds new prices fields in your products.

We currently support the following currencies out of the box:

  • USD
  • EUR
  • GBP

You can import these from the plugin:

1
import { EUR } from '@payloadcms/plugin-ecommerce'

Inventory

The inventory option is used to enable or disable inventory tracking within Payload. It defaults to true. It also takes an object:

Option

Type

Description

fieldName

string

Override the field name used to track inventory. Defaults to inventory.

For now it's quite rudimentary tracking with no integrations to 3rd party services. It will simply add an inventory field to the variants collection and decrement the inventory when an order is placed.

Payments

The payments option is used to configure payments and supported payment methods.

Option

Type

Description

paymentMethods

array

An array of payment method adapters. Currently, only Stripe is supported. More

Payment adapters

The plugin supports payment adapters to integrate with different payment gateways. Currently, only the Stripe adapter is available. Adapters will provide a client side version as well with slightly different arguments.

Every adapter supports the following arguments in addition to their own:

Argument

Type

Description

label

string

Human readabale label for this payment adapter.

groupOverrides

GroupField with FieldsOverride

Use this to override the available fields for the payment adapter type.

Client side base arguments are the following:

Argument

Type

Description

label

string

Human readabale label for this payment adapter.

See the Stripe adapter for an example of client side arguments and the React section for usage.

groupOverrides

The groupOverrides option allows you to customize the fields that are available for a specific payment adapter. It takes a GroupField object with a fields function that receives the default fields and returns an array of fields. These fields are stored in transactions and can be used to collect additional information for the payment method. Stripe, for example, will track the paymentIntentID.

Example for overriding the default fields:

1
payments: {
2
paymentMethods: [
3
stripeAdapter({
4
secretKey: process.env.STRIPE_SECRET_KEY,
5
publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,
6
webhookSecret: process.env.STRIPE_WEBHOOKS_SIGNING_SECRET,
7
groupOverrides: {
8
fields: ({ defaultFields }) => {
9
return [
10
...defaultFields,
11
{
12
name: 'customField',
13
label: 'Custom Field',
14
type: 'text',
15
},
16
]
17
}
18
}
19
}),
20
],
21
},

Stripe Adapter

The Stripe adapter is used to integrate with the Stripe payment gateway. It requires a secret key, publishable key, and optionally webhook secret.

Argument

Type

Description

secretKey

string

Required for communicating with the Stripe API in the backend.

publishableKey

string

Required for communicating with the Stripe API in the client side.

webhookSecret

string

The webhook secret used to verify incoming webhook requests from Stripe.

webhooks

WebhookHandler[]

An array of webhook handlers to register within Payload's REST API for Stripe to callback.

apiVersion

string

The Stripe API version to use. See docs. This will be deprecated soon by Stripe's SDK, configure the API version in your Stripe Dashboard.

appInfo

object

The application info to pass to Stripe. See docs.

1
import { stripeAdapter } from '@payloadcms/plugin-ecommerce/payments/stripe'
2
3
stripeAdapter({
4
secretKey: process.env.STRIPE_SECRET_KEY!,
5
publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
6
webhookSecret: process.env.STRIPE_WEBHOOKS_SIGNING_SECRET!,
7
})

Stripe webhooks

The webhooks option allows you to register custom webhook handlers for Stripe events. This is useful if you want to handle specific events that are not covered by the default handlers provided by the plugin.

1
stripeAdapter({
2
webhooks: {
3
'payment_intent.succeeded': ({ event, req }) => {
4
// Access to Payload's req object and event data
5
},
6
},
7
}),

Stripe client side

On the client side, you can use the publishableKey to initialize Stripe and handle payments. The client side version of the adapter only requires the label and publishableKey arguments. Never expose the secretKey or webhookSecret keys on the client side.

1
import { stripeAdapterClient } from '@payloadcms/plugin-ecommerce/payments/stripe'
2
3
<EcommerceProvider
4
paymentMethods={[
5
stripeAdapterClient({
6
publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,
7
}),
8
]}
9
>
10
{children}
11
</EcommerceProvider>

Products

The products option is used to configure the products and variants collections. Defaults to true which will create products and variants collections with default fields. It also takes an object:

Option

Type

Description

productsCollectionOverride

CollectionOverride

Allows you to override the collection for products with a function where you can access the defaultCollection as an argument.

variants

boolean object

Configuration for the variants collection. Defaults to true. More

validation

ProductsValidation

Customise the validation used for checking products or variants before a transaction is created or a payment can be confirmed. More

You can add your own fields or modify the structure of the existing on in the collections. Example for overriding the default fields:

1
products: {
2
productsCollectionOverride: ({ defaultCollection }) => ({
3
...defaultCollection,
4
fields: [
5
...defaultCollection.fields,
6
{
7
name: 'notes',
8
label: 'Notes',
9
type: 'textarea',
10
},
11
],
12
})
13
}

Variants

The variants option is used to configure the variants collection. It takes an object:

Option

Type

Description

variantsCollectionOverride

CollectionOverride

Allows you to override the collection for variants with a function where you can access the defaultCollection as an argument.

variantTypesCollectionOverride

CollectionOverride

Allows you to override the collection for variantTypes with a function where you can access the defaultCollection as an argument.

variantOptionsCollectionOverride

CollectionOverride

Allows you to override the collection for variantOptions with a function where you can access the defaultCollection as an argument.

You can add your own fields or modify the structure of the existing on in the collection. Example for overriding the default fields:

1
variants: {
2
variantsCollectionOverride: ({ defaultCollection }) => ({
3
...defaultCollection,
4
fields: [
5
...defaultCollection.fields,
6
{
7
name: 'customField',
8
label: 'Custom Field',
9
type: 'text',
10
},
11
],
12
})
13
}

The key differences between these collections:

  • variantTypes are the types of variants that a product can have, e.g. Size, Color.
  • variantOptions are the options for each variant type, e.g. Small, Medium, Large for Size.
  • variants are the actual variants of a product, e.g. a T-Shirt in Size Small and Color Red.

Products validation

We use an addition validation step when creating transactions or confirming payments to ensure that the products and variants being purchased are valid. This is to prevent issues such as purchasing a product that is out of stock or has been deleted.

You can customise this validation by providing your own validation function via the validation option which receives the following arguments:

Option

Type

Description

currenciesConfig

CurrenciesConfig

The full currencies configuration provided in the plugin options.

product

TypedCollection

The product being purchased.

variant

TypedCollection

The variant being purchased, if a variant was selected for the product otherwise it will be undefined.

quantity

number

The quantity being purchased.

currency

string

The currency code being used for the purchase.

The function should throw an error if the product or variant is not valid. If the function does not throw an error, the product or variant is considered valid.

The default validation function checks for the following:

  • A currency is provided.
  • The product or variant has a price in the selected currency.
  • The product or variant has enough inventory for the requested quantity.
1
export const defaultProductsValidation: ProductsValidation = ({
2
currenciesConfig,
3
currency,
4
product,
5
quantity = 1,
6
variant,
7
}) => {
8
if (!currency) {
9
throw new Error('Currency must be provided for product validation.')
10
}
11
12
const priceField = `priceIn${currency.toUpperCase()}`
13
14
if (variant) {
15
if (!variant[priceField]) {
16
throw new Error(
17
`Variant with ID ${variant.id} does not have a price in ${currency}.`,
18
)
19
}
20
21
if (
22
variant.inventory === 0 ||
23
(variant.inventory && variant.inventory < quantity)
24
) {
25
throw new Error(
26
`Variant with ID ${variant.id} is out of stock or does not have enough inventory.`,
27
)
28
}
29
} else if (product) {
30
// Validate the product's details only if the variant is not provided as it can have its own inventory and price
31
if (!product[priceField]) {
32
throw new Error(`Product does not have a price in.`, {
33
cause: { code: MissingPrice, codes: [product.id, currency] },
34
})
35
}
36
37
if (
38
product.inventory === 0 ||
39
(product.inventory && product.inventory < quantity)
40
) {
41
throw new Error(
42
`Product is out of stock or does not have enough inventory.`,
43
{
44
cause: { code: OutOfStock, codes: [product.id] },
45
},
46
)
47
}
48
}
49
}

Orders

The orders option is used to configure the orders collection. Defaults to true which will create an orders collection with default fields. It also takes an object:

Option

Type

Description

ordersCollectionOverride

CollectionOverride

Allows you to override the collection for orders with a function where you can access the defaultCollection as an argument.

You can add your own fields or modify the structure of the existing on in the collection. Example for overriding the default fields:

1
orders: {
2
ordersCollectionOverride: ({ defaultCollection }) => ({
3
...defaultCollection,
4
fields: [
5
...defaultCollection.fields,
6
{
7
name: 'notes',
8
label: 'Notes',
9
type: 'textarea',
10
},
11
],
12
})
13
}

Transactions

The transactions option is used to configure the transactions collection. Defaults to true which will create a transactions collection with default fields. It also takes an object:

Option

Type

Description

transactionsCollectionOverride

CollectionOverride

Allows you to override the collection for transactions with a function where you can access the defaultCollection as an argument.

You can add your own fields or modify the structure of the existing on in the collection. Example for overriding the default fields:

1
transactions: {
2
transactionsCollectionOverride: ({ defaultCollection }) => ({
3
...defaultCollection,
4
fields: [
5
...defaultCollection.fields,
6
{
7
name: 'notes',
8
label: 'Notes',
9
type: 'textarea',
10
},
11
],
12
})
13
}
Next

Ecommerce Frontend