Stripe Plugin

NPM

With this plugin you can easily integrate Stripe into Payload. Simply provide your Stripe credentials and this plugin will open up a two-way communication channel between the two platforms. This enables you to easily sync data back and forth, as well as proxy the Stripe REST API through Payload's access control. Use this plugin to completely offload billing to Stripe and retain full control over your application's data.

For example, you might be building an e-commerce or SaaS application, where you have a products or a plans collection that requires either a one-time payment or a subscription. You can to tie each of these products to Stripe, then easily subscribe to billing-related events to perform your application's business logic, such as active purchases or subscription cancellations.

To build a checkout flow on your front-end you can either use Stripe Checkout, or you can also build a completely custom checkout experience from scratch using Stripe Web Elements. Then to build fully custom, secure customer dashboards, you can leverage Payload's access control to restrict access to your Stripe resources so your users never have to leave your site to manage their accounts.

The beauty of this plugin is the entirety of your application's content and business logic can be handled in Payload while Stripe handles solely the billing and payment processing. You can build a completely proprietary application that is endlessly customizable and extendable, on APIs and databases that you own. Hosted services like Shopify or BigCommerce might fracture your application's content then charge you for access.

Core features
  • Hides your Stripe credentials when shipping SaaS applications
  • Allows restricted keys through Payload access control
  • Enables a two-way communication channel between Stripe and Payload
  • Proxies the Stripe REST API
  • Proxies Stripe webhooks
  • Automatically syncs data between the two platforms

Installation

Install the plugin using any JavaScript package manager like Yarn, NPM, or PNPM:

1
yarn add @payloadcms/plugin-stripe

Basic Usage

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

1
import { buildConfig } from 'payload/config'
2
import stripePlugin from '@payloadcms/plugin-stripe'
3
4
const config = buildConfig({
5
plugins: [
6
stripePlugin({
7
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
8
}),
9
],
10
})
11
12
export default config

Options

OptionTypeDefaultDescription
stripeSecretKey *stringundefinedYour Stripe secret key
stripeWebhooksEndpointSecretstringundefinedYour Stripe webhook endpoint secret
restbooleanfalseWhen true, opens the /api/stripe/rest endpoint
webhooksobject | functionundefinedEither a function to handle all webhooks events, or an object of Stripe webhook handlers, keyed to the name of the event
syncarrayundefinedAn array of sync configs
logsbooleanfalseWhen true, logs sync events to the console as they happen

* An asterisk denotes that a property is required.

Endpoints

The following custom endpoints are automatically opened for you:

EndpointMethodDescription
/api/stripe/restPOSTProxies the Stripe REST API behind Payload access control and returns the result. See the REST Proxy section for more details.
/api/stripe/webhooksPOSTHandles all Stripe webhook events
Stripe REST Proxy

If rest is true, proxies the Stripe REST API behind Payload access control and returns the result. If you need to proxy the API server-side, use the stripeProxy function.

1
const res = await fetch(`/api/stripe/rest`, {
2
method: 'POST',
3
credentials: 'include',
4
headers: {
5
'Content-Type': 'application/json',
6
// Authorization: `JWT ${token}` // NOTE: do this if not in a browser (i.e. curl or Postman)
7
},
8
body: JSON.stringify({
9
stripeMethod: 'stripe.subscriptions.list',
10
stripeArgs: [
11
{
12
customer: 'abc',
13
},
14
],
15
}),
16
})

Webhooks

Stripe webhooks are used to sync from Stripe to Payload. Webhooks listen for events on your Stripe account so you can trigger reactions to them. Follow the steps below to enable webhooks.

Development:

  1. Login using Stripe cli stripe login
  2. Forward events to localhost stripe listen --forward-to localhost:3000/api/stripe/webhooks
  3. Paste the given secret into your .env file as STRIPE_WEBHOOKS_ENDPOINT_SECRET

Production:

  1. Login and create a new webhook from the Stripe dashboard
  2. Paste YOUR_DOMAIN_NAME/api/stripe/webhooks as the "Webhook Endpoint URL"
  3. Select which events to broadcast
  4. Paste the given secret into your .env file as STRIPE_WEBHOOKS_ENDPOINT_SECRET
  5. Then, handle these events using the webhooks portion of this plugin's config:
