Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion packages/console/app/src/routes/stripe/webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ export async function POST(input: APIEvent) {
const customer = await Billing.get()
if (customer?.customerID && customer.customerID !== customerID) throw new Error("Customer ID mismatch")

const existingPayment = await Database.use((tx) =>
tx
.select({ id: PaymentTable.id })
.from(PaymentTable)
.where(eq(PaymentTable.invoiceID, invoiceID))
.then((rows) => rows[0]),
)
if (existingPayment) return

// set customer metadata
if (!customer?.customerID) {
await Billing.stripe().customers.update(customerID, {
Expand Down Expand Up @@ -272,6 +281,17 @@ export async function POST(input: APIEvent) {
const invoice = await Billing.stripe().invoices.retrieve(invoiceID, {
expand: ["payments"],
})
const paymentID = invoice.payments?.data[0]?.payment.payment_intent as string | undefined

const existingPayment = await Database.use((tx) =>
tx
.select({ id: PaymentTable.id })
.from(PaymentTable)
.where(eq(PaymentTable.invoiceID, invoiceID))
.then((rows) => rows[0]),
)
if (existingPayment) return

await Database.transaction(async (tx) => {
await tx
.update(BillingTable)
Expand All @@ -286,7 +306,7 @@ export async function POST(input: APIEvent) {
id: Identifier.create("payment"),
amount: centsToMicroCents(amountInCents),
invoiceID,
paymentID: invoice.payments?.data[0].payment.payment_intent as string,
paymentID,
customerID,
})
})
Expand Down
2 changes: 1 addition & 1 deletion packages/console/core/src/schema/billing.sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export const PaymentTable = mysqlTable(
}
>(),
},
(table) => [...workspaceIndexes(table)],
(table) => [...workspaceIndexes(table), uniqueIndex("payment_invoice_id").on(table.invoiceID)],
)

export const UsageTable = mysqlTable(
Expand Down
Loading