Lemon Squeezy JavaScript SDK

repository·main·Indexed 19 days ago

https://github.com/lmsqueezy/lemonsqueezy.js

The official JavaScript SDK for integrating Lemon Squeezy billing capabilities into server-side applications. This type-safe, tree-shakeable library provides functions to manage checkouts, customers, discounts, and discount redemptions. Key features include support for test mode and comprehensive TypeScript definitions for API parameters and response schemas.

Tokens
21K
Snippets
86
Records
116
Agent score
66%

What's inside @lemonsqueezy/lemonsqueezy.js

  1. SDK Features and Characteristics

    main

    The Lemon Squeezy JavaScript SDK provides several key benefits for developers:

    • Type-safe: Built with TypeScript and documented with TSDoc for better developer experience.
    • Tree-shakeable: The SDK is designed so you can import only the specific functions you need, minimizing your final bundle size.
  2. Configure the Lemon Squeezy SDK

    main

    To use the SDK, you must first create an API key in your Lemon Squeezy dashboard under Settings > API.

    Security Warning: Do not use this package directly in the browser. Using it client-side will expose your API key, giving anyone full access to your Lemon Squeezy account and stores. This SDK is intended for server-side environments.

    Initialize the SDK using lemonSqueezySetup by providing your apiKey and an optional onError handler.

    import {
      getAuthenticatedUser,
      lemonSqueezySetup,
    } from "@lemonsqueezy/lemonsqueezy.js";
    
    const apiKey = import.meta.env.LEMON_SQUEEZY_API_KEY;
    
    lemonSqueezySetup({
      apiKey,
      onError: (error) => console.error("Error!", error),
    });
    
    const { data, error } = await getAuthenticatedUser();
    
    if (error) {
      console.log(error.message);
    } else {
      console.log(data);
    }
  3. Install the @lemonsqueezy/lemonsqueezy.js package

    main

    Install the official Lemon Squeezy JavaScript SDK using your preferred package manager.

    # bun
    bun install @lemonsqueezy/lemonsqueezy.js
    
    # pnpm
    pnpm install @lemonsqueezy/lemonsqueezy.js
    
    # npm
    npm install @lemonsqueezy/lemonsqueezy.js
  4. Understand the Variant object structure

    main

    A Variant object represents a specific purchase option for a product. Key attributes include:

    • product_id: The ID of the parent product.
    • name: The display name of the variant.
    • slug: The unique identifier slug.
    • description: HTML description of the variant.
    • has_license_keys: Boolean indicating if license keys are generated on purchase.
    • license_length_unit: The unit for license expiration (days, months, or years).
    • status: The current VariantStatus.
    • links: An array of objects containing title and url for external links.
    • test_mode: Boolean indicating if the variant was created in test mode.
  5. List variants with listVariants()

    main

    Use listVariants to retrieve a paginated list of variants. You can filter the results by product ID or status, and control pagination using the page parameter.

    Parameters:

    • params (ListVariantsParams, optional): Configuration object.
      • filter (object, optional):
        • productId (number | string, optional): Only return variants belonging to this product.
        • status (string, optional): Only return variants with this specific status.
      • page (object, optional):
        • number (number, optional): The page number to retrieve.
        • size (number, optional): The number of results to return per page.
      • include (string[] | string, optional): Related resources to include.

    Returns: A ListVariants object containing a paginated list of variants.

    import { listVariants } from '@lemonsqueezy/lemonsqueezy.js';
    
    const variants = await listVariants({
      filter: {
        productId: 'prod_abc123',
        status: 'active'
      },
      page: {
        number: 1,
        size: 10
      }
    });
  6. Issue a partial refund with issueSubscriptionInvoiceRefund()

    main

    Use issueSubscriptionInvoiceRefund to issue a partial refund for a specific subscription invoice. The amount must be provided in cents.

    import { issueSubscriptionInvoiceRefund } from '@lemonsqueezy/lemonsqueezy.js';
    
    // Refund 1000 cents ($10.00)
    const refundedInvoice = await issueSubscriptionInvoiceRefund('inv_123', 1000);
  7. Update a subscription item with updateSubscriptionItem()

    main

    Update the details of a subscription item. This method is specifically for quantity-based billing.

    Warning: If the related subscription's product/variant has usage-based billing enabled, this will return a 422 Unprocessable Entity response.

    Usage Patterns

    • Quick Update: Pass a number directly to update only the quantity.
    • Detailed Update: Pass an object to control quantity and billing behavior.

    Billing Options

    • quantity (Required): The new unit quantity.
    • invoiceImmediately (Optional): If true, a new prorated invoice is generated and payment is attempted immediately. Defaults to false. Overridden by disableProrations.
    • disableProrations (Optional): If true, no proration is charged; the new price is applied at the next renewal. Defaults to false. Overrides invoiceImmediately.
    // Update just the quantity
    await updateSubscriptionItem('sub_item_id', 5);
    
    // Update quantity with billing options
    await updateSubscriptionItem('sub_item_id', {
      quantity: 10,
      invoiceImmediately: true,
      disableProrations: false
    });
  8. List orders with `listOrders()`

    main

    Use listOrders to retrieve a paginated list of orders, ordered by created_at in descending order.

    Filtering options:

    • filter.storeId: Only return orders belonging to a specific store.
    • filter.userEmail: Only return orders where the user_email matches.

    Pagination options:

    • page.number: The page number to retrieve.
    • page.size: The number of results per page.

    Include options:

    • include: Related resources to include in the response.
    import { listOrders } from '@lemonsqueezy/lemonsqueezy.js';
    
    const orders = await listOrders({
      filter: {
        storeId: 123,
        userEmail: 'user@example.com'
      },
      page: {
        number: 1,
        size: 20
      },
      include: ['customer']
    });
  9. List files with listFiles()

    main

    Use listFiles to retrieve a paginated list of files. You can filter the results by variantId and control pagination using page parameters.

    Parameters:

    • params (ListFilesParams, optional): Configuration object.
      • filter.variantId (number | string, optional): Only return files belonging to the specified variant ID.
      • page.number (number, optional): The page number to retrieve.
      • page.size (number, optional): The number of results to return per page.
      • include (string[] | string, optional): Related resources to include.
      • sort (string, optional): The parameter to determine the order of results.

    Returns:

    • A ListFiles object containing a paginated list of File objects.
    import { listFiles } from '@lemonsqueezy/lemonsqueezy.js';
    
    const files = await listFiles({
      filter: { variantId: 'abc-123' },
      page: { number: 1, size: 20 }
    });
  10. Retrieve the authenticated user with getAuthenticatedUser()

    main

    Use the getAuthenticatedUser() function to fetch details about the currently authenticated user associated with your API key. It returns a User object containing the user's profile information.

    import { getAuthenticatedUser } from '@lemonsqueezy/lemonsqueezy.js';
    
    const user = await getAuthenticatedUser();
    console.log(user);