route.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { NextResponse } from 'next/server'
  2. import { getSession } from '@/lib/auth'
  3. import LemonSqueezy from '@lemonsqueezy/lemonsqueezy.js'
  4. const ls = new LemonSqueezy(process.env.LEMON_SQUEEZY_API_KEY as string)
  5. export async function POST(request: Request) {
  6. const session = await getSession()
  7. if (!session) {
  8. return NextResponse.json({ error: true, message: 'Not logged in.' }, { status: 401 })
  9. }
  10. const res = await request.json()
  11. if ( !res.variantId ) {
  12. return NextResponse.json({ error: true, message: 'No variant ID was provided.' }, { status: 400 })
  13. }
  14. // Customise the checkout experience
  15. // All the options: https://docs.lemonsqueezy.com/api/checkouts#create-a-checkout
  16. const attributes = {
  17. 'checkout_options': {
  18. 'embed': true,
  19. 'media': false,
  20. 'button_color': '#fde68a'
  21. },
  22. 'checkout_data': {
  23. 'email': session.user?.email, // Displays in the checkout form
  24. 'custom': {
  25. 'user_id': session.user?.id // Sent in the background; visible in webhooks and API calls
  26. }
  27. },
  28. 'product_options': {
  29. 'enabled_variants': [res.variantId], // Only show the selected variant in the checkout
  30. 'redirect_url': `${process.env.NEXT_PUBLIC_APP_URL}/billing/`,
  31. 'receipt_link_url': `${process.env.NEXT_PUBLIC_APP_URL}/billing/`,
  32. 'receipt_button_text': 'Go to your account',
  33. 'receipt_thank_you_note': 'Thank you for signing up to Lemonstand!'
  34. }
  35. }
  36. try {
  37. const checkout = await ls.createCheckout({
  38. storeId: Number(process.env.LEMON_SQUEEZY_STORE_ID),
  39. variantId: res.variantId,
  40. attributes
  41. })
  42. return NextResponse.json({'error': false, 'url': checkout['data']['attributes']['url']}, {status: 200})
  43. } catch (e) {
  44. return NextResponse.json({'error': true, 'message': e.message}, {status: 400})
  45. }
  46. }