95 lines
2.3 KiB
TypeScript
95 lines
2.3 KiB
TypeScript
import { cookies } from "next/headers";
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
import { db } from "@/lib/db";
|
|
import { stripeAccounts } from "@/lib/schema/stripeAccounts";
|
|
import { eq } from "drizzle-orm";
|
|
|
|
type StripeOAuthResponse = {
|
|
stripe_user_id: string; // acct_...
|
|
};
|
|
|
|
export async function GET(req: NextRequest) {
|
|
const cookieStore = await cookies();
|
|
const session = cookieStore.get("session");
|
|
|
|
// 🔒 Must be logged in
|
|
if (!session) {
|
|
return NextResponse.redirect(
|
|
new URL("/login", process.env.NEXT_PUBLIC_BASE_URL)
|
|
);
|
|
}
|
|
|
|
const userId = session.value;
|
|
|
|
const { searchParams } = new URL(req.url);
|
|
const code = searchParams.get("code");
|
|
const error = searchParams.get("error");
|
|
|
|
if (error) {
|
|
console.error("Stripe OAuth error:", error);
|
|
return NextResponse.redirect(
|
|
new URL(
|
|
"/connect/stripe?error=oauth_failed",
|
|
process.env.NEXT_PUBLIC_BASE_URL
|
|
)
|
|
);
|
|
}
|
|
|
|
if (!code) {
|
|
return NextResponse.json(
|
|
{ error: "Missing OAuth code" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// 🔁 Exchange OAuth code
|
|
const tokenRes = await fetch("https://connect.stripe.com/oauth/token", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
},
|
|
body: new URLSearchParams({
|
|
grant_type: "authorization_code",
|
|
code,
|
|
client_secret: process.env.STRIPE_SECRET_KEY!,
|
|
}),
|
|
});
|
|
|
|
if (!tokenRes.ok) {
|
|
const text = await tokenRes.text();
|
|
console.error("Stripe token exchange failed:", text);
|
|
|
|
return NextResponse.redirect(
|
|
new URL(
|
|
"/connect/stripe?error=token_exchange_failed",
|
|
process.env.NEXT_PUBLIC_BASE_URL
|
|
)
|
|
);
|
|
}
|
|
|
|
const data = (await tokenRes.json()) as StripeOAuthResponse;
|
|
|
|
// ✅ Persist Stripe account → user (UPSERT)
|
|
await db
|
|
.insert(stripeAccounts)
|
|
.values({
|
|
userId,
|
|
stripeAccountId: data.stripe_user_id,
|
|
})
|
|
.onConflictDoUpdate({
|
|
target: stripeAccounts.userId,
|
|
set: {
|
|
stripeAccountId: data.stripe_user_id,
|
|
},
|
|
});
|
|
|
|
console.log("Stripe connected", {
|
|
userId,
|
|
stripeAccountId: data.stripe_user_id,
|
|
});
|
|
|
|
// ✅ Success redirect
|
|
return NextResponse.redirect(
|
|
new URL("/connect/stripe/success", process.env.NEXT_PUBLIC_BASE_URL)
|
|
);
|
|
}
|