Skip to content

Commit

Permalink
feat(plugin-stripe): update plugin stripe for v3 (#6019)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulpopus committed May 6, 2024
1 parent 665541a commit cff43ef
Show file tree
Hide file tree
Showing 19 changed files with 105 additions and 100 deletions.
25 changes: 15 additions & 10 deletions packages/plugin-stripe/package.json
Expand Up @@ -24,8 +24,8 @@
"exports": {
".": {
"import": "./src/index.ts",
"require": "./src/index.ts",
"types": "./src/index.ts"
"types": "./src/index.ts",
"default": "./src/index.ts"
}
},
"main": "./src/index.ts",
Expand All @@ -36,12 +36,14 @@
"types.d.ts"
],
"scripts": {
"build": "echo \"Build temporarily disabled.\" && exit 0",
"build": "pnpm copyfiles && pnpm build:swc && pnpm build:types",
"build:swc": "swc ./src -d ./dist --config-file .swcrc",
"build:types": "tsc --emitDeclarationOnly --outDir dist",
"clean": "rimraf {dist,*.tsbuildinfo}",
"prepublishOnly": "pnpm clean && pnpm turbo run build && pnpm test",
"test": "echo 'No tests available.'"
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
"lint": "eslint src",
"lint:fix": "eslint --fix --ext .ts,.tsx src",
"prepublishOnly": "pnpm clean && pnpm turbo build"
},
"dependencies": {
"@payloadcms/ui": "workspace:*",
Expand All @@ -51,17 +53,19 @@
},
"devDependencies": {
"@payloadcms/eslint-config": "workspace:*",
"@payloadcms/next": "workspace:*",
"@payloadcms/translations": "workspace:*",
"@payloadcms/ui": "workspace:*",
"@types/express": "^4.17.9",
"@types/lodash.get": "^4.4.7",
"@types/react": "18.2.74",
"@types/uuid": "^9.0.0",
"payload": "workspace:*",
"prettier": "^2.7.1",
"webpack": "^5.78.0"
"payload": "workspace:*"
},
"peerDependencies": {
"payload": "workspace:*",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
"@payloadcms/translations": "workspace:*",
"@payloadcms/ui": "workspace:*",
"payload": "workspace:*"
},
"publishConfig": {
"exports": {
Expand All @@ -72,6 +76,7 @@
}
},
"main": "./dist/index.js",
"registry": "https://registry.npmjs.org/",
"types": "./dist/index.d.ts"
},
"homepage:": "https://payloadcms.com"
Expand Down
8 changes: 3 additions & 5 deletions packages/plugin-stripe/src/admin.ts
@@ -1,10 +1,10 @@
import type { Config } from 'payload/config'

import type { SanitizedStripeConfig, StripeConfig } from './types'
import type { SanitizedStripeConfig, StripeConfig } from './types.js'

import { getFields } from './fields/getFields'
import { getFields } from './fields/getFields.js'

const stripePlugin =
export const stripePlugin =
(incomingStripeConfig: StripeConfig) =>
(config: Config): Config => {
const { collections } = config
Expand Down Expand Up @@ -42,5 +42,3 @@ const stripePlugin =
}),
}
}

export default stripePlugin
17 changes: 8 additions & 9 deletions packages/plugin-stripe/src/fields/getFields.ts
@@ -1,8 +1,8 @@
import type { CollectionConfig, Field } from 'payload/types'

import type { SanitizedStripeConfig } from '../types'
import type { SanitizedStripeConfig } from '../types.js'

import { LinkToDoc } from '../ui/LinkToDoc'
import { LinkToDoc } from '../ui/LinkToDoc.js'