1
import { buildConfig } from 'payload/config'
2
import stripePlugin from '@payloadcms/plugin-stripe'
3
4
const config = buildConfig({
5
plugins: [
6
stripePlugin({
7
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
8
stripeWebhooksEndpointSecret: process.env.STRIPE_WEBHOOKS_ENDPOINT_SECRET,
9
webhooks: {
10
'customer.subscription.updated': ({ event, stripe, stripeConfig }) => {
11
// do something...
12
},
13
},
14
// NOTE: you can also catch all Stripe webhook events and handle the event types yourself
15
// webhooks: (event, stripe, stripeConfig) => {
16
// switch (event.type): {
17
// case 'customer.subscription.updated': {
18
// // do something...
19
// break;
20
// }
21
// default: {
22
// break;
23
// }
24
// }
25
// }
26
}),
27
],
28
})
29
30
export default config

For a full list of available webhooks, see here.

Node

On the server you should interface with Stripe directly using the stripe npm module. That might look something like this:

1
import Stripe from 'stripe'
2
3
const stripeSecretKey = process.env.STRIPE_SECRET_KEY
4
const stripe = new Stripe(stripeSecretKey, { apiVersion: '2022-08-01' })
5
6
export const MyFunction = async () => {
7
try {
8
const customer = await stripe.customers.create({
9
email: data.email,
10
})
11
12
// do something...
13
} catch (error) {
14
console.error(error.message)
15
}
16
}

Alternatively, you can interface with the Stripe using the stripeProxy, which is exactly what the /api/stripe/rest endpoint does behind-the-scenes. Here's the same example as above, but piped through the proxy:

1
import { stripeProxy } from '@payloadcms/plugin-stripe'
2
3
export const MyFunction = async () => {
4
try {
5
const customer = await stripeProxy({
6
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
7
stripeMethod: 'customers.create',
8
stripeArgs: [
9
{
10
email: data.email,
11
},
12
],
13
})
14
15
if (customer.status === 200) {
16
// do something...
17
}
18
19
if (customer.status >= 400) {
20
throw new Error(customer.message)
21
}
22
} catch (error) {
23
console.error(error.message)
24
}
25
}

Sync

This option will setup a basic sync between Payload collections and Stripe resources for you automatically. It will create all the necessary hooks and webhooks handlers, so the only thing you have to do is map your Payload fields to their corresponding Stripe properties. As documents are created, updated, and deleted from either Stripe or Payload, the changes are reflected on either side.

1
import { buildConfig } from 'payload/config'
2
import stripePlugin from '@payloadcms/plugin-stripe'
3
4
const config = buildConfig({
5
plugins: [
6
stripePlugin({
7
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
8
stripeWebhooksEndpointSecret: process.env.STRIPE_WEBHOOKS_ENDPOINT_SECRET,
9
sync: [
10
{
11
collection: 'customers',
12
stripeResourceType: 'customers',
13
stripeResourceTypeSingular: 'customer',
14
fields: [
15
{
16
fieldPath: 'name', // this is a field on your own Payload config
17
stripeProperty: 'name', // use dot notation, if applicable
18
},
19
],
20
},
21
],
22
}),
23
],
24
})
25
26
export default config

Using sync will do the following:

  • Adds and maintains a stripeID read-only field on each collection, this is a field generated by Stripe and used as a cross-reference
  • Adds a direct link to the resource on Stripe.com
  • Adds and maintains an skipSync read-only flag on each collection to prevent infinite syncs when hooks trigger webhooks
  • Adds the following hooks to each collection:
    • beforeValidate: createNewInStripe
    • beforeChange: syncExistingWithStripe
    • afterDelete: deleteFromStripe
  • Handles the following Stripe webhooks
    • STRIPE_TYPE.created: handleCreatedOrUpdated
    • STRIPE_TYPE.updated: handleCreatedOrUpdated
    • STRIPE_TYPE.deleted: handleDeleted

TypeScript

All types can be directly imported:

1
import {
2
StripeConfig,
3
StripeWebhookHandler,
4
StripeProxy,
5
...
6
} from '@payloadcms/plugin-stripe/types';

Examples

The Templates Directory contains an official E-commerce Template which demonstrates exactly how to configure this plugin in Payload and implement it on your front-end. You can also check out How to Build An E-Commerce Site With Next.js post for a bit more context around this template.

Next

Building Your Own Plugin