Back to roadmaps lemonsqueezy Course

Applying Discount Codes Programmatically

To launch campaigns or reward loyal users, apply discount promo codes programmatically when generating your payment links.


1. Setting Up Promo Codes in Dashboard

Before applying codes via code, create them:

  1. Navigate to your Lemon Squeezy dashboard.
  2. Go to Discounts and click Create Discount.
  3. Set the code (for example, SAVE30), the type (percentage or flat rate), and click save.

2. Prefilling Discounts in Checkout Links

When creating checkouts using the SDK, specify the coupon code under the discountCode attribute:

import { createCheckout } from "@lemonsqueezy/lemonsqueezy.js";

async function generateDiscountedCheckout(variantId: string, userEmail: string) {
  const storeId = process.env.LEMONSQUEEZY_STORE_ID as string;

  const response = await createCheckout(storeId, variantId, {
    checkoutData: {
      email: userEmail,
      discountCode: "SAVE30", // Prefills discount automatically
    },
    productOptions: {
      redirectUrl: "https://mycompany.com/billing",
    },
  });

  if (response.error) {
    console.error("Discount checkout generation failed:", response.error.message);
    return null;
  }

  return response.data?.data.attributes.url;
}

3. Dynamic Discount Banners

If you want users to view discounts in your pricing UI before clicking purchase, check discount validity or amounts using standard GET request fetches before generating payment links.

Published on Last updated: