


Introduction
For many entrepreneurs, the payment process feels like the ultimate test of patience. Just when you think you've finally untangled it all, another layer of complications pops up, reminding you that smooth sailing is still a distant dream.
You feel the same? Lemon Squeezy is your aspirin!
This magical payment potion simplifies everything, so you can ditch the payment drama and focus on the fun stuff. No more coding contortions needed. It's like having a payment unicorn on your team.
Why LemonSqueezy?
Well, imagine running your SaaS business without needing a PhD in tax compliance or an endless supply of aspirin for payment headaches. LemonSqueezy streamlines it all, from payments and subscriptions to global tax compliance and fraud prevention.
Plus, it’s got your back with multi-currency support and a storefront ready for all kinds of digital products. It’s like having a tech-savvy business partner who handles all the boring stuff so you can focus on what you do best—creating! Perfect for digital creators, entrepreneurs, and anyone who prefers clicking buttons to coding solutions.
Project Setup
Before we dive in, I just want to say that you can find the full code in my GitHub repo and catch the demo on my Instagram. Now, about this project on GitHub—it’s got two payment options: first, the classic one-time payment; second, the ever-fancy subscription model.
But for this tutorial, we’re going all-in on once time payment. Oh, and for my example, I’m using a monthly house cleaning service as the case study. It might sound a tad absurd, but hey, it’s all part of our coding workout! ?
1. Setup LemonSqueezy
In order to get started you should have created a store in Lemon Squeezy as well as some products and variants.
Make sure you have test mode ON. On publishing the store, it will turn OFF; check on the bottom left side.
Here's how my product look like
Next, let's generate an API Key at https://app.lemonsqueezy.com/settings/api to connect to our store:
Add this as an environment variable to your Next.js project:
LEMONSQUEEZY_API_KEY="[YOUR API KEY]"
2. Setuup the route handler
Next, create an API route to handle the payment procces, In this part, the final result we want is to obtain a checkoutUrl which we will later pass to the Frontend section.
export const dynamic = "force-dynamic"; export async function POST(req: NextRequest) { try { const reqData = await req.json(); if (!reqData.productId) { console.error("Product ID is missing"); return NextResponse.json({ message: "Product ID is required" }, { status: 400 }); } const response = await lemonSqueezyApiInstance.post("/checkouts", { data: { type: "checkouts", attributes: { checkout_data: { custom: { user_id: "123", }, }, }, relationships: { store: { data: { type: "stores", id: process.env.LEMON_SQUEEZY_STORE_ID?.toString(), }, }, variant: { data: { type: "variants", id: reqData.productId.toString(), }, }, }, }, }); const checkoutUrl = response.data.data.attributes.url; console.log(response.data); return NextResponse.json({ checkoutUrl }); } catch (error) { console.error("Error in POST /api/lemonsqueezy:", error); return NextResponse.json({ message: "An error occured" }, { status: 500 }); } }
Here's a simple explanation for this code :
- firs we ensures that the page is always dynamically rendered, which is important for real-time data by using export const dynamic = "force-dynamic";
- Define async function that handles POST requests to this API route, The function first checks if a product ID is provided. If not, it returns an error message.
- Next we do Api Call to lemonsqueezy to creates a new checkout session , including details like the store ID and product variant.
- To get storeId, Go to settings for that
- After the Api call , it extracts the checkout URL from the response:
const checkoutUrl = response.data.data.attributes.url;
- Finally, it returns this URL in the response:
return NextResponse.json({ checkoutUrl });
To make sure our API is working correctly, we need to test it. I use a tool called Postman for this. Before we start,we need the variantId of our product You can find this in your LemonSqueezy dashboard.
If everything is working correctly, you should get a response that includes a checkoutUrl
3. CreatIng the UI & Call the item data
Now that we've laid the groundwork, our next step is time to make the frontend look good, I am a huge fan of TailwindCSS so i make the pricing card with them
the code is availale here
Next lets set up an async function that calls the API route we just created. The function will send a POST request with the productId and, in return, get the checkout URL. Once you have the URL, open it in a new tab to send the user to the payment page.
const buyProcut1 = async () => { try { const response = await axios.post("../api/lemonsqueezy", { productId: "495244", }); console.log(response.data); window.open(response.data.checkoutUrl, "_blank"); } catch (error) { console.error(error); alert("Failed to buy product #1"); } };
That code is about
- Defines an asynchronous function called buyProduct1
- Next send a request to your server with a specific productId, If success opens a new browser tab with the checkout URL
- If anything goes wrong during the process, it catches the problem, logs it, and shows an alert to the user saying the purchase failed.
4. Setup Webhook
Last but not least, we're setting up webhooks to keep track of orders. Head back to your LemonSqueezy dashboard and set up a webhook.
For the URL, you’ll need something publicly accessible, which is tricky during local development. This is where ngrok comes in handy.
ngrok will give you a temporary public URL that forwards to your local machine, You can check this link to setup ngrok in your device :
https://dashboard.ngrok.com/get-started/setup/
Just like before, the code to handle the webhook is already done for you. All you need to do is set it up in your route handler and enjoy the sweet
Let's stay in touch on Instagram, Twitter, and GitHub—where the real magic happens.
Thanks for sticking around! ?
The above is the detailed content of Effortless Payments with Lemon Squeezy | Next.js Integration Made Simple. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
