Skip to content
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

add Stripe as payment solution #134

Merged
merged 5 commits into from
Nov 30, 2023
Merged
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
8 changes: 7 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,10 @@ RESEND_API_KEY=

# Create a project in uploadthing and get api keys https://uploadthing.com/
UPLOADTHING_SECRET=
UPLOADTHING_APP_ID=
UPLOADTHING_APP_ID=

#Stripe https://stripe.com/
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET =
STRIPE_PRO_PLAN_ID=
17 changes: 17 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
version: "3"

services:
postgres:
image: postgres:15.2-alpine
restart: always
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
ports:
- 6432:5432
volumes:
- postgres-data:/var/lib/postgresql/data

volumes:
postgres-data:
8 changes: 0 additions & 8 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,6 @@ const nextConfig = {
},
];
},
images: {
remotePatterns: [
{
protocol: "https",
hostname: "placehold.co/**",
},
],
},
};

module.exports = withPWA(withContentlayer(nextConfig));
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"react-hook-form": "^7.47.0",
"react-wrap-balancer": "^1.1.0",
"resend": "^1.1.0",
"stripe": "^14.4.0",
"uploadthing": "^5.5.3",
"zod": "^3.22.4"
},
Expand Down
18 changes: 18 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

97 changes: 97 additions & 0 deletions prisma/migrations/20231111061416_stripe/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
-- CreateTable
CREATE TABLE "Account" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"provider" TEXT NOT NULL,
"providerAccountId" TEXT NOT NULL,
"refresh_token" TEXT,
"access_token" TEXT,
"expires_at" INTEGER,
"token_type" TEXT,
"scope" TEXT,
"id_token" TEXT,
"session_state" TEXT,

CONSTRAINT "Account_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "Session" (
"id" TEXT NOT NULL,
"sessionToken" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"name" TEXT,
"email" TEXT,
"emailVerified" TIMESTAMP(3),
"image" TEXT,
"shortBio" TEXT,
"stripe_customer_id" TEXT,
"stripe_subscription_id" TEXT,
"stripe_price_id" TEXT,
"stripe_current_period_end" TIMESTAMP(3),

CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "VerificationToken" (
"identifier" TEXT NOT NULL,
"token" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL
);

-- CreateTable
CREATE TABLE "Project" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"domain" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "Project_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "Account_userId_idx" ON "Account"("userId");

-- CreateIndex
CREATE UNIQUE INDEX "Account_provider_providerAccountId_key" ON "Account"("provider", "providerAccountId");

-- CreateIndex
CREATE UNIQUE INDEX "Session_sessionToken_key" ON "Session"("sessionToken");

-- CreateIndex
CREATE INDEX "Session_userId_idx" ON "Session"("userId");

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

-- CreateIndex
CREATE UNIQUE INDEX "User_stripe_customer_id_key" ON "User"("stripe_customer_id");

-- CreateIndex
CREATE UNIQUE INDEX "User_stripe_subscription_id_key" ON "User"("stripe_subscription_id");

-- CreateIndex
CREATE UNIQUE INDEX "VerificationToken_token_key" ON "VerificationToken"("token");

-- CreateIndex
CREATE UNIQUE INDEX "VerificationToken_identifier_token_key" ON "VerificationToken"("identifier", "token");

-- AddForeignKey
ALTER TABLE "Account" ADD CONSTRAINT "Account_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Project" ADD CONSTRAINT "Project_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
12 changes: 9 additions & 3 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,15 @@ model User {
emailVerified DateTime?
image String?
shortBio String?
accounts Account[]
sessions Session[]
projects Project[]

stripeCustomerId String? @unique @map(name: "stripe_customer_id")
stripeSubscriptionId String? @unique @map(name: "stripe_subscription_id")
stripePriceId String? @map(name: "stripe_price_id")
stripeCurrentPeriodEnd DateTime? @map(name: "stripe_current_period_end")

accounts Account[]
sessions Session[]
projects Project[]
}

model VerificationToken {
Expand Down
62 changes: 62 additions & 0 deletions src/app/api/stripe/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// /api/stripe

import { getServerSession } from "next-auth";
import { NextResponse } from "next/server";
import { z } from "zod";
import { proPlan } from "~/config/subscription";
import { authOptions } from "~/lib/auth";
import { stripe } from "~/lib/stripe";
import { getUserSubscriptionPlan } from "~/lib/subscription";

const billingUrl = process.env.NEXT_PUBLIC_APP_URL + "/dashboard/billing";

export async function GET() {
try {
const session = await getServerSession(authOptions);

if (!session?.user || !session?.user.email) {
return new NextResponse("Unauthorized", { status: 401 });
}

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,
});

return NextResponse.json({ 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: "subscription",
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 });
}

return new Response(null, { status: 500 });
}
}
73 changes: 73 additions & 0 deletions src/app/api/webhooks/stripe/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { type NextApiRequest } from "next";
import { headers } from "next/headers";
import { buffer } from "node:stream/consumers";
import type Stripe from "stripe";
import db from "~/lib/db";
import { stripe } from "~/lib/stripe";

export async function POST(req: NextApiRequest) {
const body = await buffer(req.body);
const signature = headers().get("Stripe-Signature") as string;

let event: Stripe.Event | undefined = undefined;

try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET as string
);
} catch (error) {
if (error instanceof Error) {
return new Response(`Webhook Error: ${error.message}`, { status: 400 });
}
}

const session = event?.data.object as Stripe.Checkout.Session;

if (event?.type === "checkout.session.completed") {
// Retrieve the subscription details from Stripe.
const subscription = await stripe.subscriptions.retrieve(
session.subscription as string
);

// Update the user stripe into in our database.
// Since this is the initial subscription, we need to update
// the subscription id and customer id.
await db.user.update({
where: {
id: session?.metadata?.userId,
},
data: {
stripeSubscriptionId: subscription.id,
stripeCustomerId: subscription.customer as string,
stripePriceId: subscription.items.data[0].price.id,
stripeCurrentPeriodEnd: new Date(
subscription.current_period_end * 1000
),
},
});
}

if (event?.type === "invoice.payment_succeeded") {
// Retrieve the subscription details from Stripe.
const subscription = await stripe.subscriptions.retrieve(
session.subscription as string
);

// Update the price id and set the new period end.
await db.user.update({
where: {
stripeSubscriptionId: subscription.id,
},
data: {
stripePriceId: subscription.items.data[0].price.id,
stripeCurrentPeriodEnd: new Date(
subscription.current_period_end * 1000
),
},
});
}

return new Response(null, { status: 200 });
}
Loading
Loading