GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add checkout session API and premium content handling · aidrivencoder/master-git-github@3bd0018

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src
    • app
      • api/create-checkout-session
        • route.ts
      • profile
        • page.tsx
      • tutorials/[id]
        • page.tsx
    • components
      • auth
        • SignUpForm.tsx
      • premium
        • PremiumContent.tsx
    • lib
      • firebase
        • auth.ts
        • schema
          • checkout.ts
        • user.ts
      • stripe
        • checkout.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/app/api/create-checkout-session/route.ts‎

Copy file name to clipboard
+63Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

‎src/app/profile/page.tsx‎

Copy file name to clipboardExpand all lines: src/app/profile/page.tsx
+11-2Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { useCallback } from 'react'
44
import { ProtectedRoute } from '@/components/auth/ProtectedRoute'
55
import { useAuth } from '@/components/providers/AuthProvider'
66
import { DisplayNameForm } from '@/components/profile/DisplayNameForm'
7+
import Link from 'next/link'
78

89
export default function ProfilePage() {
910
const { user } = useAuth()
@@ -61,8 +62,16 @@ export default function ProfilePage() {
6162
<dt className="text-sm font-medium text-gray-500 dark:text-gray-400">
6263
Subscription
6364
</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>
6675
</dd>
6776
</div>
6877
</dl>
Collapse file

‎src/app/tutorials/[id]/page.tsx‎

Copy file name to clipboardExpand all lines: src/app/tutorials/[id]/page.tsx
+8-1Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import { useEffect, useState } from 'react'
44
import { TutorialPage as ClientTutorialPage } from '@/components/tutorials/TutorialPage'
55
import { LoadingSpinner } from '@/components/ui/LoadingSpinner'
6+
import { PremiumContent } from '@/components/premium/PremiumContent'
67
import Link from 'next/link'
78
import { Tutorial } from '@/types/tutorial'
89
import { getTutorialById } from '@/tutorials/data'
@@ -68,7 +69,13 @@ export default function TutorialPage({ params }: TutorialPageProps) {
6869
return (
6970
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-8">
7071
<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+
)}
7279
</div>
7380
</div>
7481
)
Collapse file

‎src/components/auth/SignUpForm.tsx‎

Copy file name to clipboardExpand all lines: src/components/auth/SignUpForm.tsx
+13-2Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@ export function SignUpForm() {
1010
const [password, setPassword] = useState('')
1111
const [error, setError] = useState<string | null>(null)
1212
const [loading, setLoading] = useState(false)
13+
const [status, setStatus] = useState<string>('')
1314
const router = useRouter()
1415

1516
const handleSubmit = async (e: React.FormEvent) => {
1617
e.preventDefault()
1718
setError(null)
1819
setLoading(true)
20+
setStatus('Creating account...')
1921

2022
const { user, error } = await signUpWithEmail(email, password)
2123

@@ -25,6 +27,8 @@ export function SignUpForm() {
2527
return
2628
}
2729

30+
setStatus('Setting up your account...')
31+
2832
if (user) {
2933
router.push('/dashboard')
3034
}
@@ -72,8 +76,15 @@ export function SignUpForm() {
7276
disabled={loading}
7377
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"
7478
>
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+
)}
7687
</button>
7788
</form>
7889
)
79-
}
90+
}
Collapse file

‎src/components/premium/PremiumContent.tsx‎

Copy file name to clipboard
+50Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

‎src/lib/firebase/auth.ts‎

Copy file name to clipboardExpand all lines: src/lib/firebase/auth.ts
+12-2Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ import {
88
type User
99
} from 'firebase/auth'
1010
import { auth } from './config'
11-
import { Logger } from '@/lib/utils/logger'
11+
import { Logger } from '../utils/logger'
12+
import { createUserDocument } from './user'
1213

1314
export const githubAuth = new GithubAuthProvider()
1415
githubAuth.addScope('read:user')
@@ -35,11 +36,20 @@ export async function signInWithEmail(email: string, password: string) {
3536

3637
export async function signUpWithEmail(email: string, password: string) {
3738
try {
39+
// Create Firebase auth user
3840
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+
3949
Logger.info(`New user created: ${result.user.email}`, 'Auth')
4050
return { user: result.user, error: null }
4151
} catch (error) {
4252
Logger.error(`Email sign-up failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 'Auth', error)
4353
return { user: null, error }
4454
}
45-
}
55+
}
Collapse file

‎src/lib/firebase/schema/checkout.ts‎

Copy file name to clipboard
+31Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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

‎src/lib/firebase/user.ts‎

Copy file name to clipboardExpand all lines: src/lib/firebase/user.ts
+91-3Lines changed: 91 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,95 @@
11
import { updateProfile } from 'firebase/auth'
2-
import { doc, getDoc, setDoc, updateDoc } from 'firebase/firestore'
2+
import { doc, getDoc, setDoc, updateDoc, collection } from 'firebase/firestore'
33
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+
}
593

694
export async function updateUserDisplayName(displayName: string) {
795
try {
@@ -48,4 +136,4 @@ export async function updateUserDisplayName(displayName: string) {
48136
Logger.error('Failed to update display name', 'UserUpdate', error)
49137
return { success: false, error }
50138
}
51-
}
139+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.