summaryrefslogtreecommitdiff
path: root/apps/web/app/api/billing/create-checkout-session/route.ts
blob: cfbb3885bb6b1c7cbf017bb4d200735f0061b0a6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import { NextResponse } from "next/server"
import { headers } from "next/headers"
import { createSupabaseServerClient } from "@/lib/supabase/server"
import { createSupabaseAdminClient } from "@/lib/supabase/admin"
import { getStripe } from "@/lib/stripe"
import { rateLimit } from "@/lib/rate-limit"

export async function POST(request: Request) {
  const supabaseClient = await createSupabaseServerClient()
  const {
    data: { user },
  } = await supabaseClient.auth.getUser()

  if (!user) {
    return NextResponse.json({ error: "Not authenticated" }, { status: 401 })
  }

  const rateLimitResult = rateLimit(`checkout:${user.id}`, 10, 60_000)
  if (!rateLimitResult.success) {
    return NextResponse.json({ error: "Too many requests" }, { status: 429 })
  }

  const body = await request.json().catch(() => ({}))
  const billingInterval =
    body.billingInterval === "yearly" ? "yearly" : "monthly"
  const targetTier =
    body.targetTier === "developer" ? "developer" : "pro"

  const priceIdentifierMap: Record<string, string | undefined> = {
    "pro:monthly": process.env.STRIPE_PRO_MONTHLY_PRICE_IDENTIFIER,
    "pro:yearly": process.env.STRIPE_PRO_YEARLY_PRICE_IDENTIFIER,
    "developer:monthly": process.env.STRIPE_DEVELOPER_MONTHLY_PRICE_IDENTIFIER,
    "developer:yearly": process.env.STRIPE_DEVELOPER_YEARLY_PRICE_IDENTIFIER,
  }

  const stripePriceIdentifier =
    priceIdentifierMap[`${targetTier}:${billingInterval}`]

  if (!stripePriceIdentifier) {
    return NextResponse.json(
      { error: "Invalid plan configuration" },
      { status: 500 }
    )
  }

  const { data: profile, error: profileError } = await supabaseClient
    .from("user_profiles")
    .select("tier, stripe_customer_identifier, stripe_subscription_identifier")
    .eq("id", user.id)
    .single()

  if (profileError || !profile) {
    return NextResponse.json(
      { error: "Failed to load profile" },
      { status: 500 }
    )
  }

  const tierRank: Record<string, number> = { free: 0, pro: 1, developer: 2 }
  const currentRank = tierRank[profile.tier] ?? 0
  const targetRank = tierRank[targetTier] ?? 0

  if (currentRank >= targetRank) {
    return NextResponse.json(
      { error: `Already on ${profile.tier} plan` },
      { status: 400 }
    )
  }

  if (profile.stripe_subscription_identifier && currentRank > 0) {
    const subscription = await getStripe().subscriptions.retrieve(
      profile.stripe_subscription_identifier
    )

    const existingItemIdentifier = subscription.items.data[0]?.id

    if (!existingItemIdentifier) {
      return NextResponse.json(
        { error: "Could not find existing subscription item" },
        { status: 500 }
      )
    }

    await getStripe().subscriptions.update(
      profile.stripe_subscription_identifier,
      {
        items: [
          {
            id: existingItemIdentifier,
            price: stripePriceIdentifier,
          },
        ],
        proration_behavior: "always_invoice",
        metadata: { supabase_user_identifier: user.id },
      }
    )

    const adminClient = createSupabaseAdminClient()
    await adminClient
      .from("user_profiles")
      .update({ tier: targetTier })
      .eq("id", user.id)

    return NextResponse.json({ upgraded: true })
  }

  let stripeCustomerIdentifier = profile.stripe_customer_identifier

  if (!stripeCustomerIdentifier) {
    const customer = await getStripe().customers.create({
      email: user.email,
      metadata: { supabase_user_identifier: user.id },
    })

    stripeCustomerIdentifier = customer.id

    const adminClient = createSupabaseAdminClient()
    const { error: updateError } = await adminClient
      .from("user_profiles")
      .update({ stripe_customer_identifier: stripeCustomerIdentifier })
      .eq("id", user.id)

    if (updateError) {
      console.error("Admin client update error:", updateError)
      return NextResponse.json(
        { error: "Failed to save customer: " + updateError.message },
        { status: 500 }
      )
    }
  }

  const headersList = await headers()
  const origin = headersList.get("origin") || "http://localhost:3000"

  const checkoutSession = await getStripe().checkout.sessions.create({
    customer: stripeCustomerIdentifier,
    mode: "subscription",
    line_items: [
      {
        price: stripePriceIdentifier,
        quantity: 1,
      },
    ],
    success_url: `${origin}/reader/settings?billing=success`,
    cancel_url: `${origin}/reader/settings?billing=cancelled`,
    subscription_data: {
      metadata: { supabase_user_identifier: user.id },
    },
    client_reference_id: user.id,
  })

  return NextResponse.json({ url: checkoutSession.url })
}