GeezerVison is showing github.com — Add checkout session API and premium content handling · aidrivencoder/master-git-github@3bd0018
File treeExpand file treeCollapse file tree Open diff view settings api/create-checkout-session
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboard +63Lines changed: 63 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import { NextResponse } from 'next/server'; | | 2 | +import Stripe from 'stripe'; | | 3 | +import { getAuth } from 'firebase-admin/auth'; | | 4 | +import { Timestamp } from 'firebase-admin/firestore'; | | 5 | +import { adminDb } from '@/lib/firebase/config/firebase-admin'; | | 6 | + | | 7 | +// Initialize Stripe | | 8 | +const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { | | 9 | + apiVersion: '2023-08-16', | | 10 | +}); | | 11 | + | | 12 | +export async function POST(request: Request) { | | 13 | + try { | | 14 | + const { priceId } = await request.json(); | | 15 | + | | 16 | + // Get the session token from the Authorization header | | 17 | + const authHeader = request.headers.get('Authorization'); | | 18 | + if (!authHeader?.startsWith('Bearer ')) { | | 19 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | | 20 | + } | | 21 | + | | 22 | + const token = authHeader.split('Bearer ')[1]; | | 23 | + | | 24 | + // Verify the token and get the user | | 25 | + const decodedToken = await getAuth().verifyIdToken(token); | | 26 | + const userId = decodedToken.uid; | | 27 | + | | 28 | + // Create a Stripe checkout session | | 29 | + const session = await stripe.checkout.sessions.create({ | | 30 | + mode: 'subscription', | | 31 | + payment_method_types: ['card'], | | 32 | + line_items: [ | | 33 | + { | | 34 | + price: priceId, | | 35 | + quantity: 1, | | 36 | + }, | | 37 | + ], | | 38 | + success_url: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`, | | 39 | + cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/pricing`, | | 40 | + metadata: { | | 41 | + userId, | | 42 | + }, | | 43 | + }); | | 44 | + | | 45 | + // Store the checkout session in Firestore | | 46 | + await adminDb.collection('checkoutSessions').doc(session.id).set({ | | 47 | + userId, | | 48 | + priceId, | | 49 | + sessionId: session.id, | | 50 | + status: 'pending', | | 51 | + createdAt: Timestamp.now(), | | 52 | + updatedAt: Timestamp.now(), | | 53 | + }); | | 54 | + | | 55 | + return NextResponse.json({ sessionId: session.id, url: session.url }); | | 56 | + } catch (error: any) { | | 57 | + console.error('Error creating checkout session:', error); | | 58 | + return NextResponse.json( | | 59 | + { error: error.message }, | | 60 | + { status: 500 } | | 61 | + ); | | 62 | + } | | 63 | +} |
Collapse file Copy file name to clipboardExpand all lines: src/app/profile/page.tsx +11-2Lines changed: 11 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -4,6 +4,7 @@ import { useCallback } from 'react' | 4 | 4 | import { ProtectedRoute } from '@/components/auth/ProtectedRoute' | 5 | 5 | import { useAuth } from '@/components/providers/AuthProvider' | 6 | 6 | import { DisplayNameForm } from '@/components/profile/DisplayNameForm' | | 7 | +import Link from 'next/link' | 7 | 8 |
| 8 | 9 | export default function ProfilePage() { | 9 | 10 | const { user } = useAuth() | @@ -61,8 +62,16 @@ export default function ProfilePage() { | 61 | 62 | <dt className="text-sm font-medium text-gray-500 dark:text-gray-400"> | 62 | 63 | Subscription | 63 | 64 | </dt> | 64 | | - <dd className="mt-1 text-sm text-gray-900 dark:text-white"> | 65 | | - {user?.subscription?.tier ? `${user.subscription.tier.charAt(0).toUpperCase()}${user.subscription.tier.slice(1)} Plan` : 'No Plan'} | | 65 | + <dd className="mt-1 flex items-center justify-between"> | | 66 | + <span className="text-sm text-gray-900 dark:text-white"> | | 67 | + {user?.subscription?.tier ? `${user.subscription.tier.charAt(0).toUpperCase()}${user.subscription.tier.slice(1)} Plan` : 'No Plan'} | | 68 | + </span> | | 69 | + <Link | | 70 | + href="/pricing" | | 71 | + className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500" | | 72 | + > | | 73 | + Upgrade | | 74 | + </Link> | 66 | 75 | </dd> | 67 | 76 | </div> | 68 | 77 | </dl> | |
Collapse file Copy file name to clipboardExpand all lines: src/app/tutorials/[id]/page.tsx +8-1Lines changed: 8 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 3 | 3 | import { useEffect, useState } from 'react' | 4 | 4 | import { TutorialPage as ClientTutorialPage } from '@/components/tutorials/TutorialPage' | 5 | 5 | import { LoadingSpinner } from '@/components/ui/LoadingSpinner' | | 6 | +import { PremiumContent } from '@/components/premium/PremiumContent' | 6 | 7 | import Link from 'next/link' | 7 | 8 | import { Tutorial } from '@/types/tutorial' | 8 | 9 | import { getTutorialById } from '@/tutorials/data' | @@ -68,7 +69,13 @@ export default function TutorialPage({ params }: TutorialPageProps) { | 68 | 69 | return ( | 69 | 70 | <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-8"> | 70 | 71 | <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> | 71 | | - <ClientTutorialPage tutorial={tutorial} /> | | 72 | + {tutorial.isPremium ? ( | | 73 | + <PremiumContent> | | 74 | + <ClientTutorialPage tutorial={tutorial} /> | | 75 | + </PremiumContent> | | 76 | + ) : ( | | 77 | + <ClientTutorialPage tutorial={tutorial} /> | | 78 | + )} | 72 | 79 | </div> | 73 | 80 | </div> | 74 | 81 | ) | |
Collapse file Copy file name to clipboardExpand all lines: src/components/auth/SignUpForm.tsx +13-2Lines changed: 13 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -10,12 +10,14 @@ export function SignUpForm() { | 10 | 10 | const [password, setPassword] = useState('') | 11 | 11 | const [error, setError] = useState<string | null>(null) | 12 | 12 | const [loading, setLoading] = useState(false) | | 13 | + const [status, setStatus] = useState<string>('') | 13 | 14 | const router = useRouter() | 14 | 15 |
| 15 | 16 | const handleSubmit = async (e: React.FormEvent) => { | 16 | 17 | e.preventDefault() | 17 | 18 | setError(null) | 18 | 19 | setLoading(true) | | 20 | + setStatus('Creating account...') | 19 | 21 |
| 20 | 22 | const { user, error } = await signUpWithEmail(email, password) | 21 | 23 |
| @@ -25,6 +27,8 @@ export function SignUpForm() { | 25 | 27 | return | 26 | 28 | } | 27 | 29 |
| | 30 | + setStatus('Setting up your account...') | | 31 | + | 28 | 32 | if (user) { | 29 | 33 | router.push('/dashboard') | 30 | 34 | } | @@ -72,8 +76,15 @@ export function SignUpForm() { | 72 | 76 | disabled={loading} | 73 | 77 | className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 dark:bg-primary-500 dark:hover:bg-primary-600" | 74 | 78 | > | 75 | | - {loading ? <LoadingSpinner size="sm" /> : 'Create Account'} | | 79 | + {loading ? ( | | 80 | + <div className="flex items-center space-x-2"> | | 81 | + <LoadingSpinner size="sm" /> | | 82 | + <span>{status}</span> | | 83 | + </div> | | 84 | + ) : ( | | 85 | + 'Create Account' | | 86 | + )} | 76 | 87 | </button> | 77 | 88 | </form> | 78 | 89 | ) | 79 | | -} | | 90 | +} |
Collapse file Copy file name to clipboard +50Lines changed: 50 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use client' | | 2 | + | | 3 | +import { useEffect, useState } from 'react' | | 4 | +import { useAuth } from '../providers/AuthProvider' | | 5 | +import { checkPremiumAccess } from '@/lib/firebase/user' | | 6 | +import Link from 'next/link' | | 7 | + | | 8 | +interface PremiumContentProps { | | 9 | + children: React.ReactNode | | 10 | +} | | 11 | + | | 12 | +export function PremiumContent({ children }: PremiumContentProps) { | | 13 | + const { user } = useAuth() | | 14 | + const [hasPremiumAccess, setHasPremiumAccess] = useState<boolean | null>(null) | | 15 | + | | 16 | + useEffect(() => { | | 17 | + async function checkAccess() { | | 18 | + if (user) { | | 19 | + const hasAccess = await checkPremiumAccess(user.id) | | 20 | + setHasPremiumAccess(hasAccess) | | 21 | + } | | 22 | + } | | 23 | + checkAccess() | | 24 | + }, [user]) | | 25 | + | | 26 | + if (hasPremiumAccess === null) { | | 27 | + return <div className="animate-pulse">Loading...</div> | | 28 | + } | | 29 | + | | 30 | + if (!hasPremiumAccess) { | | 31 | + return ( | | 32 | + <div className="p-6 bg-yellow-50 border border-yellow-200 rounded-lg"> | | 33 | + <h3 className="text-lg font-semibold text-yellow-800 mb-2"> | | 34 | + Premium Content | | 35 | + </h3> | | 36 | + <p className="text-yellow-700 mb-4"> | | 37 | + This content is available exclusively to premium subscribers. | | 38 | + </p> | | 39 | + <Link | | 40 | + href="/pricing" | | 41 | + className="inline-block px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 transition-colors" | | 42 | + > | | 43 | + Upgrade to Premium | | 44 | + </Link> | | 45 | + </div> | | 46 | + ) | | 47 | + } | | 48 | + | | 49 | + return <>{children}</> | | 50 | +} |
Collapse file Copy file name to clipboardExpand all lines: src/lib/firebase/auth.ts +12-2Lines changed: 12 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 8 | 8 | type User | 9 | 9 | } from 'firebase/auth' | 10 | 10 | import { auth } from './config' | 11 | | -import { Logger } from '@/lib/utils/logger' | | 11 | +import { Logger } from '../utils/logger' | | 12 | +import { createUserDocument } from './user' | 12 | 13 |
| 13 | 14 | export const githubAuth = new GithubAuthProvider() | 14 | 15 | githubAuth.addScope('read:user') | @@ -35,11 +36,20 @@ export async function signInWithEmail(email: string, password: string) { | 35 | 36 |
| 36 | 37 | export async function signUpWithEmail(email: string, password: string) { | 37 | 38 | try { | | 39 | + // Create Firebase auth user | 38 | 40 | const result = await createUserWithEmailAndPassword(auth, email, password) | | 41 | + | | 42 | + // Create user document with Stripe customer | | 43 | + const { success, error: userDocError } = await createUserDocument(result.user.uid, email) | | 44 | + | | 45 | + if (!success) { | | 46 | + throw userDocError | | 47 | + } | | 48 | + | 39 | 49 | Logger.info(`New user created: ${result.user.email}`, 'Auth') | 40 | 50 | return { user: result.user, error: null } | 41 | 51 | } catch (error) { | 42 | 52 | Logger.error(`Email sign-up failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 'Auth', error) | 43 | 53 | return { user: null, error } | 44 | 54 | } | 45 | | -} | | 55 | +} |
Collapse file Copy file name to clipboard +31Lines changed: 31 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import { Timestamp } from 'firebase/firestore'; | | 2 | + | | 3 | +export interface CheckoutSession { | | 4 | + id: string; | | 5 | + userId: string; | | 6 | + priceId: string; | | 7 | + status: 'pending' | 'complete' | 'failed'; | | 8 | + sessionId: string; | | 9 | + createdAt: Timestamp; | | 10 | + updatedAt: Timestamp; | | 11 | +} | | 12 | + | | 13 | +export const checkoutConverter = { | | 14 | + toFirestore: (checkout: CheckoutSession) => { | | 15 | + return { | | 16 | + ...checkout, | | 17 | + }; | | 18 | + }, | | 19 | + fromFirestore: (snapshot: any, options: any): CheckoutSession => { | | 20 | + const data = snapshot.data(options); | | 21 | + return { | | 22 | + id: snapshot.id, | | 23 | + userId: data.userId, | | 24 | + priceId: data.priceId, | | 25 | + status: data.status, | | 26 | + sessionId: data.sessionId, | | 27 | + createdAt: data.createdAt, | | 28 | + updatedAt: data.updatedAt, | | 29 | + }; | | 30 | + }, | | 31 | +}; |
Collapse file Copy file name to clipboardExpand all lines: src/lib/firebase/user.ts +91-3Lines changed: 91 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import { updateProfile } from 'firebase/auth' | 2 | | -import { doc, getDoc, setDoc, updateDoc } from 'firebase/firestore' | | 2 | +import { doc, getDoc, setDoc, updateDoc, collection } from 'firebase/firestore' | 3 | 3 | import { auth, db } from './config' | 4 | | -import { Logger } from '@/lib/utils/logger' | | 4 | +import { Logger } from '../utils/logger' | | 5 | + | | 6 | +async function createStripeCustomer(email: string) { | | 7 | + try { | | 8 | + // Using the Firebase Extension endpoint | | 9 | + const response = await fetch('/api/stripe/customers', { | | 10 | + method: 'POST', | | 11 | + headers: { | | 12 | + 'Content-Type': 'application/json', | | 13 | + }, | | 14 | + body: JSON.stringify({ email }) | | 15 | + }); | | 16 | + | | 17 | + if (!response.ok) { | | 18 | + throw new Error('Failed to create Stripe customer'); | | 19 | + } | | 20 | + | | 21 | + const data = await response.json(); | | 22 | + return { customerId: data.customerId, error: null }; | | 23 | + } catch (error) { | | 24 | + Logger.error('Failed to create Stripe customer', 'StripeCustomer', error); | | 25 | + return { customerId: null, error }; | | 26 | + } | | 27 | +} | | 28 | + | | 29 | +export async function checkPremiumAccess(userId: string): Promise<boolean> { | | 30 | + try { | | 31 | + const subscriptionRef = doc(collection(db, 'subscriptions'), userId); | | 32 | + const subscriptionDoc = await getDoc(subscriptionRef); | | 33 | + | | 34 | + if (!subscriptionDoc.exists()) { | | 35 | + return false; | | 36 | + } | | 37 | + | | 38 | + const subscription = subscriptionDoc.data(); | | 39 | + return subscription.status === 'active'; | | 40 | + } catch (error) { | | 41 | + Logger.error('Failed to check premium access', 'PremiumAccess', error); | | 42 | + return false; | | 43 | + } | | 44 | +} | | 45 | + | | 46 | +export async function createUserDocument(uid: string, email: string) { | | 47 | + try { | | 48 | + const userRef = doc(db, 'users', uid); | | 49 | + const userDoc = await getDoc(userRef); | | 50 | + | | 51 | + if (!userDoc.exists()) { | | 52 | + // Create Stripe customer | | 53 | + const { customerId, error: stripeError } = await createStripeCustomer(email); | | 54 | + | | 55 | + if (stripeError) { | | 56 | + throw stripeError; | | 57 | + } | | 58 | + | | 59 | + // Create new user document with Stripe customer ID | | 60 | + const userData = { | | 61 | + id: uid, | | 62 | + email, | | 63 | + displayName: email.split('@')[0], // Default display name | | 64 | + subscription: { | | 65 | + tier: 'free', | | 66 | + stripeCustomerId: customerId | | 67 | + }, | | 68 | + progress: { | | 69 | + completedTutorials: [], | | 70 | + totalTimeSpent: 0 | | 71 | + }, | | 72 | + preferences: { | | 73 | + emailNotifications: true, | | 74 | + theme: 'system', | | 75 | + difficulty: 'beginner', | | 76 | + language: 'en' | | 77 | + }, | | 78 | + createdAt: new Date(), | | 79 | + updatedAt: new Date() | | 80 | + }; | | 81 | + | | 82 | + await setDoc(userRef, userData); | | 83 | + Logger.info(`New user document created for: ${uid}`, 'UserCreate'); | | 84 | + return { success: true, userData }; | | 85 | + } | | 86 | + | | 87 | + return { success: true, userData: userDoc.data() }; | | 88 | + } catch (error) { | | 89 | + Logger.error('Failed to create user document', 'UserCreate', error); | | 90 | + return { success: false, error }; | | 91 | + } | | 92 | +} | 5 | 93 |
| 6 | 94 | export async function updateUserDisplayName(displayName: string) { | 7 | 95 | try { | @@ -48,4 +136,4 @@ export async function updateUserDisplayName(displayName: string) { | 48 | 136 | Logger.error('Failed to update display name', 'UserUpdate', error) | 49 | 137 | return { success: false, error } | 50 | 138 | } | 51 | | -} | | 139 | +} |
|