UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.
✨ feat: Add stripe webhook and billing setup
Dillion Vermace8670c3b56a
diff --git a/app/(dashboard)/dashboard/billing/page.tsx b/app/(dashboard)/dashboard/billing/page.tsxindex 4de323df..2101a7aa 100644--- a/app/(dashboard)/dashboard/billing/page.tsx+++ b/app/(dashboard)/dashboard/billing/page.tsx@@ -1,12 +1,14 @@import { DashboardHeader } from "@/components/dashboard/header";+import { OrderList } from "@/components/dashboard/order-list";import { DashboardShell } from "@/components/dashboard/shell";import { authOptions } from "@/lib/auth";import { getCurrentUser } from "@/lib/session";+import { getUserPayments } from "@/lib/stripe-utils";import { redirect } from "next/navigation";export const metadata = {title: "Billing | Magic UI",- description: "Manage billing and your subscription plan.",+ description: "Manage billing information.",};export default async function BillingPage() {@@ -16,29 +18,13 @@ export default async function BillingPage() {redirect(authOptions?.pages?.signIn || "/login");}- // const subscriptionPlan = await getUserSubscriptionPlan(user.id);-- // // If user has a pro plan, check cancel status on Stripe.- // let isCanceled = false;- // if (subscriptionPlan.isPro && subscriptionPlan.stripeSubscriptionId) {- // const stripePlan = await stripe.subscriptions.retrieve(- // subscriptionPlan.stripeSubscriptionId- // );- // isCanceled = stripePlan.cancel_at_period_end;- // }+ const payments = await getUserPayments(user.id);return (<DashboardShell><DashboardHeader heading="Billing" text="Manage billing information" /><div className="grid gap-8">- {/* <BillingForm- subscriptionPlan={- {- // ...subscriptionPlan,- // isCanceled,- }- }- /> */}+ <OrderList payments={payments} /></div></DashboardShell>);diff --git a/app/(docs)/components/[slug]/not-found.tsx b/app/(docs)/components/[slug]/not-found.tsxindex 96ec839c..5ec5a9bb 100644--- a/app/(docs)/components/[slug]/not-found.tsx+++ b/app/(docs)/components/[slug]/not-found.tsx@@ -1,23 +1,36 @@import { EmptyPlaceholder } from "@/components/empty-placeholder";import { buttonVariants } from "@/components/ui/button";+import { getCurrentUser } from "@/lib/session";import Link from "next/link";+import { env } from "process";++export default async function NotFound() {+ const user = await getCurrentUser();+ const url = new URL(+ env.NODE_ENV === "development"+ ? "https://buy.stripe.com/test_bIY7uvbbzecfcw09AB"+ : "https://buy.stripe.com/3cs8zHafOdUa0tG9AA"+ );++ if (user && user.email) {+ url.searchParams.append("prefilled_email", user.email);+ }-export default function NotFound() {return (<EmptyPlaceholder className="w-full"><EmptyPlaceholder.Icon name="logo" /><EmptyPlaceholder.Title>- Pre-order to access Magic UI+ Pre-order to get access Magic UI</EmptyPlaceholder.Title><EmptyPlaceholder.Description>- You will get access to all future components and their source code so- you can use them in your projects 🎉+ You get the complete source code of all components and templates so you+ can use them in your projects 🎉</EmptyPlaceholder.Description><Link- href="https://buy.stripe.com/3cs8zHafOdUa0tG9AA"+ href={url.toString()}target="_blank"rel="noreferrer"- className={buttonVariants({ variant: "outline" })}+ className={buttonVariants({ variant: "default" })}>Pre-order</Link>diff --git a/app/(docs)/components/[slug]/page.tsx b/app/(docs)/components/[slug]/page.tsxindex 1310d14e..111d84bb 100644--- a/app/(docs)/components/[slug]/page.tsx+++ b/app/(docs)/components/[slug]/page.tsx@@ -7,8 +7,10 @@ import { Mdx } from "@/components/mdx-components";import { DashboardTableOfContents } from "@/components/toc";import { ScrollArea } from "@/components/ui/scroll-area";import { getCurrentUser } from "@/lib/session";+import { getUserPayments } from "@/lib/stripe-utils";import { getTableOfContents } from "@/lib/toc";import { absoluteUrl, cn, constructMetadata } from "@/lib/utils";+import { Payment } from "@prisma/client";import { allComponents } from "contentlayer/generated";import { ChevronRight } from "lucide-react";import type { Metadata } from "next";@@ -76,8 +78,17 @@ export async function generateMetadata({});}-export default async function Post({ params }: { params: { slug: string } }) {+interface Props {+ params: { slug: string };+}++export default async function Component({ params }: Props) {const user = await getCurrentUser();+ const { payments } = await getUserPayments(user?.id!);++ const paid = payments.some(+ (payment: Payment) => payment.status === "succeeded"+ );const component = allComponents.find((component) => component.slugAsParams === params.slug@@ -170,8 +181,8 @@ export default async function Post({ params }: { params: { slug: string } }) {</MagicContainer></ComponentWrapper>- {user && <Mdx code={component.body.code} />}- {!user && <NotFound />}+ {user && paid && <Mdx code={component.body.code} />}+ {(!user || !paid) && <NotFound />}</div></div>diff --git a/app/(marketing)/page.tsx b/app/(marketing)/page.tsxindex fb3172d5..e2ce0bf0 100644--- a/app/(marketing)/page.tsx+++ b/app/(marketing)/page.tsx@@ -1,12 +1,16 @@import { FadeIn } from "@/components/magicui/FadeIn";import { buttonVariants } from "@/components/ui/button";import { Separator } from "@/components/ui/separator";+import { getCurrentUser } from "@/lib/session";import { cn } from "@/lib/utils";import { ChevronRight } from "lucide-react";import Link from "next/link";+import { env } from "process";import { CSSProperties } from "react";-export default function Home() {+export default async function Home() {+ const user = await getCurrentUser();+return (<><section className="space-y-6 pb-8 pt-20 md:pb-12 md:pt-10 lg:py-32">@@ -70,21 +74,36 @@ export default function Home() {delay={0.3}><div className="space-x-4">+ {user && (+ <Link+ href="/components"+ className={cn(buttonVariants({ size: "lg" }))}+ >+ Get Started+ </Link>+ )}+ {!user && (+ <Link+ href={+ env.NODE_ENV === "development"+ ? "https://buy.stripe.com/test_bIY7uvbbzecfcw09AB"+ : "https://buy.stripe.com/3cs8zHafOdUa0tG9AA"+ }+ // href="https://buy.stripe.com/3cs8zHafOdUa0tG9AA"+ target="_blank"+ rel="noreferrer"+ className={cn(buttonVariants({ size: "lg" }))}+ >+ Pre-order+ </Link>+ )}<Link- href="https://buy.stripe.com/3cs8zHafOdUa0tG9AA"- target="_blank"- rel="noreferrer"- className={cn(buttonVariants({ size: "lg" }))}- >- Pre-order- </Link>- <Link- href="/components"+ href="https://twitter.com/dillionverma"className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>- Components+ Follow along on Twitter</Link></div></FadeIn>diff --git a/app/api/users/stripe/route.ts b/app/api/users/stripe/route.tsindex e243a5a8..fc9a20f1 100644--- a/app/api/users/stripe/route.ts+++ b/app/api/users/stripe/route.ts@@ -1,7 +1,4 @@-import { proPlan } from "@/config/subscriptions";import { authOptions } from "@/lib/auth";-import { stripe } from "@/lib/stripe";-import { getUserSubscriptionPlan } from "@/lib/subscription";import { absoluteUrl } from "@/lib/utils";import { getServerSession } from "next-auth/next";import { z } from "zod";@@ -16,40 +13,42 @@ export async function GET(req: Request) {return new Response(null, { status: 403 });}- const subscriptionPlan = await getUserSubscriptionPlan(session.user.id);+ return new Response(JSON.stringify({ url: "test" }));++ // const subscriptionPlan = await getUserSubscriptionPlan(session.user.id);// The user is on the pro plan.// Create a portal session to manage subscription.- if (subscriptionPlan.isPro && subscriptionPlan.stripeCustomerId) {- const stripeSession = await stripe.billingPortal.sessions.create({- customer: subscriptionPlan.stripeCustomerId,- return_url: billingUrl,- });+ // if (subscriptionPlan.isPro && subscriptionPlan.stripeCustomerId) {+ // const stripeSession = await stripe.billingPortal.sessions.create({+ // customer: subscriptionPlan.stripeCustomerId,+ // return_url: billingUrl,+ // });- return new Response(JSON.stringify({ url: stripeSession.url }));- }+ // return new Response(JSON.stringify({ url: stripeSession.url }));+ // }// The user is on the free plan.// Create a checkout session to upgrade.- const stripeSession = await stripe.checkout.sessions.create({- success_url: billingUrl,- cancel_url: billingUrl,- payment_method_types: ["card"],- mode: "payment",- billing_address_collection: "auto",- customer_email: session.user.email,- line_items: [- {- price: proPlan.stripePriceId,- quantity: 1,- },- ],- metadata: {- userId: session.user.id,- },- });-- return new Response(JSON.stringify({ url: stripeSession.url }));+ // const stripeSession = await stripe.checkout.sessions.create({+ // success_url: billingUrl,+ // cancel_url: billingUrl,+ // payment_method_types: ["card"],+ // mode: "payment",+ // billing_address_collection: "auto",+ // customer_email: session.user.email,+ // line_items: [+ // {+ // price: proPlan.stripePriceId,+ // quantity: 1,+ // },+ // ],+ // metadata: {+ // userId: session.user.id,+ // },+ // });++ // return new Response(JSON.stringify({ url: stripeSession.url }));} catch (error) {if (error instanceof z.ZodError) {return new Response(JSON.stringify(error.issues), { status: 422 });diff --git a/app/api/webhooks/stripe/route.ts b/app/api/webhooks/stripe/route.tsnew file mode 100644index 00000000..bf363cfc--- /dev/null+++ b/app/api/webhooks/stripe/route.ts@@ -0,0 +1,98 @@+import { env } from "@/env.mjs";+import { stripe } from "@/lib/stripe";+import { upsertCustomer, upsertPayment } from "@/lib/stripe-utils";+import { headers } from "next/headers";+import Stripe from "stripe";++const relevantEvents = new Set([+ // "product.created",+ // "product.updated",+ // "price.created",+ // "price.updated",+ "customer.created",+ "checkout.session.completed",+ // "customer.subscription.created",+ // "customer.subscription.updated",+ // "customer.subscription.deleted",+]);++export async function POST(req: Request) {+ const body = await req.text();+ const sig = headers().get("Stripe-Signature") as string;+ const webhookSecret = env.STRIPE_WEBHOOK_SECRET;+ let event: Stripe.Event;++ try {+ if (!sig || !webhookSecret) return;+ event = stripe.webhooks.constructEvent(body, sig, webhookSecret);+ } catch (err: any) {+ console.log(`❌ Error message: ${err.message}`);+ return new Response(`Webhook Error: ${err.message}`, { status: 400 });+ }++ if (relevantEvents.has(event.type)) {+ try {+ switch (event.type) {+ // case 'product.created':+ // case 'product.updated':+ // await upsertProductRecord(event.data.object as Stripe.Product);+ // break;+ // case 'price.created':+ // case 'price.updated':+ // await upsertPriceRecord(event.data.object as Stripe.Price);+ // break;+ // case 'customer.subscription.created':+ // case 'customer.subscription.updated':+ // case 'customer.subscription.deleted':+ // const subscription = event.data.object as Stripe.Subscription;+ // await manageSubscriptionStatusChange(+ // subscription.id,+ // subscription.customer as string,+ // event.type === 'customer.subscription.created'+ // );+ // break;++ case "customer.created":+ const customer = event.data.object as Stripe.Customer;+ console.log("Customer: ", customer);+ break;+ case "checkout.session.completed":+ const session = event.data.object as Stripe.Checkout.Session;+ if (session.mode === "subscription") {+ // const subscriptionId = session.subscription;+ // await manageSubscriptionStatusChange(+ // subscriptionId as string,+ // session.customer as string,+ // true+ // );+ } else if (session.mode === "payment") {+ if (!session.customer_details?.email) {+ throw new Error("No email provided");+ }+ const customer = await upsertCustomer(+ session.customer_details.email,+ session.customer_details.name || ""+ );+ await upsertPayment(session.payment_intent as string, customer.id);++ console.log("Login Link");++ // await signIn("email", {+ // email: session.customer_details.email,+ // });+ // await sendLoginEmail(session.customer_details.email);+ }+ break;+ default:+ throw new Error("Unhandled relevant event!");+ }+ } catch (error) {+ console.log(error);+ return new Response("Webhook handler failed. View logs.", {+ status: 400,+ });+ }+ }++ return new Response(null, { status: 200 });+}diff --git a/components/dashboard/billing-form.tsx b/components/dashboard/billing-form.tsxdeleted file mode 100644index f2eec745..00000000--- a/components/dashboard/billing-form.tsx+++ /dev/null@@ -1,89 +0,0 @@-"use client";--import { Icons } from "@/components/icons";-import { buttonVariants } from "@/components/ui/button";-import {- Card,- CardContent,- CardDescription,- CardFooter,- CardHeader,- CardTitle,-} from "@/components/ui/card";-import { toast } from "@/components/ui/use-toast";-import { cn, formatDate } from "@/lib/utils";-import * as React from "react";-import { UserSubscriptionPlan } from "types";--interface BillingFormProps extends React.HTMLAttributes<HTMLFormElement> {- subscriptionPlan: UserSubscriptionPlan & {- isCanceled: boolean;- };-}--export function BillingForm({- subscriptionPlan,- className,- ...props-}: BillingFormProps) {- const [isLoading, setIsLoading] = React.useState<boolean>(false);-- async function onSubmit(event: any) {- event.preventDefault();- setIsLoading(!isLoading);-- // Get a Stripe session URL.- const response = await fetch("/api/users/stripe");-- if (!response?.ok) {- return toast({- title: "Something went wrong.",- description: "Please refresh the page and try again.",- variant: "destructive",- });- }-- // Redirect to the Stripe session.- // This could be a checkout page for initial upgrade.- // Or portal to manage existing subscription.- const session = await response.json();- if (session) {- window.location.href = session.url;- }- }-- return (- <form className={cn(className)} onSubmit={onSubmit} {...props}>- <Card>- <CardHeader>- <CardTitle>Subscription Plan</CardTitle>- <CardDescription>- You are currently on the <strong>{subscriptionPlan.name}</strong>{" "}- plan.- </CardDescription>- </CardHeader>- <CardContent>{subscriptionPlan.description}</CardContent>- <CardFooter className="flex flex-col items-start space-y-2 md:flex-row md:justify-between md:space-x-0">- <button- type="submit"- className={cn(buttonVariants())}- disabled={isLoading}- >- {isLoading && (- <Icons.spinner className="mr-2 h-4 w-4 animate-spin" />- )}- {subscriptionPlan.isPro ? "Manage Subscription" : "Upgrade to PRO"}- </button>- {subscriptionPlan.isPro ? (- <p className="rounded-full text-xs font-medium">- {subscriptionPlan.isCanceled- ? "Your plan will be canceled on "- : "Your plan renews on "}- {formatDate(subscriptionPlan.stripeCurrentPeriodEnd)}.- </p>- ) : null}- </CardFooter>- </Card>- </form>- );-}diff --git a/components/dashboard/order-list.tsx b/components/dashboard/order-list.tsxnew file mode 100644index 00000000..498971bc--- /dev/null+++ b/components/dashboard/order-list.tsx@@ -0,0 +1,96 @@+"use client";++import { Badge } from "@/components/ui/badge";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { cn } from "@/lib/utils";+import { UserPayments } from "@/types";+import { Payment } from "@prisma/client";+import Link from "next/link";+import { HTMLAttributes } from "react";+import { buttonVariants } from "../ui/button";++interface OrderListProps extends HTMLAttributes<HTMLFormElement> {+ payments: UserPayments;+}++export function OrderList({ payments, className, ...props }: OrderListProps) {+ return (+ <Card>+ <CardHeader>+ <CardTitle>Orders</CardTitle>+ <CardDescription>+ You have {payments.payments.length}{" "}+ {payments.payments.length === 1 ? "order" : "orders"}.+ </CardDescription>+ </CardHeader>++ <CardContent>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Name</TableHead>+ <TableHead>Status</TableHead>+ <TableHead>Amount</TableHead>+ <TableHead className="text-right">Reciept</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {payments.payments.map((payment: Payment) => (+ <TableRow key={payment.id}>+ <TableCell className="font-medium">+ <div className="flex flex-col gap-2">+ <CardTitle>Magic UI Pre-order (x1)</CardTitle>+ </div>+ </TableCell>+ <TableCell>+ <Badge+ variant={"outline"}+ className={cn(+ payment.status === "succeeded" && " bg-green-400/40",+ payment.status === "failed" && " bg-red-400/40"+ )}+ >+ {payment.status}+ </Badge>+ </TableCell>+ <TableCell>+ {Intl.NumberFormat("en-US", {+ style: "currency",+ currency: payment.currency,+ }).format(payment.amount / 100)}+ </TableCell>+ <TableCell className="whitespace-wrap text-right">+ {payment.status === "succeeded" && payment.receiptUrl && (+ <Link+ className={cn(+ buttonVariants({ size: "sm", variant: "default" }),+ "text-sm"+ )}+ href={payment.receiptUrl || ""}+ >+ See reciept+ </Link>+ )}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ );+}diff --git a/components/ui/table.tsx b/components/ui/table.tsxnew file mode 100644index 00000000..eb17c5a0--- /dev/null+++ b/components/ui/table.tsx@@ -0,0 +1,117 @@+import * as React from "react"++import { cn } from "@/lib/utils"++const Table = React.forwardRef<+ HTMLTableElement,+ React.HTMLAttributes<HTMLTableElement>+>(({ className, ...props }, ref) => (+ <div className="w-full overflow-auto">+ <table+ ref={ref}+ className={cn("w-full caption-bottom text-sm", className)}+ {...props}+ />+ </div>+))+Table.displayName = "Table"++const TableHeader = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />+))+TableHeader.displayName = "TableHeader"++const TableBody = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <tbody+ ref={ref}+ className={cn("[&_tr:last-child]:border-0", className)}+ {...props}+ />+))+TableBody.displayName = "TableBody"++const TableFooter = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <tfoot+ ref={ref}+ className={cn("bg-primary font-medium text-primary-foreground", className)}+ {...props}+ />+))+TableFooter.displayName = "TableFooter"++const TableRow = React.forwardRef<+ HTMLTableRowElement,+ React.HTMLAttributes<HTMLTableRowElement>+>(({ className, ...props }, ref) => (+ <tr+ ref={ref}+ className={cn(+ "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",+ className+ )}+ {...props}+ />+))+TableRow.displayName = "TableRow"++const TableHead = React.forwardRef<+ HTMLTableCellElement,+ React.ThHTMLAttributes<HTMLTableCellElement>+>(({ className, ...props }, ref) => (+ <th+ ref={ref}+ className={cn(+ "h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",+ className+ )}+ {...props}+ />+))+TableHead.displayName = "TableHead"++const TableCell = React.forwardRef<+ HTMLTableCellElement,+ React.TdHTMLAttributes<HTMLTableCellElement>+>(({ className, ...props }, ref) => (+ <td+ ref={ref}+ className={cn(+ "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",+ className+ )}+ {...props}+ />+))+TableCell.displayName = "TableCell"++const TableCaption = React.forwardRef<+ HTMLTableCaptionElement,+ React.HTMLAttributes<HTMLTableCaptionElement>+>(({ className, ...props }, ref) => (+ <caption+ ref={ref}+ className={cn("mt-4 text-sm text-muted-foreground", className)}+ {...props}+ />+))+TableCaption.displayName = "TableCaption"++export {+ Table,+ TableHeader,+ TableBody,+ TableFooter,+ TableHead,+ TableRow,+ TableCell,+ TableCaption,+}diff --git a/content/components/magic-card.mdx b/content/components/magic-card.mdxindex 630ed025..e1c2329f 100644--- a/content/components/magic-card.mdx+++ b/content/components/magic-card.mdx@@ -3,7 +3,7 @@ title: Magic Carddate: 2023-06-25summary: A spotlight effect that follows your mouse cursor and highlights borders on hover.author: dillionverma-published: false+published: truevideo: https://cdn.magicuikit.com/magic-border.webm---@@ -318,14 +318,14 @@ Now you can use the `MagicContainer` and `MagicCard` components to create a magi## Props-### MagicBorderContainer+### MagicContainer| Prop name | Type | Default | Description || --------- | --------- | ------- | --------------------------------------- || children | ReactNode | - | The children to render || className | string | - | The className to apply to the container |-### MagicBorderCard+### MagicCard| Prop name | Type | Default | Description || -------------- | --------- | ---------------------- | ---------------------------------- |diff --git a/env.mjs b/env.mjsindex 52e056bd..910f1761 100644--- a/env.mjs+++ b/env.mjs@@ -13,7 +13,7 @@ export const env = createEnv({DATABASE_URL: z.string().min(1),RESEND_API_KEY: z.string().min(1),STRIPE_API_KEY: z.string().min(1),- STRIPE_WEBHOOK_SECRET: z.string().optional(),+ STRIPE_WEBHOOK_SECRET: z.string().min(1),// SMTP_FROM: z.string().min(1),// POSTMARK_API_TOKEN: z.string().min(1),// POSTMARK_SIGN_IN_TEMPLATE: z.string().min(1),diff --git a/lib/auth.ts b/lib/auth.tsindex 42229f91..a6fd5b19 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -4,6 +4,7 @@ import { PrismaAdapter } from "@next-auth/prisma-adapter";import { NextAuthOptions } from "next-auth";import EmailProvider from "next-auth/providers/email";import { sendLoginEmail } from "./emails/send-login-email";+import { upsertCustomer } from "./stripe-utils";export const authOptions: NextAuthOptions = {adapter: PrismaAdapter(db),@@ -67,7 +68,11 @@ export const authOptions: NextAuthOptions = {email: message.user.email,},};- // await sendWelcomeEmail(params); // <-- send welcome email++ if (message.user.email) {+ await upsertCustomer(message.user.email!, message.user.name!);+ // await sendWelcomeEmail(params); // <-- send welcome email+ }},},};diff --git a/lib/stripe-utils.ts b/lib/stripe-utils.tsnew file mode 100644index 00000000..659dd684--- /dev/null+++ b/lib/stripe-utils.ts@@ -0,0 +1,105 @@+import { db } from "@/lib/db";+import { stripe } from "@/lib/stripe";+import { UserPayments } from "@/types";++export async function getUserPayments(userId: string): Promise<UserPayments> {+ const user = await db.user.findFirst({+ where: {+ id: userId,+ },+ include: {+ customer: {+ include: {+ payments: true,+ },+ },+ },+ });++ if (!user) {+ throw new Error("User not found");+ }++ if (!user.customer) {+ throw new Error("Customer not found");+ }++ return {+ ...user,+ payments: user.customer.payments,+ };++ // Check if user is on a pro plan.+ // const isPro = user.stripePriceId === proPlan.stripePriceId;+ // user.stripeCurrentPeriodEnd?.getTime() + 86_400_000 > Date.now();++ // const plan = isPro ? proPlan : freePlan;++ // return {+ // ...plan,+ // ...user,+ // // stripeCurrentPeriodEnd: user.stripeCurrentPeriodEnd?.getTime(),+ // isPro,+ // };+}++export const upsertPayment = async (+ paymentIntent: string,+ customerId: string+) => {+ const p = await stripe.paymentIntents.retrieve(paymentIntent);++ const payment = await db.payment.create({+ data: {+ stripeId: paymentIntent,+ amount: p.amount,+ currency: p.currency,+ status: p.status,+ customerId: customerId,+ },+ });++ console.log(p);+};++export const upsertCustomer = async (email: string, name?: string) => {+ // Create or update user in our table+ const user = await db.user.upsert({+ where: { email },+ create: { email, name },+ update: { email, name },+ });++ const stripeCustomers = await stripe.customers.list({+ email,+ limit: 1,+ });++ let stripeCustomer = stripeCustomers.data[0];++ if (stripeCustomers.data.length === 0) {+ stripeCustomer = await stripe.customers.create({+ email,+ name,+ metadata: {+ userId: user.id,+ },+ });+ }++ // create or update customer in our table+ const customer = await db.customer.upsert({+ where: {+ userId: user.id,+ },+ create: {+ stripeId: stripeCustomer.id,+ userId: user.id,+ },+ update: {+ stripeId: stripeCustomer.id,+ },+ });++ return customer;+};diff --git a/lib/subscription.ts b/lib/subscription.tsdeleted file mode 100644index 1f312b7a..00000000--- a/lib/subscription.ts+++ /dev/null@@ -1,37 +0,0 @@-// @ts-nocheck--import { freePlan, proPlan } from "@/config/subscriptions";-import { db } from "@/lib/db";--export async function getUserSubscriptionPlan(- userId: string-): Promise<UserSubscriptionPlan> {- const user = await db.user.findFirst({- where: {- id: userId,- },- select: {- // stripeSubscriptionId: true,- // stripeCurrentPeriodEnd: true,- // stripeCustomerId: true,- // stripePriceId: true,- },- });-- if (!user) {- throw new Error("User not found");- }-- // Check if user is on a pro plan.- const isPro = user.stripePriceId === proPlan.stripePriceId;- // user.stripeCurrentPeriodEnd?.getTime() + 86_400_000 > Date.now();-- const plan = isPro ? proPlan : freePlan;-- return {- ...plan,- ...user,- // stripeCurrentPeriodEnd: user.stripeCurrentPeriodEnd?.getTime(),- isPro,- };-}diff --git a/package.json b/package.jsonindex d9d48284..8858389b 100644--- a/package.json+++ b/package.json@@ -8,7 +8,7 @@"start": "next start","lint": "next lint","dev:email": "email dev -p 3004",- "dev:stripe": "stripe listen --forward-to localhost:3004/api/v1/stripe/webhook",+ "dev:stripe": "stripe listen --forward-to localhost:3003/api/webhooks/stripe","dev:migrate": "dotenv -e .env.local -- npx prisma db push","dev:reset": "dotenv -e .env.local -- npx prisma migrate reset","dev:seed": "npx tsx prisma/seed.ts"diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 8dbf019a..75f8c2a5 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -68,23 +68,32 @@ model User {// Stripe Customermodel Customer {- id String @id @default(uuid())+ id String @id @default(uuid())+ createdAt DateTime @default(now())+ updatedAt DateTime @default(now()) @updatedAt+user User? @relation(fields: [userId], references: [id])userId String? @uniquestripeId String @unique- Payment Payment[]+ payments Payment[]@@index([userId])}// Stripe Paymentmodel Payment {- id String @id @default(uuid())- stripeId String @unique+ id String @id @default(uuid())+ createdAt DateTime @default(now())+ updatedAt DateTime @default(now()) @updatedAt++ stripeId String @uniqueamount Intcurrency String+ status String+ receiptUrl String?+customer Customer @relation(fields: [customerId], references: [id])customerId Stringdiff --git a/prisma/seed.ts b/prisma/seed.tsindex a1621eb2..b10976e1 100644--- a/prisma/seed.ts+++ b/prisma/seed.ts@@ -36,7 +36,7 @@ async function seed() {const user = await db.user.upsert({where: { email: c.email },update: {},- create: { email: c.email },+ create: { email: c.email, name: c.name },});const customer = await db.customer.upsert({@@ -50,13 +50,17 @@ async function seed() {const stripePayments = await stripe.getPaymentIntents(c.id);+ console.log(stripePayments);+for (const stripePayment of stripePayments) {await db.payment.create({data: {+ customerId: customer.id,stripeId: stripePayment.id,amount: stripePayment.amount,currency: stripePayment.currency,- customerId: customer.id,+ status: stripePayment.status,+ receiptUrl: stripePayment.receipt_url,},});}diff --git a/types/index.d.ts b/types/index.d.tsindex f96833dd..81e760e6 100644--- a/types/index.d.ts+++ b/types/index.d.ts@@ -33,3 +33,7 @@ export type UserSubscriptionPlan = SubscriptionPlan &stripeCurrentPeriodEnd: number;isPro: boolean;};++export type UserPayments = Pick<User> & {+ payments: Payment[];+};