interface Args {
collection: CollectionConfig
Expand Down Expand Up @@ -39,13 +39,12 @@ export const getFields = ({ collection, stripeConfig, syncConfig }: Args): Field
type: 'ui',
admin: {
components: {
Field: (args) =>
LinkToDoc({
...args,
isTestKey: stripeConfig.isTestKey,
nameOfIDField: 'stripeID',
stripeResourceType: syncConfig.stripeResourceType,
}),
Field: LinkToDoc,
},
custom: {
isTestKey: stripeConfig.isTestKey,
nameOfIDField: 'stripeID',
stripeResourceType: syncConfig.stripeResourceType,
},
position: 'sidebar',
},
Expand Down
20 changes: 13 additions & 7 deletions packages/plugin-stripe/src/hooks/createNewInStripe.ts
Expand Up @@ -3,11 +3,12 @@ import type { CollectionBeforeValidateHook, CollectionConfig } from 'payload/typ
import { APIError } from 'payload/errors'
import Stripe from 'stripe'

import type { StripeConfig } from '../types'
import type { StripeConfig } from '../types.js'

import { deepen } from '../utilities/deepen'
import { deepen } from '../utilities/deepen.js'

const stripeSecretKey = process.env.STRIPE_SECRET_KEY
// api version can only be the latest, stripe recommends ts ignoring it
const stripe = new Stripe(stripeSecretKey || '', { apiVersion: '2022-08-01' })

type HookArgsWithCustomCollection = Omit<
Expand Down Expand Up @@ -52,12 +53,15 @@ export const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (ar

if (syncConfig) {
// combine all fields of this object and match their respective values within the document
let syncedFields = syncConfig.fields.reduce((acc, field) => {
const { fieldPath, stripeProperty } = field
let syncedFields = syncConfig.fields.reduce(
(acc, field) => {
const { fieldPath, stripeProperty } = field

acc[stripeProperty] = dataRef[fieldPath]
return acc
}, {} as Record<string, any>)
acc[stripeProperty] = dataRef[fieldPath]
return acc
},
{} as Record<string, any>,
)

syncedFields = deepen(syncedFields)

Expand All @@ -72,6 +76,7 @@ export const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (ar
try {
// NOTE: Typed as "any" because the "create" method is not standard across all Stripe resources
const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(
// @ts-expect-error
syncedFields,
)

Expand Down Expand Up @@ -105,6 +110,7 @@ export const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (ar

// NOTE: Typed as "any" because the "create" method is not standard across all Stripe resources
const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(
// @ts-expect-error
syncedFields,
)

Expand Down
3 changes: 2 additions & 1 deletion packages/plugin-stripe/src/hooks/deleteFromStripe.ts
Expand Up @@ -3,9 +3,10 @@ import type { CollectionAfterDeleteHook, CollectionConfig } from 'payload/types'
import { APIError } from 'payload/errors'
import Stripe from 'stripe'

import type { StripeConfig } from '../types'
import type { StripeConfig } from '../types.js'

const stripeSecretKey = process.env.STRIPE_SECRET_KEY
// api version can only be the latest, stripe recommends ts ignoring it
const stripe = new Stripe(stripeSecretKey || '', { apiVersion: '2022-08-01' })

type HookArgsWithCustomCollection = Omit<Parameters<CollectionAfterDeleteHook>[0], 'collection'> & {
Expand Down
20 changes: 12 additions & 8 deletions packages/plugin-stripe/src/hooks/syncExistingWithStripe.ts
Expand Up @@ -3,11 +3,12 @@ import type { CollectionBeforeChangeHook, CollectionConfig } from 'payload/types
import { APIError } from 'payload/errors'
import Stripe from 'stripe'

import type { StripeConfig } from '../types'
import type { StripeConfig } from '../types.js'

import { deepen } from '../utilities/deepen'
import { deepen } from '../utilities/deepen.js'

const stripeSecretKey = process.env.STRIPE_SECRET_KEY
// api version can only be the latest, stripe recommends ts ignoring it
const stripe = new Stripe(stripeSecretKey || '', { apiVersion: '2022-08-01' })

type HookArgsWithCustomCollection = Omit<
Expand Down Expand Up @@ -39,12 +40,15 @@ export const syncExistingWithStripe: CollectionBeforeChangeHookWithArgs = async
if (syncConfig) {
if (operation === 'update') {
// combine all fields of this object and match their respective values within the document
let syncedFields = syncConfig.fields.reduce((acc, field) => {
const { fieldPath, stripeProperty } = field

acc[stripeProperty] = data[fieldPath]
return acc
}, {} as Record<string, any>)
let syncedFields = syncConfig.fields.reduce(
(acc, field) => {
const { fieldPath, stripeProperty } = field

acc[stripeProperty] = data[fieldPath]
return acc
},
{} as Record<string, any>,
)

syncedFields = deepen(syncedFields)

Expand Down
7 changes: 4 additions & 3 deletions packages/plugin-stripe/src/index.ts
Expand Up @@ -9,7 +9,10 @@ import { syncExistingWithStripe } from './hooks/syncExistingWithStripe.js'
import { stripeREST } from './routes/rest.js'
import { stripeWebhooks } from './routes/webhooks.js'

const stripePlugin =
export { LinkToDoc } from './ui/LinkToDoc.js'
export { stripeProxy } from './utilities/stripeProxy.js'

export const stripePlugin =
(incomingStripeConfig: StripeConfig) =>
(config: Config): Config => {
const { collections } = config
Expand Down Expand Up @@ -112,5 +115,3 @@ const stripePlugin =
endpoints,
}
}

export default stripePlugin
9 changes: 0 additions & 9 deletions packages/plugin-stripe/src/mocks/mockFile.js

This file was deleted.

2 changes: 2 additions & 0 deletions packages/plugin-stripe/src/routes/rest.ts
Expand Up @@ -33,7 +33,9 @@ export const stripeREST = async (args: {
}

responseJSON = await stripeProxy({
// @ts-expect-error
stripeArgs,
// @ts-expect-error
stripeMethod,
stripeSecretKey,
})
Expand Down
8 changes: 3 additions & 5 deletions packages/plugin-stripe/src/routes/webhooks.ts
Expand Up @@ -19,24 +19,22 @@ export const stripeWebhooks = async (args: {

if (stripeWebhooksEndpointSecret) {
const stripe = new Stripe(stripeSecretKey, {
// api version can only be the latest, stripe recommends ts ignoring it
apiVersion: '2022-08-01',
appInfo: {
name: 'Stripe Payload Plugin',
url: 'https://payloadcms.com',
},
})

const body = await req.text()
const stripeSignature = req.headers.get('stripe-signature')

if (stripeSignature) {
let event: Stripe.Event | undefined

try {
event = stripe.webhooks.constructEvent(
await req.text(),
stripeSignature,
stripeWebhooksEndpointSecret,
)
event = stripe.webhooks.constructEvent(body, stripeSignature, stripeWebhooksEndpointSecret)
} catch (err: unknown) {
const msg: string = err instanceof Error ? err.message : JSON.stringify(err)
req.payload.logger.error(`Error constructing Stripe event: ${msg}`)
Expand Down
14 changes: 6 additions & 8 deletions packages/plugin-stripe/src/ui/LinkToDoc.tsx
@@ -1,17 +1,15 @@
'use client'
import type { CustomComponent } from 'payload/config'
import type { UIField } from 'payload/types'

import { useFieldProps } from '@payloadcms/ui/forms/FieldPropsProvider'
// import CopyToClipboard from 'payload/dist/admin/components/elements/CopyToClipboard'
import { useFormFields } from '@payloadcms/ui/forms/Form'
import React from 'react'

export const LinkToDoc: React.FC<
UIField & {
isTestKey: boolean
nameOfIDField: string
stripeResourceType: string
}
> = (props) => {
const { isTestKey, nameOfIDField, stripeResourceType } = props
export const LinkToDoc: CustomComponent<UIField> = () => {
const { custom } = useFieldProps()
const { isTestKey, nameOfIDField, stripeResourceType } = custom

const field = useFormFields(([fields]) => fields[nameOfIDField])
const { value: stripeID } = field || {}
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-stripe/src/utilities/stripeProxy.ts
@@ -1,7 +1,7 @@
import lodashGet from 'lodash.get'
import Stripe from 'stripe'

import type { StripeProxy } from '../types'
import type { StripeProxy } from '../types.js'

export const stripeProxy: StripeProxy = async ({ stripeArgs, stripeMethod, stripeSecretKey }) => {
const stripe = new Stripe(stripeSecretKey, {
Expand Down
17 changes: 10 additions & 7 deletions packages/plugin-stripe/src/webhooks/handleCreatedOrUpdated.ts
@@ -1,8 +1,8 @@
import { v4 as uuid } from 'uuid'

import type { SanitizedStripeConfig, StripeWebhookHandler } from '../types'
import type { SanitizedStripeConfig, StripeWebhookHandler } from '../types.js'

import { deepen } from '../utilities/deepen'
import { deepen } from '../utilities/deepen.js'

type HandleCreatedOrUpdated = (
args: Parameters<StripeWebhookHandler>[0] & {
Expand Down Expand Up @@ -62,12 +62,15 @@ export const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => {
const foundDoc = payloadQuery.docs[0] as any

// combine all properties of the Stripe doc and match their respective fields within the document
let syncedData = syncConfig.fields.reduce((acc, field) => {
const { fieldPath, stripeProperty } = field
let syncedData = syncConfig.fields.reduce(
(acc, field) => {
const { fieldPath, stripeProperty } = field

acc[fieldPath] = stripeDoc[stripeProperty]
return acc
}, {} as Record<string, any>)
acc[fieldPath] = stripeDoc[stripeProperty]
return acc
},
{} as Record<string, any>,
)

syncedData = deepen({
...syncedData,
Expand Down
3 changes: 2 additions & 1 deletion packages/plugin-stripe/src/webhooks/handleDeleted.ts
@@ -1,4 +1,4 @@
import type { SanitizedStripeConfig, StripeWebhookHandler } from '../types'
import type { SanitizedStripeConfig, StripeWebhookHandler } from '../types.js'

type HandleDeleted = (
args: Parameters<StripeWebhookHandler>[0] & {
Expand Down Expand Up @@ -58,6 +58,7 @@ export const handleDeleted: HandleDeleted = async (args) => {
if (logs) payload.logger.info(`- Deleting Payload document with ID: '${foundDoc.id}'...`)

try {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
payload.delete({
id: foundDoc.id,
collection: collectionSlug,
Expand Down
14 changes: 7 additions & 7 deletions packages/plugin-stripe/src/webhooks/index.ts
@@ -1,9 +1,9 @@
import type { StripeWebhookHandler } from '../types'
import type { StripeWebhookHandler } from '../types.js'

import { handleCreatedOrUpdated } from './handleCreatedOrUpdated'
import { handleDeleted } from './handleDeleted'
import { handleCreatedOrUpdated } from './handleCreatedOrUpdated.js'
import { handleDeleted } from './handleDeleted.js'

export const handleWebhooks: StripeWebhookHandler = async (args) => {
export const handleWebhooks: StripeWebhookHandler = (args) => {
const { event, payload, stripeConfig } = args

if (stripeConfig?.logs)
Expand All @@ -21,7 +21,7 @@ export const handleWebhooks: StripeWebhookHandler = async (args) => {
if (syncConfig) {
switch (method) {
case 'created': {
await handleCreatedOrUpdated({
void handleCreatedOrUpdated({
...args,
resourceType,
stripeConfig,
Expand All @@ -30,7 +30,7 @@ export const handleWebhooks: StripeWebhookHandler = async (args) => {
break
}
case 'updated': {
await handleCreatedOrUpdated({
void handleCreatedOrUpdated({
...args,
resourceType,
stripeConfig,
Expand All @@ -39,7 +39,7 @@ export const handleWebhooks: StripeWebhookHandler = async (args) => {
break
}
case 'deleted': {
await handleDeleted({
void handleDeleted({
...args,
resourceType,
stripeConfig,
Expand Down

0 comments on commit cff43ef

Please sign in to comment.