Last active
March 15, 2024 10:00
-
-
Save azivkovi/445a50064558778841a50ee1479d874f to your computer and use it in GitHub Desktop.
checkoutSession.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Stripe from 'stripe'; | |
import prisma from '@/lib/prisma.lib'; | |
import dayjs from 'dayjs'; | |
import createOrUpdateUser from '@/helpers/create-update-user'; | |
import registerEducation from '@/helpers/register-education'; | |
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { | |
// https://github.com/stripe/stripe-node#configuration | |
apiVersion: '2022-11-15', | |
}); | |
const handler = async (req, res) => { | |
if (req.method === 'POST') { | |
const { | |
price, | |
monthlyRates, | |
validFor, | |
level, | |
person: { | |
firstName, | |
lastName, | |
email, | |
residence, | |
birthDate, | |
phoneNumber, | |
occupation, | |
payment, | |
}, | |
company, | |
education: { type, name, slug, parentId }, | |
installments, | |
token, | |
options, | |
} = req.body; | |
try { | |
/* Recaptcha check */ | |
if (token) { | |
const human = await recaptcha(token); | |
if (!human) { | |
return res.status(400).json({ | |
success: false, | |
error: 'Recaptcha fail', | |
}); | |
} | |
} | |
const stripeConnect = await prisma.stripe_connect.findFirst({ | |
where: { | |
slug, | |
}, | |
}); | |
// Create new user or update existing | |
await createOrUpdateUser( | |
firstName, | |
lastName, | |
email, | |
residence, | |
birthDate, | |
phoneNumber, | |
occupation | |
); | |
const existing = await stripe.customers.search({ | |
query: `email:\'${email}\'`, | |
}); | |
const customer = | |
existing.data.length === 0 | |
? await stripe.customers.create({ | |
email, | |
name: `${firstName} ${lastName}`, | |
}) | |
: existing.data[0]; | |
const mode = installments === 1 && type !== 'subscription' ? 'payment' : 'subscription'; | |
const params = { | |
payment_method_types: ['card'], | |
mode, | |
locale: 'hr', | |
customer: customer.id, | |
allow_promotion_codes: true, | |
line_items: [ | |
{ | |
price_data: { | |
unit_amount: parseInt(price * 100), | |
currency: 'eur', | |
product_data: { | |
name: `${name} - ${level} ${ | |
installments > 1 && type !== 'subscription' ? `(Broj rata: ${installments})` : '' | |
}`, | |
}, | |
}, | |
quantity: 1, | |
}, | |
], | |
metadata: { | |
installments: type === 'subscription' ? 0 : parseInt(installments) - 1, // Prva rata placa se odmah | |
connect: stripeConnect ? 'true' : 'false', | |
}, | |
expires_at: dayjs().add(30, 'minutes').unix(), | |
success_url: `${req.headers.origin}/moj-profil?prijava=uspjeh&session_id={CHECKOUT_SESSION_ID}`, | |
cancel_url: req.headers.referer, | |
}; | |
if (mode === 'subscription') { | |
params.line_items[0].price_data.recurring = { | |
interval: type === 'subscription' && installments === 1 ? 'year' : 'month', | |
}; | |
} | |
if (stripeConnect) { | |
if (mode === 'payment') { | |
params.payment_intent_data = { | |
transfer_data: { | |
destination: stripeConnect.accountId, | |
}, | |
}; | |
} else { | |
params.subscription_data = { | |
application_fee_percent: 100 - parseInt(stripeConnect.percent_share), | |
transfer_data: { | |
destination: stripeConnect.accountId, | |
}, | |
}; | |
} | |
} | |
const checkoutSession = await stripe.checkout.sessions.create(params); | |
// Create new registration entry | |
await registerEducation({ | |
firstName, | |
lastName, | |
company, | |
email, | |
phoneNumber, | |
payment, | |
checkoutId: checkoutSession.id, | |
status: 'pending', | |
validFor, | |
level, | |
price, | |
monthlyRates, | |
education: name, | |
educationType: type, | |
parentId, | |
slug, | |
options, | |
}); | |
res.status(200).json(checkoutSession); | |
} catch (error) { | |
console.log('ERROR', error); | |
const errorMessage = error instanceof Error ? error.message : 'Internal server error'; | |
res.status(500).json({ statusCode: 500, message: errorMessage }); | |
} | |
} else { | |
res.setHeader('Allow', 'POST'); | |
res.status(405).end('Method Not Allowed'); | |
} | |
}; | |
export default handler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment