Last active
January 27, 2023 22:16
-
-
Save cookernetes/a3c478b722e8f794408b8bae34732497 to your computer and use it in GitHub Desktop.
Stripe + Payload CMS Integration for easy product management :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { CollectionBeforeChangeHook } from "payload/types"; | |
import Stripe from "stripe"; | |
export const syncWithStripe: CollectionBeforeChangeHook = async ({ | |
operation, | |
data, | |
originalDoc, | |
}) => { | |
const stripe = new Stripe(process.env.T_STRIPE_SECRET!, { | |
apiVersion: "2022-11-15", | |
}); | |
if (operation === "create") { | |
const product = await stripe.products.create({ | |
name: data.name, | |
active: true, | |
description: data.description, | |
default_price_data: { | |
currency: "GBP", | |
unit_amount: data.price * 100, | |
}, | |
}); | |
return { | |
...data, | |
stripeProductID: product.id, | |
stripePriceID: product.default_price, | |
}; | |
} else if (operation === "update") { | |
await stripe.products.update(originalDoc.stripeProductID, { | |
name: data.name, | |
active: true, | |
description: data.description, | |
}); | |
if (data.price !== originalDoc.price) { | |
const newPrice = await stripe.prices.create({ | |
product: originalDoc.stripeProductID, | |
currency: "GBP", | |
unit_amount: data.price * 100, | |
}); | |
await stripe.products.update(originalDoc.stripeProductID, { | |
default_price: newPrice.id, | |
}); | |
await stripe.prices.update(originalDoc.stripePriceID, { | |
active: false, | |
}); | |
return { | |
...data, | |
stripePriceID: newPrice.id, | |
}; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment