Tutorials

How to preview checkout totals with the API

Dan Rowden  ·  May 12, 2023

Sometimes you may want to fetch and show in your application how much a certain customer would pay before they enter the checkout, taking into consideration things like location, discounts and tax ID validation.

This is easy to do on Lemon Squeezy with a single API call.

Because accessing the Lemon Squeezy requires an API key that provides programatic access to your store, you should never query our API directly in the client (e.g. a browser). Always build a wrapper around the API so your secret API key can stay private.

If you haven't already, make sure to read through our Developer Guide, which takes you through setting up a full integration from creating products and syncing customer data in your application.

How to preview a checkout using the API

Using the Lemon Squeezy API, you can make a call to create a checkout and add "preview": true to the request's attributes.

Here's an example request:

POST https://api.lemonsqueezy.com/v1/checkouts { "data": { "type": "checkouts", "attributes": { "checkout_data": { "billing_address": { "country": "DE" }, "tax_number": "DE 123456789", "discount_code": "SUMMER10" }, "preview": true }, "relationships": { "store": { "data": { "type": "stores", "id": "1" } }, "variant": { "data": { "type": "variants", "id": "1" } } } } }

In this request you can add information about the customer and order so you can get a proper estimate of their payment. Add in the details—for example, location, tax ID and discount code—in checkout_data. This will generate a specific checkout price preview based on your customer's data.

In the response, you will see the usual Checkout object but with extra data in data.attributes.preview, which will look like this:

{ ... "data": { "type": "checkouts", "id": "cb9beae2-a60c-4db1-b7c4-edf6b303628a", "attributes": { ... "preview": { "currency": "USD", "currency_rate": 1, "subtotal": 2400, "discount_total": 0, "tax": 456, "total": 2856, "subtotal_usd": 2400, "discount_total_usd": 0, "tax_usd": 456, "total_usd": 2856, "subtotal_formatted": "$24.00", "discount_total_formatted": "$0.00", "tax_formatted": "$4.56", "total_formatted": "$28.56" }, ... }, "relationships": { ... }, "links": { ... } } }

This preview object contains monetary values which you can then use to display pricing in your page: currency (taken from the product), subtotal, tax, discount total and total. All values are based on the price you set on your product variant combined with the data you provide in checkout_data in the request.

You can see a full explanation of each value in the Checkout docs.

Now you can display a price like this in your application:

Subtotal: $24.00 Tax: $4.56 Total: $28.56
Previous
Send webhooks to LogSnag