- Sponsor
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
update stripe sdk and webhooks to match #427
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
8c978ee
b759d63
df84c5b
24c6967
147e0f5
1041d5e
2061222
3b52486
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,7 +2,6 @@ import type { StripeMode } from './paymentProcessor'; | |
|
||
import Stripe from 'stripe'; | ||
import { stripe } from './stripeClient'; | ||
import { assertUnreachable } from '../../shared/utils'; | ||
|
||
// WASP_WEB_CLIENT_URL will be set up by Wasp when deploying to production: https://wasp.sh/docs/deploying | ||
const DOMAIN = process.env.WASP_WEB_CLIENT_URL || 'http://localhost:3000'; | ||
|
@@ -41,8 +40,6 @@ export async function createStripeCheckoutSession({ | |
mode, | ||
}: CreateStripeCheckoutSessionParams) { | ||
try { | ||
const paymentIntentData = getPaymentIntentData({ mode, priceId }); | ||
|
||
return await stripe.checkout.sessions.create({ | ||
line_items: [ | ||
{ | ||
|
@@ -54,33 +51,14 @@ export async function createStripeCheckoutSession({ | |
success_url: `${DOMAIN}/checkout?success=true`, | ||
cancel_url: `${DOMAIN}/checkout?canceled=true`, | ||
automatic_tax: { enabled: true }, | ||
allow_promotion_codes: true, | ||
customer_update: { | ||
address: 'auto', | ||
}, | ||
customer: customerId, | ||
// Stripe only allows us to pass payment intent metadata for one-time payments, not subscriptions. | ||
// We do this so that we can capture priceId in the payment_intent.succeeded webhook | ||
// and easily confirm the user's payment based on the price id. For subscriptions, we can get the price id | ||
// in the customer.subscription.updated webhook via the line_items field. | ||
payment_intent_data: paymentIntentData, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we're no longer dealing with payment intents to handle one-time payment products. these are now just getting handled directly in checkout.session.completed. |
||
}); | ||
} catch (error) { | ||
console.error(error); | ||
throw error; | ||
} | ||
} | ||
|
||
function getPaymentIntentData({ mode, priceId }: { mode: StripeMode; priceId: string }): | ||
| { | ||
metadata: { priceId: string }; | ||
} | ||
| undefined { | ||
switch (mode) { | ||
case 'subscription': | ||
return undefined; | ||
case 'payment': | ||
return { metadata: { priceId } }; | ||
default: | ||
assertUnreachable(mode); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,7 +2,7 @@ import type { SubscriptionStatus } from '../plans'; | |
import { PaymentPlanId } from '../plans'; | ||
import { PrismaClient } from '@prisma/client'; | ||
|
||
export const updateUserStripePaymentDetails = ( | ||
export const updateUserStripePaymentDetails = async ( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why the |
||
{ userStripeId, subscriptionPlan, subscriptionStatus, datePaid, numOfCreditsPurchased }: { | ||
userStripeId: string; | ||
subscriptionPlan?: PaymentPlanId; | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,5 +8,5 @@ export const stripe = new Stripe(requireNodeEnvVar('STRIPE_API_KEY'), { | |
// npm package to the API version that matches your Stripe dashboard's one. | ||
// For more details and alternative setups check | ||
// https://docs.stripe.com/api/versioning . | ||
apiVersion: '2022-11-15', | ||
apiVersion: '2025-04-30.basil', | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixes issue #229 |
||
}); |
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
|
@@ -9,11 +9,9 @@ import { updateUserStripePaymentDetails } from './paymentDetails'; | |||||||||
import { emailSender } from 'wasp/server/email'; | ||||||||||
import { assertUnreachable } from '../../shared/utils'; | ||||||||||
import { requireNodeEnvVar } from '../../server/utils'; | ||||||||||
import { z } from 'zod'; | ||||||||||
import { | ||||||||||
parseWebhookPayload, | ||||||||||
type InvoicePaidData, | ||||||||||
type PaymentIntentSucceededData, | ||||||||||
type SessionCompletedData, | ||||||||||
type SubscriptionDeletedData, | ||||||||||
type SubscriptionUpdatedData, | ||||||||||
|
@@ -32,9 +30,6 @@ export const stripeWebhook: PaymentsWebhook = async (request, response, context) | |||||||||
case 'invoice.paid': | ||||||||||
await handleInvoicePaid(data, prismaUserDelegate); | ||||||||||
break; | ||||||||||
case 'payment_intent.succeeded': | ||||||||||
await handlePaymentIntentSucceeded(data, prismaUserDelegate); | ||||||||||
break; | ||||||||||
case 'customer.subscription.updated': | ||||||||||
await handleCustomerSubscriptionUpdated(data, prismaUserDelegate); | ||||||||||
break; | ||||||||||
|
@@ -85,83 +80,64 @@ export const stripeMiddlewareConfigFn: MiddlewareConfigFn = (middlewareConfig) = | |||||||||
return middlewareConfig; | ||||||||||
}; | ||||||||||
|
||||||||||
// Because a checkout session completed could potentially result in a failed payment, | ||||||||||
// we can update the user's payment details here, but confirm credits or a subscription | ||||||||||
// if the payment succeeds in other, more specific, webhooks. | ||||||||||
export async function handleCheckoutSessionCompleted( | ||||||||||
// Here we only update the user's payment details, and confirm credits because Stripe does not send invoices for one-time payments. | ||||||||||
// NOTE: If you're accepting async payment methods like bank transfers or SEPA and not just card payments | ||||||||||
// which are synchronous, checkout session completed could potentially result in a pending payment. | ||||||||||
// If so, use the checkout.session.async_payment_succeeded event to confirm the payment. | ||||||||||
Comment on lines
+85
to
+86
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Makes it clearer what we're talking about. |
||||||||||
async function handleCheckoutSessionCompleted( | ||||||||||
session: SessionCompletedData, | ||||||||||
prismaUserDelegate: PrismaClient['user'] | ||||||||||
) { | ||||||||||
const userStripeId = session.customer; | ||||||||||
const lineItems = await getSubscriptionLineItemsBySessionId(session.id); | ||||||||||
const isSuccessfulOneTimePayment = session.mode === 'payment' && session.payment_status === 'paid'; | ||||||||||
if (isSuccessfulOneTimePayment) { | ||||||||||
await saveSuccessfulOneTimePayment(session, prismaUserDelegate); | ||||||||||
} | ||||||||||
} | ||||||||||
|
||||||||||
async function saveSuccessfulOneTimePayment( | ||||||||||
session: SessionCompletedData, | ||||||||||
prismaUserDelegate: PrismaClient['user'] | ||||||||||
) { | ||||||||||
const userStripeId = session.customer; | ||||||||||
const lineItems = await getCheckoutLineItemsBySessionId(session.id); | ||||||||||
const lineItemPriceId = extractPriceId(lineItems); | ||||||||||
|
||||||||||
const planId = getPlanIdByPriceId(lineItemPriceId); | ||||||||||
const plan = paymentPlans[planId]; | ||||||||||
if (plan.effect.kind === 'credits') { | ||||||||||
return; | ||||||||||
} | ||||||||||
const { subscriptionPlan } = getPlanEffectPaymentDetails({ planId, planEffect: plan.effect }); | ||||||||||
const { numOfCreditsPurchased } = getPlanEffectPaymentDetails({ planId, planEffect: plan.effect }); | ||||||||||
return updateUserStripePaymentDetails( | ||||||||||
{ userStripeId, numOfCreditsPurchased, datePaid: new Date() }, | ||||||||||
prismaUserDelegate | ||||||||||
); | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. due to updates to the webhook events on Stripe's side, we can now process credits-based payments and subscriptions within the same endpoint. If it's a subscription payment, There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think your sentence got cut off in editing 😄 |
||||||||||
} | ||||||||||
|
||||||||||
return updateUserStripePaymentDetails({ userStripeId, subscriptionPlan }, prismaUserDelegate); | ||||||||||
// This is called when a subscription is successfully purchased or renewed and payment succeeds. | ||||||||||
// Invoices are not created for one-time payments, so we handle them above. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of "above," let's say where we handle them. |
||||||||||
async function handleInvoicePaid(invoice: InvoicePaidData, prismaUserDelegate: PrismaClient['user']) { | ||||||||||
await saveActiveSubscription(invoice, prismaUserDelegate); | ||||||||||
} | ||||||||||
|
||||||||||
// This is called when a subscription is purchased or renewed and payment succeeds. | ||||||||||
// Invoices are not created for one-time payments, so we handle them in the payment_intent.succeeded webhook. | ||||||||||
export async function handleInvoicePaid(invoice: InvoicePaidData, prismaUserDelegate: PrismaClient['user']) { | ||||||||||
async function saveActiveSubscription(invoice: InvoicePaidData, prismaUserDelegate: PrismaClient['user']) { | ||||||||||
const userStripeId = invoice.customer; | ||||||||||
const datePaid = new Date(invoice.period_start * 1000); | ||||||||||
return updateUserStripePaymentDetails({ userStripeId, datePaid }, prismaUserDelegate); | ||||||||||
} | ||||||||||
|
||||||||||
export async function handlePaymentIntentSucceeded( | ||||||||||
paymentIntent: PaymentIntentSucceededData, | ||||||||||
prismaUserDelegate: PrismaClient['user'] | ||||||||||
) { | ||||||||||
// We handle invoices in the invoice.paid webhook. Invoices exist for subscription payments, | ||||||||||
// but not for one-time payment/credits products which use the Stripe `payment` mode on checkout sessions. | ||||||||||
if (paymentIntent.invoice) { | ||||||||||
return; | ||||||||||
} | ||||||||||
|
||||||||||
const userStripeId = paymentIntent.customer; | ||||||||||
const datePaid = new Date(paymentIntent.created * 1000); | ||||||||||
|
||||||||||
// We capture the price id from the payment intent metadata | ||||||||||
// that we passed in when creating the checkout session in checkoutUtils.ts. | ||||||||||
const { metadata } = paymentIntent; | ||||||||||
|
||||||||||
if (!metadata.priceId) { | ||||||||||
throw new HttpError(400, 'No price id found in payment intent'); | ||||||||||
} | ||||||||||
|
||||||||||
const planId = getPlanIdByPriceId(metadata.priceId); | ||||||||||
const plan = paymentPlans[planId]; | ||||||||||
if (plan.effect.kind === 'subscription') { | ||||||||||
return; | ||||||||||
} | ||||||||||
|
||||||||||
const { numOfCreditsPurchased } = getPlanEffectPaymentDetails({ planId, planEffect: plan.effect }); | ||||||||||
|
||||||||||
const priceId = extractPriceId(invoice.lines); | ||||||||||
const subscriptionPlan = getPlanIdByPriceId(priceId); | ||||||||||
return updateUserStripePaymentDetails( | ||||||||||
{ userStripeId, numOfCreditsPurchased, datePaid }, | ||||||||||
{ userStripeId, datePaid, subscriptionPlan, subscriptionStatus: SubscriptionStatus.Active }, | ||||||||||
prismaUserDelegate | ||||||||||
); | ||||||||||
} | ||||||||||
|
||||||||||
export async function handleCustomerSubscriptionUpdated( | ||||||||||
async function handleCustomerSubscriptionUpdated( | ||||||||||
subscription: SubscriptionUpdatedData, | ||||||||||
prismaUserDelegate: PrismaClient['user'] | ||||||||||
) { | ||||||||||
const userStripeId = subscription.customer; | ||||||||||
let subscriptionStatus: SubscriptionStatus | undefined; | ||||||||||
|
||||||||||
const priceId = extractPriceId(subscription.items); | ||||||||||
const subscriptionPlan = getPlanIdByPriceId(priceId); | ||||||||||
|
||||||||||
// There are other subscription statuses, such as `trialing` that we are not handling and simply ignore | ||||||||||
// If you'd like to handle more statuses, you can add more cases above. Make sure to update the `SubscriptionStatus` type in `payment/plans.ts` as well | ||||||||||
// If you'd like to handle more statuses, you can add more cases above. Make sure to update the `SubscriptionStatus` type in `payment/plans.ts` as well. | ||||||||||
if (subscription.status === SubscriptionStatus.Active) { | ||||||||||
subscriptionStatus = subscription.cancel_at_period_end | ||||||||||
? SubscriptionStatus.CancelAtPeriodEnd | ||||||||||
|
@@ -188,7 +164,7 @@ export async function handleCustomerSubscriptionUpdated( | |||||||||
} | ||||||||||
} | ||||||||||
|
||||||||||
export async function handleCustomerSubscriptionDeleted( | ||||||||||
async function handleCustomerSubscriptionDeleted( | ||||||||||
subscription: SubscriptionDeletedData, | ||||||||||
prismaUserDelegate: PrismaClient['user'] | ||||||||||
) { | ||||||||||
|
@@ -199,40 +175,41 @@ export async function handleCustomerSubscriptionDeleted( | |||||||||
); | ||||||||||
} | ||||||||||
|
||||||||||
type SubscsriptionItems = z.infer<typeof subscriptionItemsSchema>; | ||||||||||
|
||||||||||
const subscriptionItemsSchema = z.object({ | ||||||||||
data: z.array( | ||||||||||
z.object({ | ||||||||||
price: z.object({ | ||||||||||
id: z.string(), | ||||||||||
}), | ||||||||||
}) | ||||||||||
), | ||||||||||
}); | ||||||||||
|
||||||||||
function extractPriceId(items: SubscsriptionItems): string { | ||||||||||
// We only expect one line item, but if you set up a product with multiple prices, you should change this function to handle them. | ||||||||||
function extractPriceId( | ||||||||||
items: Stripe.ApiList<Stripe.LineItem> | SubscriptionUpdatedData['items'] | InvoicePaidData['lines'] | ||||||||||
): string { | ||||||||||
if (items.data.length === 0) { | ||||||||||
throw new HttpError(400, 'No items in stripe event object'); | ||||||||||
} | ||||||||||
if (items.data.length > 1) { | ||||||||||
throw new HttpError(400, 'More than one item in stripe event object'); | ||||||||||
} | ||||||||||
return items.data[0].price.id; | ||||||||||
} | ||||||||||
const item = items.data[0]; | ||||||||||
|
||||||||||
async function getSubscriptionLineItemsBySessionId(sessionId: string) { | ||||||||||
try { | ||||||||||
const { line_items: lineItemsRaw } = await stripe.checkout.sessions.retrieve(sessionId, { | ||||||||||
expand: ['line_items'], | ||||||||||
}); | ||||||||||
// The 'price' property is found on SubscriptionItem and LineItem. | ||||||||||
if ('price' in item && item.price?.id) { | ||||||||||
return item.price.id; | ||||||||||
} | ||||||||||
|
||||||||||
const lineItems = await subscriptionItemsSchema.parseAsync(lineItemsRaw); | ||||||||||
// The 'pricing' property is found on InvoiceLineItem. | ||||||||||
if ('pricing' in item) { | ||||||||||
const priceId = item.pricing?.price_details?.price; | ||||||||||
if (priceId) { | ||||||||||
return priceId; | ||||||||||
} | ||||||||||
} | ||||||||||
throw new HttpError(400, 'Unable to extract price id from item'); | ||||||||||
} | ||||||||||
|
||||||||||
return lineItems; | ||||||||||
} catch (e: unknown) { | ||||||||||
throw new HttpError(500, 'Error parsing Stripe line items'); | ||||||||||
async function getCheckoutLineItemsBySessionId(sessionId: string) { | ||||||||||
const { line_items } = await stripe.checkout.sessions.retrieve(sessionId, { | ||||||||||
expand: ['line_items'], | ||||||||||
}); | ||||||||||
if (!line_items) { | ||||||||||
throw new HttpError(400, 'No line items found in checkout session'); | ||||||||||
} | ||||||||||
return line_items; | ||||||||||
} | ||||||||||
|
||||||||||
function getPlanIdByPriceId(priceId: string): PaymentPlanId { | ||||||||||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixes #412