| 2 | const { getDb } = require('../database'); |
| 3 | |
| 4 | const createCheckoutSession = async (req, res) => { |
| 5 | const { priceId } = req.body; |
| 6 | const userId = req.session.user.userId; |
| 7 | |
| 8 | console.log('Creating checkout session for user:', userId); |
| 9 | |
| 10 | try { |
| 11 | // Get the price details to check if it's recurring |
| 12 | const price = await stripe.prices.retrieve(priceId); |
| 13 | const isSubscription = price.type === 'recurring'; |
| 14 | |
| 15 | // Check if this is a monthly subscription for trial (exclude yearly) |
| 16 | const MONTHLY_SUBSCRIPTION_PRICE_IDS = [ |
| 17 | 'price_1R94kODv6kE7Gata9Zwzvvom', // BASIC_SUBSCRIPTION |
| 18 | 'price_1QtBf2Dv6kE7Gatasq6pq1Tc', // PLUS_SUBSCRIPTION |
| 19 | ]; |
| 20 | const isMonthlySubscription = MONTHLY_SUBSCRIPTION_PRICE_IDS.includes(priceId); |
| 21 | |
| 22 | // Check if user has already used their free trial |
| 23 | let userHasUsedTrial = false; |
| 24 | if (isSubscription && isMonthlySubscription) { |
| 25 | const db = getDb(); |
| 26 | const user = await db.collection('users').findOne({ userId }); |
| 27 | userHasUsedTrial = user?.hasUsedFreeTrial === true; |
| 28 | console.log('User has used free trial:', userHasUsedTrial); |
| 29 | } |
| 30 | |
| 31 | // Base session configuration |
| 32 | const sessionConfig = { |
| 33 | mode: isSubscription ? 'subscription' : 'payment', |
| 34 | payment_method_types: ['card'], |
| 35 | line_items: [{ |
| 36 | price: priceId, |
| 37 | quantity: 1, |
| 38 | }], |
| 39 | metadata: { |
| 40 | priceId: priceId |
| 41 | }, |
| 42 | allow_promotion_codes: true, |
| 43 | success_url: 'https://hanbokstudy.com/success?session_id={CHECKOUT_SESSION_ID}', |
| 44 | cancel_url: 'https://hanbokstudy.com/pricing', |
| 45 | client_reference_id: userId.toString(), |
| 46 | }; |
| 47 | |
| 48 | // Add trial settings for monthly subscriptions (only if user hasn't used trial yet) |
| 49 | if (isSubscription && isMonthlySubscription && !userHasUsedTrial) { |
| 50 | // sessionConfig.subscription_data = { |
| 51 | // trial_period_days: 7, |
| 52 | // trial_settings: { |
| 53 | // end_behavior: { |
| 54 | // missing_payment_method: 'cancel', |
| 55 | // }, |
| 56 | // }, |
| 57 | // }; |
| 58 | // sessionConfig.payment_method_collection = 'if_required'; |
| 59 | // console.log('Applying 7-day free trial to checkout session'); |
| 60 | } else if (isSubscription && isMonthlySubscription && userHasUsedTrial) { |
| 61 | console.log('User has already used free trial, no trial applied'); |