Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(lemon-squeezy): manage customers, subscriptions, discounts and license keys; verify webhooks (#16423)

Odai Ahmada756b367d2e0
diff --git a/bun.lock b/bun.lock
index b4fb2b8349b..425ab03c42b 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5124,15 +5124,17 @@
},
"packages/pieces/community/lemon-squeezy": {
"name": "@activepieces/piece-lemon-squeezy",
- "version": "0.2.0",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/letmepost": {
diff --git a/packages/pieces/community/lemon-squeezy/package.json b/packages/pieces/community/lemon-squeezy/package.json
index 9b117eb23e0..2800c1d6a07 100644
--- a/packages/pieces/community/lemon-squeezy/package.json
+++ b/packages/pieces/community/lemon-squeezy/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-lemon-squeezy",
- "version": "0.2.0",
+ "version": "0.3.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -8,14 +8,17 @@
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/lemon-squeezy/src/i18n/translation.json b/packages/pieces/community/lemon-squeezy/src/i18n/translation.json
index eba25de98df..bda9bbbfee5 100644
--- a/packages/pieces/community/lemon-squeezy/src/i18n/translation.json
+++ b/packages/pieces/community/lemon-squeezy/src/i18n/translation.json
@@ -1,12 +1,42 @@
{
"Lemon Squeezy is a payment gateway for e-commerce and subscription-based businesses.": "Lemon Squeezy is a payment gateway for e-commerce and subscription-based businesses.",
- "\nTo get your API Key:\n\n1. Go to your Lemon Squeezy dashboard\n2. Navigate to Settings » API\n3. Create a new API key\n4. Copy the API key and paste it here\n": "\nTo get your API Key:\n\n1. Go to your Lemon Squeezy dashboard\n2. Navigate to Settings » API\n3. Create a new API key\n4. Copy the API key and paste it here\n",
+ "\nTo get your API Key:\n\n1. Go to your Lemon Squeezy dashboard\n2. Navigate to Settings » API\n3. Create a new API key\n4. Copy the API key and paste it here\n\nKeys created in test mode only see test-mode data, and webhooks for this connection are created in the same mode.\n": "\nTo get your API Key:\n\n1. Go to your Lemon Squeezy dashboard\n2. Navigate to Settings » API\n3. Create a new API key\n4. Copy the API key and paste it here\n\nKeys created in test mode only see test-mode data, and webhooks for this connection are created in the same mode.\n",
"List Products": "List Products",
"List Orders": "List Orders",
"Get Order": "Get Order",
"List Subscriptions": "List Subscriptions",
"Create Checkout": "Create Checkout",
"List Customers": "List Customers",
+ "List Stores": "List Stores",
+ "Get Customer": "Get Customer",
+ "Find Customer by Email": "Find Customer by Email",
+ "Create Customer": "Create Customer",
+ "Update Customer": "Update Customer",
+ "Get Order (AI)": "Get Order (AI)",
+ "List Order Items": "List Order Items",
+ "Generate Order Invoice": "Generate Order Invoice",
+ "Get Product": "Get Product",
+ "List Variants": "List Variants",
+ "Get Subscription": "Get Subscription",
+ "List Subscriptions (AI)": "List Subscriptions (AI)",
+ "Cancel Subscription": "Cancel Subscription",
+ "Resume Subscription": "Resume Subscription",
+ "Pause Subscription": "Pause Subscription",
+ "Unpause Subscription": "Unpause Subscription",
+ "Change Subscription Plan": "Change Subscription Plan",
+ "List Subscription Invoices": "List Subscription Invoices",
+ "List Discounts": "List Discounts",
+ "Create Discount": "Create Discount",
+ "Delete Discount": "Delete Discount",
+ "Get License Key": "Get License Key",
+ "Update License Key": "Update License Key",
+ "List License Keys": "List License Keys",
+ "Get Discount": "Get Discount",
+ "List License Key Activations": "List License Key Activations",
+ "List Affiliates": "List Affiliates",
+ "List Discount Redemptions": "List Discount Redemptions",
+ "List Subscription Items": "List Subscription Items",
+ "Validate License Key": "Validate License Key",
"Custom API Call": "Custom API Call",
"Retrieve a paginated list of products from your Lemon Squeezy store.": "Retrieve a paginated list of products from your Lemon Squeezy store.",
"Retrieve a paginated list of orders from your Lemon Squeezy store, with optional filters.": "Retrieve a paginated list of orders from your Lemon Squeezy store, with optional filters.",
@@ -14,6 +44,36 @@
"Retrieve a paginated list of subscriptions from your Lemon Squeezy store.": "Retrieve a paginated list of subscriptions from your Lemon Squeezy store.",
"Create a checkout URL for a specific Lemon Squeezy product variant.": "Create a checkout URL for a specific Lemon Squeezy product variant.",
"Retrieve a paginated list of customers from your Lemon Squeezy store.": "Retrieve a paginated list of customers from your Lemon Squeezy store.",
+ "List the stores your API key can access.": "List the stores your API key can access.",
+ "Retrieve a customer by ID.": "Retrieve a customer by ID.",
+ "Look up a customer by email address.": "Look up a customer by email address.",
+ "Create a customer in a store.": "Create a customer in a store.",
+ "Update a customer's details or archive the customer.": "Update a customer's details or archive the customer.",
+ "Retrieve an order and its items by order ID.": "Retrieve an order and its items by order ID.",
+ "List order items, filtered by order, product or variant.": "List order items, filtered by order, product or variant.",
+ "Generate a downloadable PDF invoice for an order.": "Generate a downloadable PDF invoice for an order.",
+ "Retrieve a product by ID.": "Retrieve a product by ID.",
+ "List product variants, optionally for one product.": "List product variants, optionally for one product.",
+ "Retrieve a subscription by ID.": "Retrieve a subscription by ID.",
+ "List subscriptions filtered by IDs, email or status.": "List subscriptions filtered by IDs, email or status.",
+ "Cancel a subscription at the end of its billing period.": "Cancel a subscription at the end of its billing period.",
+ "Undo a cancellation during the grace period.": "Undo a cancellation during the grace period.",
+ "Pause payment collection for a subscription.": "Pause payment collection for a subscription.",
+ "Resume payment collection on a paused subscription.": "Resume payment collection on a paused subscription.",
+ "Move a subscription to another variant (plan). This can charge the customer.": "Move a subscription to another variant (plan). This can charge the customer.",
+ "List subscription invoices (renewal payments).": "List subscription invoices (renewal payments).",
+ "List discount codes.": "List discount codes.",
+ "Create a discount code in a store.": "Create a discount code in a store.",
+ "Permanently delete a discount code.": "Permanently delete a discount code.",
+ "Retrieve a license key by ID or by the key itself.": "Retrieve a license key by ID or by the key itself.",
+ "Change a license key's activation limit, expiry or disabled state.": "Change a license key's activation limit, expiry or disabled state.",
+ "List license keys, filtered by store, order or product.": "List license keys, filtered by store, order or product.",
+ "Retrieve a discount by ID.": "Retrieve a discount by ID.",
+ "List the activations (instances) of license keys.": "List the activations (instances) of license keys.",
+ "List affiliates, optionally by store or email.": "List affiliates, optionally by store or email.",
+ "List the orders that used a discount.": "List the orders that used a discount.",
+ "List the price items (quantity, usage-based) of subscriptions.": "List the price items (quantity, usage-based) of subscriptions.",
+ "Check whether a license key is valid, without activating it.": "Check whether a license key is valid, without activating it.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Store": "Store",
"Page": "Page",
@@ -32,6 +92,45 @@
"Expires At": "Expires At",
"Custom Data": "Custom Data",
"Email": "Email",
+ "Customer ID": "Customer ID",
+ "Name": "Name",
+ "City": "City",
+ "Region": "Region",
+ "Country": "Country",
+ "Archive Customer": "Archive Customer",
+ "Order ID": "Order ID",
+ "Product ID": "Product ID",
+ "Variant ID": "Variant ID",
+ "Billing Name": "Billing Name",
+ "Address": "Address",
+ "State / Region": "State / Region",
+ "ZIP / Postal Code": "ZIP / Postal Code",
+ "Notes": "Notes",
+ "Language": "Language",
+ "Status": "Status",
+ "Subscription ID": "Subscription ID",
+ "Store ID": "Store ID",
+ "Pause Mode": "Pause Mode",
+ "Resumes At": "Resumes At",
+ "New Variant": "New Variant",
+ "Charge Prorated Amount Now": "Charge Prorated Amount Now",
+ "Disable Proration": "Disable Proration",
+ "Code": "Code",
+ "Amount Type": "Amount Type",
+ "Amount": "Amount",
+ "Max Redemptions": "Max Redemptions",
+ "Starts At": "Starts At",
+ "Duration (subscriptions)": "Duration (subscriptions)",
+ "Duration in Months": "Duration in Months",
+ "Discount ID": "Discount ID",
+ "License Key ID": "License Key ID",
+ "License Key": "License Key",
+ "Activation Limit": "Activation Limit",
+ "Unlimited Activations": "Unlimited Activations",
+ "Never Expires": "Never Expires",
+ "Affiliate Email": "Affiliate Email",
+ "Price ID": "Price ID",
+ "Instance ID": "Instance ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -48,7 +147,7 @@
"Filter orders by customer email address.": "Filter orders by customer email address.",
"Filter orders by status.": "Filter orders by status.",
"Number of orders to return per page (1–100). Default is 10.": "Number of orders to return per page (1–100). Default is 10.",
- "Select the order to retrieve.": "Select the order to retrieve.",
+ "The order to retrieve (the list shows up to 1,000 orders).": "The order to retrieve (the list shows up to 1,000 orders).",
"Filter subscriptions by store.": "Filter subscriptions by store.",
"Filter subscriptions by order.": "Filter subscriptions by order.",
"Filter subscriptions by a specific order item ID.": "Filter subscriptions by a specific order item ID.",
@@ -70,6 +169,79 @@
"Filter customers by store. Leave empty to return customers from all stores.": "Filter customers by store. Leave empty to return customers from all stores.",
"Filter customers by their email address.": "Filter customers by their email address.",
"Number of customers to return per page (1–100). Default is 10.": "Number of customers to return per page (1–100). Default is 10.",
+ "Number of stores to return per page (1–100). Default is 10.": "Number of stores to return per page (1–100). Default is 10.",
+ "The numeric ID of the customer.": "The numeric ID of the customer.",
+ "The exact customer email address.": "The exact customer email address.",
+ "Filter by store. Leave empty to include every store the API key can see.": "Filter by store. Leave empty to include every store the API key can see.",
+ "The store to create the customer in.": "The store to create the customer in.",
+ "The customer's full name.": "The customer's full name.",
+ "The customer's email address.": "The customer's email address.",
+ "State, county or region.": "State, county or region.",
+ "ISO 3166-1 alpha-2 country code, for example US or DE.": "ISO 3166-1 alpha-2 country code, for example US or DE.",
+ "Archive the customer (it can be restored in the dashboard).": "Archive the customer (it can be restored in the dashboard).",
+ "The numeric order ID (the \"id\" field of an order).": "The numeric order ID (the \"id\" field of an order).",
+ "Only items of this order.": "Only items of this order.",
+ "Only items of this product.": "Only items of this product.",
+ "Only items of this variant.": "Only items of this variant.",
+ "Number of order items to return per page (1–100). Default is 10.": "Number of order items to return per page (1–100). Default is 10.",
+ "The numeric ID of the order.": "The numeric ID of the order.",
+ "Name or company on the invoice.": "Name or company on the invoice.",
+ "ISO 3166-1 alpha-2 country code, for example US.": "ISO 3166-1 alpha-2 country code, for example US.",
+ "Extra text printed on the invoice, such as a VAT number.": "Extra text printed on the invoice, such as a VAT number.",
+ "Invoice language code, for example en, de or fr. Defaults to English.": "Invoice language code, for example en, de or fr. Defaults to English.",
+ "The numeric ID of the product.": "The numeric ID of the product.",
+ "Only variants of this product.": "Only variants of this product.",
+ "Number of variants to return per page (1–100). Default is 10.": "Number of variants to return per page (1–100). Default is 10.",
+ "The numeric ID of the subscription.": "The numeric ID of the subscription.",
+ "Numeric store ID.": "Numeric store ID.",
+ "Numeric order ID.": "Numeric order ID.",
+ "Numeric order item ID.": "Numeric order item ID.",
+ "Numeric product ID.": "Numeric product ID.",
+ "Numeric variant ID.": "Numeric variant ID.",
+ "Exact customer email address.": "Exact customer email address.",
+ "Void stops access while paused; Free keeps access without paying.": "Void stops access while paused; Free keeps access without paying.",
+ "Auto-resume date (ISO 8601). Empty keeps it paused until unpaused.": "Auto-resume date (ISO 8601). Empty keeps it paused until unpaused.",
+ "The variant (plan) to move the subscription to.": "The variant (plan) to move the subscription to.",
+ "Charge the prorated difference now, not at the next renewal.": "Charge the prorated difference now, not at the next renewal.",
+ "Bill the new price from the next renewal, without proration.": "Bill the new price from the next renewal, without proration.",
+ "Only invoices of this subscription.": "Only invoices of this subscription.",
+ "Number of invoices to return per page (1–100). Default is 10.": "Number of invoices to return per page (1–100). Default is 10.",
+ "Number of discounts to return per page (1–100). Default is 10.": "Number of discounts to return per page (1–100). Default is 10.",
+ "The store the discount belongs to.": "The store the discount belongs to.",
+ "Internal name, for example \"Black Friday\".": "Internal name, for example \"Black Friday\".",
+ "The code customers enter: 3-256 uppercase letters and numbers.": "The code customers enter: 3-256 uppercase letters and numbers.",
+ "Percent off (1-100) or a fixed amount in cents (500 = $5.00).": "Percent off (1-100) or a fixed amount in cents (500 = $5.00).",
+ "Leave empty for unlimited.": "Leave empty for unlimited.",
+ "ISO 8601 date-time. Leave empty to start now.": "ISO 8601 date-time. Leave empty to start now.",
+ "ISO 8601 date-time. Leave empty for no expiry.": "ISO 8601 date-time. Leave empty for no expiry.",
+ "How long the discount applies to a subscription.": "How long the discount applies to a subscription.",
+ "Required when Duration is Repeating.": "Required when Duration is Repeating.",
+ "The numeric ID of the discount (not the code).": "The numeric ID of the discount (not the code).",
+ "The numeric license key ID. Leave empty when searching by key.": "The numeric license key ID. Leave empty when searching by key.",
+ "The full license key string. Leave empty when using the ID.": "The full license key string. Leave empty when using the ID.",
+ "The numeric ID of the license key.": "The numeric ID of the license key.",
+ "New maximum number of activations.": "New maximum number of activations.",
+ "Remove the activation limit.": "Remove the activation limit.",
+ "New ISO 8601 expiry date-time, for example 2027-01-31T00:00:00Z.": "New ISO 8601 expiry date-time, for example 2027-01-31T00:00:00Z.",
+ "Remove the expiry date.": "Remove the expiry date.",
+ "Leave empty to keep the current state.": "Leave empty to keep the current state.",
+ "Only keys from this order.": "Only keys from this order.",
+ "Only keys from this order item.": "Only keys from this order item.",
+ "Only keys for this product.": "Only keys for this product.",
+ "Number of license keys to return per page (1–100). Default is 10.": "Number of license keys to return per page (1–100). Default is 10.",
+ "Only activations of this license key.": "Only activations of this license key.",
+ "Number of activations to return per page (1–100). Default is 10.": "Number of activations to return per page (1–100). Default is 10.",
+ "Only affiliates of this store.": "Only affiliates of this store.",
+ "Exact email of the affiliate.": "Exact email of the affiliate.",
+ "Number of affiliates to return per page (1–100). Default is 10.": "Number of affiliates to return per page (1–100). Default is 10.",
+ "Only redemptions of this discount.": "Only redemptions of this discount.",
+ "Only redemptions on this order.": "Only redemptions on this order.",
+ "Number of redemptions to return per page (1–100). Default is 10.": "Number of redemptions to return per page (1–100). Default is 10.",
+ "Only items of this subscription.": "Only items of this subscription.",
+ "Only items on this price.": "Only items on this price.",
+ "Number of items to return per page (1–100). Default is 10.": "Number of items to return per page (1–100). Default is 10.",
+ "The full license key to check.": "The full license key to check.",
+ "Also check this activation (instance) of the key.": "Also check this activation (instance) of the key.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
"Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
@@ -90,6 +262,19 @@
"Unpaid": "Unpaid",
"Cancelled": "Cancelled",
"Expired": "Expired",
+ "Published": "Published",
+ "Draft": "Draft",
+ "Void (no access)": "Void (no access)",
+ "Free (keep access)": "Free (keep access)",
+ "Void": "Void",
+ "Partially Refunded": "Partially Refunded",
+ "Percent": "Percent",
+ "Fixed amount (cents)": "Fixed amount (cents)",
+ "Once": "Once",
+ "Repeating": "Repeating",
+ "Forever": "Forever",
+ "Disable key": "Disable key",
+ "Enable key": "Enable key",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
diff --git a/packages/pieces/community/lemon-squeezy/src/index.ts b/packages/pieces/community/lemon-squeezy/src/index.ts
index e3cc940beca..e9ceb7a2429 100644
--- a/packages/pieces/community/lemon-squeezy/src/index.ts
+++ b/packages/pieces/community/lemon-squeezy/src/index.ts
@@ -1,7 +1,7 @@
import { createPiece } from "@activepieces/pieces-framework";
import { createCustomApiCallAction } from "@activepieces/pieces-common";
import { lemonSqueezyAuth } from "./lib/common/auth";
-import { LEMON_SQUEEZY_API_BASE } from "./lib/common/api";
+import { LEMON_SQUEEZY_API_BASE } from "./lib/common/client";
import { orderCreatedTrigger } from "./lib/triggers/order-created";
import { orderRefundedTrigger } from "./lib/triggers/order-refunded";
import { subscriptionCreatedTrigger } from "./lib/triggers/subscription-created";
@@ -24,12 +24,42 @@ import { getOrder } from "./lib/actions/get-order";
import { listSubscriptions } from "./lib/actions/list-subscriptions";
import { createCheckout } from "./lib/actions/create-checkout";
import { listCustomers } from "./lib/actions/list-customers";
+import { listStores } from "./lib/actions/list-stores";
+import { getCustomer } from "./lib/actions/get-customer";
+import { findCustomerByEmail } from "./lib/actions/find-customer-by-email";
+import { createCustomer } from "./lib/actions/create-customer";
+import { updateCustomer } from "./lib/actions/update-customer";
+import { getOrderAi } from "./lib/actions/get-order-ai";
+import { listOrderItems } from "./lib/actions/list-order-items";
+import { generateOrderInvoice } from "./lib/actions/generate-order-invoice";
+import { getProduct } from "./lib/actions/get-product";
+import { listVariants } from "./lib/actions/list-variants";
+import { getSubscription } from "./lib/actions/get-subscription";
+import { listSubscriptionsAi } from "./lib/actions/list-subscriptions-ai";
+import { cancelSubscription } from "./lib/actions/cancel-subscription";
+import { resumeSubscription } from "./lib/actions/resume-subscription";
+import { pauseSubscription } from "./lib/actions/pause-subscription";
+import { unpauseSubscription } from "./lib/actions/unpause-subscription";
+import { changeSubscriptionPlan } from "./lib/actions/change-subscription-plan";
+import { listSubscriptionInvoices } from "./lib/actions/list-subscription-invoices";
+import { listDiscounts } from "./lib/actions/list-discounts";
+import { createDiscount } from "./lib/actions/create-discount";
+import { deleteDiscount } from "./lib/actions/delete-discount";
+import { getLicenseKey } from "./lib/actions/get-license-key";
+import { updateLicenseKey } from "./lib/actions/update-license-key";
+import { listLicenseKeys } from "./lib/actions/list-license-keys";
+import { getDiscount } from "./lib/actions/get-discount";
+import { listLicenseKeyInstances } from "./lib/actions/list-license-key-instances";
+import { listAffiliates } from "./lib/actions/list-affiliates";
+import { listDiscountRedemptions } from "./lib/actions/list-discount-redemptions";
+import { listSubscriptionItems } from "./lib/actions/list-subscription-items";
+import { validateLicense } from "./lib/actions/validate-license";
export const lemonSqueezy = createPiece({
displayName: "Lemon Squeezy",
auth: lemonSqueezyAuth,
description: "Lemon Squeezy is a payment gateway for e-commerce and subscription-based businesses.",
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: "https://cdn.activepieces.com/pieces/lemon-squeezy.png",
authors: ["onyedikachi-david", "Harmatta"],
actions: [
@@ -39,6 +69,36 @@ export const lemonSqueezy = createPiece({
listSubscriptions,
createCheckout,
listCustomers,
+ listStores,
+ getCustomer,
+ findCustomerByEmail,
+ createCustomer,
+ updateCustomer,
+ getOrderAi,
+ listOrderItems,
+ generateOrderInvoice,
+ getProduct,
+ listVariants,
+ getSubscription,
+ listSubscriptionsAi,
+ cancelSubscription,
+ resumeSubscription,
+ pauseSubscription,
+ unpauseSubscription,
+ changeSubscriptionPlan,
+ listSubscriptionInvoices,
+ listDiscounts,
+ createDiscount,
+ deleteDiscount,
+ getLicenseKey,
+ updateLicenseKey,
+ listLicenseKeys,
+ getDiscount,
+ listLicenseKeyInstances,
+ listAffiliates,
+ listDiscountRedemptions,
+ listSubscriptionItems,
+ validateLicense,
createCustomApiCallAction({
auth: lemonSqueezyAuth,
baseUrl: () => LEMON_SQUEEZY_API_BASE,
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/cancel-subscription.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/cancel-subscription.ts
new file mode 100644
index 00000000000..49cac2272be
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/cancel-subscription.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { deleteRecord, flatten, readPath, seg, toResource } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const cancelSubscription = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'cancel_subscription',
+ displayName: 'Cancel Subscription',
+ description: 'Cancel a subscription at the end of its billing period.',
+ audience: 'both',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Cancels a subscription at the end of its current billing period; the customer keeps access until then and it can be resumed with Resume Subscription during that grace period. Repeat calls are safe and return the cancelled subscription.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.subscription),
+ props: {
+ subscriptionId: Property.ShortText({
+ displayName: 'Subscription ID',
+ description: 'The numeric ID of the subscription.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const body = await deleteRecord({
+ apiKey: auth.secret_text,
+ path: `/subscriptions/${seg({ value: propsValue.subscriptionId, label: 'Subscription ID' })}`,
+ });
+ return flatten(toResource(readPath({ value: body, path: ['data'] })));
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/change-subscription-plan.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/change-subscription-plan.ts
new file mode 100644
index 00000000000..62268d67a0d
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/change-subscription-plan.ts
@@ -0,0 +1,67 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { numericId, patchRecord, seg } from '../common/client';
+import { productOptions, variantOptions } from '../common/props';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const changeSubscriptionPlan = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'change_subscription_plan',
+ displayName: 'Change Subscription Plan',
+ description: 'Move a subscription to another variant (plan). This can charge the customer.',
+ audience: 'human',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Moves a Lemon Squeezy subscription to another variant (plan) by subscription ID and variant ID. Can charge the customer: prorated by default, immediately if requested. Repeating the same change leaves the subscription unchanged.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.subscription),
+ props: {
+ subscriptionId: Property.ShortText({
+ displayName: 'Subscription ID',
+ description: 'The numeric ID of the subscription.',
+ required: true,
+ }),
+ productId: Property.Dropdown({
+ displayName: 'Product',
+ description: 'Select a product to filter the variant list below.',
+ required: false,
+ auth: lemonSqueezyAuth,
+ refreshers: ['auth'],
+ options: async ({ auth }) => productOptions({ auth }),
+ }),
+ variantId: Property.Dropdown({
+ displayName: 'New Variant',
+ description: 'The variant (plan) to move the subscription to.',
+ required: true,
+ auth: lemonSqueezyAuth,
+ refreshers: ['auth', 'productId'],
+ options: async ({ auth, productId }) => variantOptions({ auth, productId }),
+ }),
+ invoiceImmediately: Property.Checkbox({
+ displayName: 'Charge Prorated Amount Now',
+ description: 'Charge the prorated difference now, not at the next renewal.',
+ required: false,
+ defaultValue: false,
+ }),
+ disableProrations: Property.Checkbox({
+ displayName: 'Disable Proration',
+ description: 'Bill the new price from the next renewal, without proration.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ if (propsValue.invoiceImmediately && propsValue.disableProrations) {
+ throw new Error('Choose either Charge Prorated Amount Now or Disable Proration, not both.');
+ }
+ const variantId = Number(numericId({ value: propsValue.variantId, label: 'New Variant' }));
+ const attributes: Record<string, unknown> = { variant_id: variantId };
+ if (propsValue.invoiceImmediately) attributes['invoice_immediately'] = true;
+ if (propsValue.disableProrations) attributes['disable_prorations'] = true;
+ const id = numericId({ value: propsValue.subscriptionId, label: 'Subscription ID' });
+ return patchRecord({ apiKey: auth.secret_text, type: 'subscriptions', path: `/subscriptions/${seg({ value: id, label: 'Subscription ID' })}`, id: id, attributes: attributes });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/create-checkout.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/create-checkout.ts
index 29807e3221b..750822778eb 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/actions/create-checkout.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/create-checkout.ts
@@ -1,14 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { lemonSqueezyAuth } from '../common/auth';
-import {
- LEMON_SQUEEZY_API_BASE,
- getLemonSqueezyHeaders,
- fetchStoreOptions,
- fetchProductOptions,
- fetchVariantOptions,
-} from '../common/api';
-
+import { isoDateOrUndefined, lsRequest, numericId } from '../common/client';
+import { storeOptions, productOptions, variantOptions } from '../common/props';
+import { rawSchemas } from '../common/output-schemas';
export const createCheckout = createAction({
name: 'create_checkout',
classification: 'WRITE',
@@ -17,6 +11,7 @@ export const createCheckout = createAction({
audience: 'both',
aiMetadata: { description: 'Create a hosted Lemon Squeezy checkout URL for a given store and product variant, optionally pre-filling customer email/name, applying a discount code, overriding the price, attaching custom data, or setting a redirect and expiry. Use to generate a payable link to send a customer. Not idempotent: each call creates a new checkout, so repeated calls yield distinct URLs. Requires a store and variant ID.', idempotent: false },
auth: lemonSqueezyAuth,
+ outputSchema: rawSchemas.checkout,
props: {
storeId: Property.Dropdown({
displayName: 'Store',
@@ -24,13 +19,7 @@ export const createCheckout = createAction({
required: true,
auth: lemonSqueezyAuth,
refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchStoreOptions(auth.secret_text);
- return { options };
- },
+ options: async ({ auth }) => storeOptions({ auth }),
}),
productId: Property.Dropdown({
displayName: 'Product',
@@ -38,13 +27,7 @@ export const createCheckout = createAction({
required: false,
auth: lemonSqueezyAuth,
refreshers: ['auth', 'storeId'],
- options: async ({ auth, storeId }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchProductOptions(auth.secret_text, storeId as string | undefined);
- return { options };
- },
+ options: async ({ auth, storeId }) => productOptions({ auth, storeId }),
}),
variantId: Property.Dropdown({
displayName: 'Variant',
@@ -52,13 +35,7 @@ export const createCheckout = createAction({
required: true,
auth: lemonSqueezyAuth,
refreshers: ['auth', 'productId'],
- options: async ({ auth, productId }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchVariantOptions(auth.secret_text, productId as string | undefined);
- return { options };
- },
+ options: async ({ auth, productId }) => variantOptions({ auth, productId }),
}),
customerEmail: Property.ShortText({
displayName: 'Customer Email',
@@ -98,55 +75,42 @@ export const createCheckout = createAction({
},
async run(context) {
const { auth, propsValue } = context;
+ const storeId = numericId({ value: propsValue.storeId, label: 'Store' });
+ const variantId = numericId({ value: propsValue.variantId, label: 'Variant' });
+ const expiresAt = isoDateOrUndefined({ value: propsValue.expiresAt, label: 'Expires At' });
+
+ const customData = propsValue.customData;
+ if (customData !== undefined && customData !== null && (typeof customData !== 'object' || Array.isArray(customData))) {
+ throw new Error('Custom Data must be a JSON object of key-value pairs, for example {"user_id": "123"}.');
+ }
+ const customPrice = propsValue.customPrice;
+ if (customPrice !== undefined && customPrice !== null && (!Number.isInteger(Number(customPrice)) || Number(customPrice) < 0)) {
+ throw new Error('Custom Price must be a whole number of cents (0 or more).');
+ }
const checkoutData: Record<string, unknown> = {};
if (propsValue.customerEmail) checkoutData['email'] = propsValue.customerEmail;
if (propsValue.customerName) checkoutData['name'] = propsValue.customerName;
if (propsValue.discountCode) checkoutData['discount_code'] = propsValue.discountCode;
- if (propsValue.customData) checkoutData['custom'] = propsValue.customData;
-
- const checkoutOptions: Record<string, unknown> = {};
- if (propsValue.redirectUrl) checkoutOptions['redirect_url'] = propsValue.redirectUrl;
+ if (customData && Object.keys(customData).length > 0) checkoutData['custom'] = customData;
const attributes: Record<string, unknown> = {};
+ if (Object.keys(checkoutData).length > 0) attributes['checkout_data'] = checkoutData;
+ if (propsValue.redirectUrl) attributes['product_options'] = { redirect_url: propsValue.redirectUrl };
+ if (customPrice !== undefined && customPrice !== null) attributes['custom_price'] = Number(customPrice);
+ if (expiresAt) attributes['expires_at'] = expiresAt;
- if (Object.keys(checkoutData).length > 0) {
- attributes['checkout_data'] = checkoutData;
- }
-
- if (Object.keys(checkoutOptions).length > 0) {
- attributes['checkout_options'] = checkoutOptions;
- }
-
- if (propsValue.customPrice != null) {
- attributes['custom_price'] = propsValue.customPrice;
- }
-
- if (propsValue.expiresAt) {
- attributes['expires_at'] = propsValue.expiresAt;
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `${LEMON_SQUEEZY_API_BASE}/checkouts`,
- headers: getLemonSqueezyHeaders(auth.secret_text),
+ const response = await lsRequest({
+ apiKey: auth.secret_text,
+ method: 'POST',
+ path: '/checkouts',
body: {
data: {
type: 'checkouts',
attributes,
relationships: {
- store: {
- data: {
- type: 'stores',
- id: String(propsValue.storeId),
- },
- },
- variant: {
- data: {
- type: 'variants',
- id: String(propsValue.variantId),
- },
- },
+ store: { data: { type: 'stores', id: storeId } },
+ variant: { data: { type: 'variants', id: variantId } },
},
},
},
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/create-customer.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/create-customer.ts
new file mode 100644
index 00000000000..45fa1d38364
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/create-customer.ts
@@ -0,0 +1,44 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { createRecord, numericId } from '../common/client';
+import { storeDropdown } from '../common/props';
+import { countryCode } from '../common/validation';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const createCustomer = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'create_customer',
+ displayName: 'Create Customer',
+ description: 'Create a customer in a store.',
+ audience: 'both',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Creates a customer record in a Lemon Squeezy store with a name and email, and optionally city, region and 2-letter country code. Not idempotent: Lemon Squeezy rejects a second customer with the same email in the same store, so look the email up first with Find Customer by Email.',
+ idempotent: false,
+ },
+ outputSchema: recordSchema(flatFields.customer),
+ props: {
+ storeId: storeDropdown({ required: true, description: 'The store to create the customer in.' }),
+ name: Property.ShortText({ displayName: 'Name', description: 'The customer\'s full name.', required: true }),
+ email: Property.ShortText({ displayName: 'Email', description: 'The customer\'s email address.', required: true }),
+ city: Property.ShortText({ displayName: 'City', required: false }),
+ region: Property.ShortText({ displayName: 'Region', description: 'State, county or region.', required: false }),
+ country: Property.ShortText({ displayName: 'Country', description: 'ISO 3166-1 alpha-2 country code, for example US or DE.', required: false }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const storeId = numericId({ value: propsValue.storeId, label: 'Store' });
+ const attributes: Record<string, unknown> = { name: propsValue.name, email: propsValue.email };
+ if (propsValue.city) attributes['city'] = propsValue.city;
+ if (propsValue.region) attributes['region'] = propsValue.region;
+ if (propsValue.country) attributes['country'] = countryCode(propsValue.country);
+ return createRecord({
+ apiKey: auth.secret_text,
+ path: '/customers',
+ type: 'customers',
+ attributes,
+ relationships: { store: { data: { type: 'stores', id: storeId } } },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/create-discount.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/create-discount.ts
new file mode 100644
index 00000000000..8e9140d421e
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/create-discount.ts
@@ -0,0 +1,85 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { createRecord, isoDateOrUndefined, numericId } from '../common/client';
+import { storeDropdown } from '../common/props';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const createDiscount = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'create_discount',
+ displayName: 'Create Discount',
+ description: 'Create a discount code in a store.',
+ audience: 'both',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Creates a discount code in a Lemon Squeezy store: percent (1-100) or fixed amount in cents, optional redemption limit, start/expiry dates (ISO 8601) and duration for subscriptions (once, repeating with months, forever). Not idempotent: codes must be unique, so a repeat call with the same code fails.',
+ idempotent: false,
+ },
+ outputSchema: recordSchema(flatFields.discount),
+ props: {
+ storeId: storeDropdown({ required: true, description: 'The store the discount belongs to.' }),
+ name: Property.ShortText({ displayName: 'Name', description: 'Internal name, for example "Black Friday".', required: true }),
+ code: Property.ShortText({ displayName: 'Code', description: 'The code customers enter: 3-256 uppercase letters and numbers.', required: true }),
+ amountType: Property.StaticDropdown({
+ displayName: 'Amount Type',
+ required: true,
+ defaultValue: 'percent',
+ options: { options: [{ label: 'Percent', value: 'percent' }, { label: 'Fixed amount (cents)', value: 'fixed' }] },
+ }),
+ amount: Property.Number({
+ displayName: 'Amount',
+ description: 'Percent off (1-100) or a fixed amount in cents (500 = $5.00).',
+ required: true,
+ }),
+ maxRedemptions: Property.Number({ displayName: 'Max Redemptions', description: 'Leave empty for unlimited.', required: false }),
+ startsAt: Property.ShortText({ displayName: 'Starts At', description: 'ISO 8601 date-time. Leave empty to start now.', required: false }),
+ expiresAt: Property.ShortText({ displayName: 'Expires At', description: 'ISO 8601 date-time. Leave empty for no expiry.', required: false }),
+ duration: Property.StaticDropdown({
+ displayName: 'Duration (subscriptions)',
+ description: 'How long the discount applies to a subscription.',
+ required: false,
+ defaultValue: 'once',
+ options: { options: [{ label: 'Once', value: 'once' }, { label: 'Repeating', value: 'repeating' }, { label: 'Forever', value: 'forever' }] },
+ }),
+ durationInMonths: Property.Number({ displayName: 'Duration in Months', description: 'Required when Duration is Repeating.', required: false }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const storeId = numericId({ value: propsValue.storeId, label: 'Store' });
+ const code = String(propsValue.code ?? '').trim();
+ if (!/^[A-Z0-9]{3,256}$/.test(code)) throw new Error('Code must be 3-256 uppercase letters (A-Z) and numbers.');
+ const amountType = propsValue.amountType;
+ if (amountType !== 'percent' && amountType !== 'fixed') throw new Error('Amount Type must be percent or fixed.');
+ const amount = Number(propsValue.amount);
+ if (!Number.isInteger(amount) || amount < 1 || (amountType === 'percent' && amount > 100)) {
+ throw new Error(amountType === 'percent' ? 'Amount must be a whole percent between 1 and 100.' : 'Amount must be a whole number of cents (1 or more).');
+ }
+ const attributes: Record<string, unknown> = { name: propsValue.name, code, amount, amount_type: amountType };
+ if (propsValue.maxRedemptions !== undefined && propsValue.maxRedemptions !== null) {
+ const max = Number(propsValue.maxRedemptions);
+ if (!Number.isInteger(max) || max < 1) throw new Error('Max Redemptions must be a whole number of 1 or more.');
+ attributes['is_limited_redemptions'] = true;
+ attributes['max_redemptions'] = max;
+ }
+ const startsAt = isoDateOrUndefined({ value: propsValue.startsAt, label: 'Starts At' });
+ const expiresAt = isoDateOrUndefined({ value: propsValue.expiresAt, label: 'Expires At' });
+ if (startsAt && expiresAt && Date.parse(expiresAt) <= Date.parse(startsAt)) throw new Error('Expires At must be after Starts At.');
+ if (startsAt) attributes['starts_at'] = startsAt;
+ if (expiresAt) attributes['expires_at'] = expiresAt;
+ const duration = propsValue.duration || 'once';
+ attributes['duration'] = duration;
+ if (duration === 'repeating') {
+ const months = Number(propsValue.durationInMonths);
+ if (!Number.isInteger(months) || months < 1) throw new Error('Duration in Months must be a whole number of 1 or more when Duration is Repeating.');
+ attributes['duration_in_months'] = months;
+ }
+ return createRecord({
+ apiKey: auth.secret_text,
+ path: '/discounts',
+ type: 'discounts',
+ attributes,
+ relationships: { store: { data: { type: 'stores', id: storeId } } },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/delete-discount.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/delete-discount.ts
new file mode 100644
index 00000000000..f9f0c67faaa
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/delete-discount.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { LemonSqueezyApiError, lsRequest, numericId, seg } from '../common/client';
+
+
+export const deleteDiscount = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'delete_discount',
+ displayName: 'Delete Discount',
+ description: 'Permanently delete a discount code.',
+ audience: 'both',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Lemon Squeezy discount by numeric discount ID; customers can no longer use the code. Past orders keep their discount. Idempotent: deleting a discount that is already gone returns already_deleted=true.',
+ idempotent: true,
+ },
+ outputSchema: {
+ fields: [
+ { key: 'id', label: 'Discount ID' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'already_deleted', label: 'Already Deleted', format: 'boolean' },
+ ],
+ },
+ props: {
+ discountId: Property.ShortText({
+ displayName: 'Discount ID',
+ description: 'The numeric ID of the discount (not the code).',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const id = numericId({ value: propsValue.discountId, label: 'Discount ID' });
+ try {
+ await lsRequest({ apiKey: auth.secret_text, method: 'DELETE', path: `/discounts/${seg({ value: id, label: 'Discount ID' })}` });
+ return { id, deleted: true, already_deleted: false };
+ } catch (error) {
+ if (error instanceof LemonSqueezyApiError && error.status === 404) {
+ return { id, deleted: true, already_deleted: true };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/find-customer-by-email.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/find-customer-by-email.ts
new file mode 100644
index 00000000000..45cb0cfbd79
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/find-customer-by-email.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords } from '../common/client';
+import { storeDropdown } from '../common/props';
+import { flatFields } from '../common/output-schemas';
+
+export const findCustomerByEmail = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'find_customer_by_email',
+ displayName: 'Find Customer by Email',
+ description: 'Look up a customer by email address.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Finds a Lemon Squeezy customer by exact email address, optionally within one store. Returns found=false (not an error) when no customer matches; when the email exists in several stores, the first match is returned and all matches are listed. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'customer', label: 'Customer', description: 'Null when no customer matches.', children: flatFields.customer },
+ { key: 'matches', label: 'All Matches', listItems: flatFields.customer, labelKey: 'name' },
+ ],
+ },
+ props: {
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'The exact customer email address.',
+ required: true,
+ }),
+ storeId: storeDropdown({ required: false, description: 'Filter by store. Leave empty to include every store the API key can see.' }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const email = propsValue.email.trim();
+ if (!email.includes('@')) throw new Error('Email must be a valid email address.');
+ const result = await listRecords({
+ apiKey: auth.secret_text,
+ path: '/customers',
+ query: {
+ 'filter[email]': email,
+ 'filter[store_id]': propsValue.storeId ? String(propsValue.storeId) : undefined,
+ 'page[size]': '100',
+ },
+ });
+ return { found: result.items.length > 0, customer: result.items[0] ?? null, matches: result.items };
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/generate-order-invoice.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/generate-order-invoice.ts
new file mode 100644
index 00000000000..a68aa53a7ec
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/generate-order-invoice.ts
@@ -0,0 +1,62 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { lsRequest, numericId, seg, readPath } from '../common/client';
+import { countryCode } from '../common/validation';
+
+
+export const generateOrderInvoice = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'generate_order_invoice',
+ displayName: 'Generate Order Invoice',
+ description: 'Generate a downloadable PDF invoice for an order.',
+ audience: 'both',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Generates a PDF invoice for a paid Lemon Squeezy order with the billing name and address you give, and returns a temporary download URL. Calling it again regenerates the same invoice with the latest details. Send the URL to the customer; it expires.',
+ idempotent: true,
+ },
+ outputSchema: {
+ fields: [
+ { key: 'order_id', label: 'Order ID' },
+ { key: 'invoice_url', label: 'Invoice Download URL', format: 'url', description: 'Signed, temporary link to the PDF.' },
+ ],
+ },
+ props: {
+ orderId: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The numeric ID of the order.',
+ required: true,
+ }),
+ name: Property.ShortText({ displayName: 'Billing Name', description: 'Name or company on the invoice.', required: true }),
+ address: Property.ShortText({ displayName: 'Address', required: true }),
+ city: Property.ShortText({ displayName: 'City', required: true }),
+ state: Property.ShortText({ displayName: 'State / Region', required: false }),
+ zipCode: Property.ShortText({ displayName: 'ZIP / Postal Code', required: true }),
+ country: Property.ShortText({ displayName: 'Country', description: 'ISO 3166-1 alpha-2 country code, for example US.', required: true }),
+ notes: Property.LongText({ displayName: 'Notes', description: 'Extra text printed on the invoice, such as a VAT number.', required: false }),
+ locale: Property.ShortText({ displayName: 'Language', description: 'Invoice language code, for example en, de or fr. Defaults to English.', required: false }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const id = numericId({ value: propsValue.orderId, label: 'Order ID' });
+ const { body } = await lsRequest({
+ apiKey: auth.secret_text,
+ method: 'POST',
+ path: `/orders/${seg({ value: id, label: 'Order ID' })}/generate-invoice`,
+ query: {
+ name: propsValue.name,
+ address: propsValue.address,
+ city: propsValue.city,
+ state: propsValue.state,
+ zip_code: propsValue.zipCode,
+ country: countryCode(propsValue.country),
+ notes: propsValue.notes,
+ locale: propsValue.locale,
+ },
+ });
+ const url = readPath({ value: body, path: ['meta', 'urls', 'download_invoice'] });
+ if (typeof url !== 'string' || !url) throw new Error('Lemon Squeezy did not return an invoice URL for this order.');
+ return { order_id: id, invoice_url: url };
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/get-customer.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-customer.ts
new file mode 100644
index 00000000000..172f96296d8
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-customer.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { getRecord, seg } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const getCustomer = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'get_customer',
+ displayName: 'Get Customer',
+ description: 'Retrieve a customer by ID.',
+ audience: 'both',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Fetches one Lemon Squeezy customer by numeric customer ID, including status, revenue, MRR and customer portal URL. Use Find Customer by Email when you only have an email. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.customer),
+ props: {
+ customerId: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The numeric ID of the customer.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return getRecord({ apiKey: auth.secret_text, path: `/customers/${seg({ value: propsValue.customerId, label: 'Customer ID' })}` });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/get-discount.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-discount.ts
new file mode 100644
index 00000000000..d1673259de2
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-discount.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { getRecord, seg } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const getDiscount = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'get_discount',
+ displayName: 'Get Discount',
+ description: 'Retrieve a discount by ID.',
+ audience: 'both',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Fetches one Lemon Squeezy discount by numeric discount ID: code, amount and type, redemption limit, start/expiry dates and status. Use before sharing a code with a customer to confirm it is published and not expired; use List Discounts to find the ID from a code. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.discount),
+ props: {
+ discountId: Property.ShortText({
+ displayName: 'Discount ID',
+ description: 'The numeric ID of the discount (not the code).',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return getRecord({ apiKey: auth.secret_text, path: `/discounts/${seg({ value: propsValue.discountId, label: 'Discount ID' })}` });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/get-license-key.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-license-key.ts
new file mode 100644
index 00000000000..b2ad319aa8a
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-license-key.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { LemonSqueezyApiError, getRecord, lookupLicenseKeyId, seg } from '../common/client';
+import { flatFields } from '../common/output-schemas';
+
+export const getLicenseKey = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'get_license_key',
+ displayName: 'Get License Key',
+ description: 'Retrieve a license key by ID or by the key itself.',
+ audience: 'both',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Fetches one Lemon Squeezy license key by numeric license key ID or by the full key string (give exactly one). Returns the full key, status, activation limit and count, expiry and the owning order/customer. Returns found=false when the key does not exist. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'license_key', label: 'License Key', description: 'Null when not found.', children: flatFields.licenseKey },
+ ],
+ },
+ props: {
+ licenseKeyId: Property.ShortText({
+ displayName: 'License Key ID',
+ description: 'The numeric license key ID. Leave empty when searching by key.',
+ required: false,
+ }),
+ licenseKey: Property.ShortText({
+ displayName: 'License Key',
+ description: 'The full license key string. Leave empty when using the ID.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const byId = propsValue.licenseKeyId?.trim() || undefined;
+ const byKey = propsValue.licenseKey?.trim() || undefined;
+ if ((byId ? 1 : 0) + (byKey ? 1 : 0) !== 1) throw new Error('Provide exactly one of License Key ID or License Key.');
+ const id = byId ?? ((byKey ? await lookupLicenseKeyId(byKey) : undefined));
+ if (!id) return { found: false, license_key: null };
+ try {
+ return { found: true, license_key: await getRecord({ apiKey: auth.secret_text, path: `/license-keys/${seg({ value: id, label: 'License Key ID' })}` }) };
+ } catch (error) {
+ if (error instanceof LemonSqueezyApiError && error.status === 404) return { found: false, license_key: null };
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/get-order-ai.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-order-ai.ts
new file mode 100644
index 00000000000..3f5506aed52
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-order-ai.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { flatten, lsRequest, readPath, seg, toResource } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const getOrderAi = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'get_order_ai',
+ displayName: 'Get Order (AI)',
+ description: 'Retrieve an order and its items by order ID.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Fetches one Lemon Squeezy order by numeric order ID (not the order number shown to customers), with totals in cents, status, customer email, receipt URL and all order items. Use List Orders to find the ID by email or status. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema([...flatFields.order, { key: 'order_items', label: 'Order Items', listItems: flatFields.orderItem, labelKey: 'product_name' }]),
+ props: {
+ orderId: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'The numeric order ID (the "id" field of an order).',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const { body } = await lsRequest({
+ apiKey: auth.secret_text,
+ method: 'GET',
+ path: `/orders/${seg({ value: propsValue.orderId, label: 'Order ID' })}`,
+ query: { include: 'order-items' },
+ });
+ const included = readPath({ value: body, path: ['included'] });
+ return {
+ ...flatten(toResource(readPath({ value: body, path: ['data'] }))),
+ order_items: (Array.isArray(included) ? included : [])
+ .map(toResource)
+ .filter((r) => r.type === 'order-items')
+ .map(flatten),
+ };
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/get-order.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-order.ts
index 58ccd5c671c..6b7f6ab28bf 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/actions/get-order.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-order.ts
@@ -1,41 +1,33 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { lemonSqueezyAuth } from '../common/auth';
-import { LEMON_SQUEEZY_API_BASE, getLemonSqueezyHeaders, fetchOrderOptions } from '../common/api';
-
+import { lsRequest, seg } from '../common/client';
+import { orderOptions } from '../common/props';
+import { rawSchemas } from '../common/output-schemas';
export const getOrder = createAction({
name: 'get_order',
classification: 'READ',
displayName: 'Get Order',
description: 'Retrieve the details of a specific order by its ID.',
- audience: 'both',
- aiMetadata: { description: 'Fetch the full details of one Lemon Squeezy order by its order ID. Use when you already have an order ID and need its complete record; to discover orders by store, email, or status first, use List Orders. Read-only and idempotent.', idempotent: true },
+ audience: 'human',
auth: lemonSqueezyAuth,
+ outputSchema: rawSchemas.order,
props: {
orderId: Property.Dropdown({
displayName: 'Order',
- description: 'Select the order to retrieve.',
+ description: 'The order to retrieve (the list shows up to 1,000 orders).',
required: true,
auth: lemonSqueezyAuth,
refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchOrderOptions(auth.secret_text);
- return { options };
- },
+ options: async ({ auth }) => orderOptions({ auth }),
}),
},
async run(context) {
const { auth, propsValue } = context;
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `${LEMON_SQUEEZY_API_BASE}/orders/${propsValue.orderId}`,
- headers: getLemonSqueezyHeaders(auth.secret_text),
+ const response = await lsRequest({
+ apiKey: auth.secret_text,
+ method: 'GET',
+ path: `/orders/${seg({ value: propsValue.orderId, label: 'Order' })}`,
});
-
return response.body;
},
});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/get-product.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-product.ts
new file mode 100644
index 00000000000..672ce0e47b0
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-product.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { getRecord, seg } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const getProduct = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'get_product',
+ displayName: 'Get Product',
+ description: 'Retrieve a product by ID.',
+ audience: 'both',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Fetches one Lemon Squeezy product by numeric product ID: name, status, price range in cents and buy-now URL. Use List Variants for its variants. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.product),
+ props: {
+ productId: Property.ShortText({
+ displayName: 'Product ID',
+ description: 'The numeric ID of the product.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return getRecord({ apiKey: auth.secret_text, path: `/products/${seg({ value: propsValue.productId, label: 'Product ID' })}` });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/get-subscription.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-subscription.ts
new file mode 100644
index 00000000000..ef8d9cfaa90
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/get-subscription.ts
@@ -0,0 +1,30 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { getRecord, seg } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const getSubscription = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'get_subscription',
+ displayName: 'Get Subscription',
+ description: 'Retrieve a subscription by ID.',
+ audience: 'both',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Fetches one Lemon Squeezy subscription by numeric subscription ID: status, plan (product/variant), renewal and end dates, pause state, card and customer portal URLs. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.subscription),
+ props: {
+ subscriptionId: Property.ShortText({
+ displayName: 'Subscription ID',
+ description: 'The numeric ID of the subscription.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return getRecord({ apiKey: auth.secret_text, path: `/subscriptions/${seg({ value: propsValue.subscriptionId, label: 'Subscription ID' })}` });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-affiliates.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-affiliates.ts
new file mode 100644
index 00000000000..a6810e41dc4
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-affiliates.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listAffiliates = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_affiliates',
+ displayName: 'List Affiliates',
+ description: 'List affiliates, optionally by store or email.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy affiliates with their status and total/unpaid earnings in cents, optionally filtered by store ID or exact affiliate email, with page-based pagination. Use to look up an affiliate before a payout or to report on the affiliate program. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.affiliate, itemLabel: 'user_email' }),
+ props: {
+ storeId: Property.ShortText({ displayName: 'Store ID', description: 'Only affiliates of this store.', required: false }),
+ userEmail: Property.ShortText({ displayName: 'Affiliate Email', description: 'Exact email of the affiliate.', required: false }),
+ ...pageProps('affiliates'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/affiliates',
+ query: {
+ 'filter[store_id]': optionalId({ value: propsValue.storeId, label: 'Store ID' }),
+ 'filter[user_email]': propsValue.userEmail?.trim() || undefined,
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-customers.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-customers.ts
index 7d5efb91563..d8aae322973 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-customers.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-customers.ts
@@ -1,8 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { lemonSqueezyAuth } from '../common/auth';
-import { LEMON_SQUEEZY_API_BASE, getLemonSqueezyHeaders, buildQueryString, fetchStoreOptions } from '../common/api';
-
+import { lsRequest, pageParams } from '../common/client';
+import { storeOptions } from '../common/props';
+import { rawSchemas } from '../common/output-schemas';
export const listCustomers = createAction({
name: 'list_customers',
classification: 'SEARCH',
@@ -11,6 +11,7 @@ export const listCustomers = createAction({
audience: 'both',
aiMetadata: { description: 'List customers from Lemon Squeezy, optionally narrowed by store (empty store spans all stores) and email address, with page-based pagination. Use to look up a customer by email or enumerate the customer base. Read-only and idempotent.', idempotent: true },
auth: lemonSqueezyAuth,
+ outputSchema: rawSchemas.customers,
props: {
storeId: Property.Dropdown({
displayName: 'Store',
@@ -18,13 +19,7 @@ export const listCustomers = createAction({
required: false,
auth: lemonSqueezyAuth,
refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchStoreOptions(auth.secret_text);
- return { options };
- },
+ options: async ({ auth }) => storeOptions({ auth }),
}),
email: Property.ShortText({
displayName: 'Email',
@@ -51,15 +46,13 @@ export const listCustomers = createAction({
if (propsValue.storeId) queryParams['filter[store_id]'] = propsValue.storeId;
if (propsValue.email) queryParams['filter[email]'] = propsValue.email;
- if (propsValue.page) queryParams['page[number]'] = String(propsValue.page);
- if (propsValue.perPage) queryParams['page[size]'] = String(propsValue.perPage);
-
- const url = `${LEMON_SQUEEZY_API_BASE}/customers${buildQueryString(queryParams)}`;
+ Object.assign(queryParams, pageParams(propsValue));
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url,
- headers: getLemonSqueezyHeaders(auth.secret_text),
+ const response = await lsRequest({
+ apiKey: auth.secret_text,
+ method: 'GET',
+ path: '/customers',
+ query: queryParams,
});
return response.body;
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-discount-redemptions.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-discount-redemptions.ts
new file mode 100644
index 00000000000..a96440d408e
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-discount-redemptions.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listDiscountRedemptions = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_discount_redemptions',
+ displayName: 'List Discount Redemptions',
+ description: 'List the orders that used a discount.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy discount redemptions (one per order that used a code, with the amount saved in cents), optionally filtered by discount ID or order ID, with page-based pagination. Use to measure how a promotion performed or to check which code an order used. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.discountRedemption, itemLabel: 'discount_code' }),
+ props: {
+ discountId: Property.ShortText({ displayName: 'Discount ID', description: 'Only redemptions of this discount.', required: false }),
+ orderId: Property.ShortText({ displayName: 'Order ID', description: 'Only redemptions on this order.', required: false }),
+ ...pageProps('redemptions'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/discount-redemptions',
+ query: {
+ 'filter[discount_id]': optionalId({ value: propsValue.discountId, label: 'Discount ID' }),
+ 'filter[order_id]': optionalId({ value: propsValue.orderId, label: 'Order ID' }),
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-discounts.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-discounts.ts
new file mode 100644
index 00000000000..e5bcd561d58
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-discounts.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps, storeDropdown } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listDiscounts = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_discounts',
+ displayName: 'List Discounts',
+ description: 'List discount codes.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy discount codes, optionally for one store, with page-based pagination. Use to check whether a code exists or find a discount ID to delete. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.discount, itemLabel: 'code' }),
+ props: {
+ storeId: storeDropdown({ required: false, description: 'Filter by store. Leave empty to include every store the API key can see.' }),
+ ...pageProps('discounts'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/discounts',
+ query: {
+ 'filter[store_id]': optionalId({ value: propsValue.storeId, label: 'Store' }),
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-license-key-instances.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-license-key-instances.ts
new file mode 100644
index 00000000000..2b3b0cd3dff
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-license-key-instances.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listLicenseKeyInstances = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_license_key_instances',
+ displayName: 'List License Key Activations',
+ description: 'List the activations (instances) of license keys.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists the activations (instances, for example a machine or site) of Lemon Squeezy license keys, optionally for one license key ID, with page-based pagination. Use to see where a customer activated a key before raising its activation limit or helping them free a slot. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.licenseKeyInstance, itemLabel: 'name' }),
+ props: {
+ licenseKeyId: Property.ShortText({
+ displayName: 'License Key ID',
+ description: 'Only activations of this license key.',
+ required: false,
+ }),
+ ...pageProps('activations'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/license-key-instances',
+ query: {
+ 'filter[license_key_id]': optionalId({ value: propsValue.licenseKeyId, label: 'License Key ID' }),
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-license-keys.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-license-keys.ts
new file mode 100644
index 00000000000..973b42fc1a1
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-license-keys.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps, storeDropdown } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listLicenseKeys = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_license_keys',
+ displayName: 'List License Keys',
+ description: 'List license keys, filtered by store, order or product.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy license keys (full key included), optionally filtered by store, order ID, order item ID or product ID, with page-based pagination. Use Get License Key to look up a single key string. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.licenseKey, itemLabel: 'key_short' }),
+ props: {
+ storeId: storeDropdown({ required: false, description: 'Filter by store. Leave empty to include every store the API key can see.' }),
+ orderId: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'Only keys from this order.',
+ required: false,
+ }),
+ orderItemId: Property.ShortText({
+ displayName: 'Order Item ID',
+ description: 'Only keys from this order item.',
+ required: false,
+ }),
+ productId: Property.ShortText({
+ displayName: 'Product ID',
+ description: 'Only keys for this product.',
+ required: false,
+ }),
+ ...pageProps('license keys'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/license-keys',
+ query: {
+ 'filter[store_id]': optionalId({ value: propsValue.storeId, label: 'Store' }),
+ 'filter[order_id]': optionalId({ value: propsValue.orderId, label: 'Order ID' }),
+ 'filter[order_item_id]': optionalId({ value: propsValue.orderItemId, label: 'Order Item ID' }),
+ 'filter[product_id]': optionalId({ value: propsValue.productId, label: 'Product ID' }),
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-order-items.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-order-items.ts
new file mode 100644
index 00000000000..75f452491bc
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-order-items.ts
@@ -0,0 +1,51 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listOrderItems = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_order_items',
+ displayName: 'List Order Items',
+ description: 'List order items, filtered by order, product or variant.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy order items (the product and variant lines of orders), optionally filtered by order ID, product ID or variant ID, with page-based pagination. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.orderItem, itemLabel: 'product_name' }),
+ props: {
+ orderId: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'Only items of this order.',
+ required: false,
+ }),
+ productId: Property.ShortText({
+ displayName: 'Product ID',
+ description: 'Only items of this product.',
+ required: false,
+ }),
+ variantId: Property.ShortText({
+ displayName: 'Variant ID',
+ description: 'Only items of this variant.',
+ required: false,
+ }),
+ ...pageProps('order items'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/order-items',
+ query: {
+ 'filter[order_id]': optionalId({ value: propsValue.orderId, label: 'Order ID' }),
+ 'filter[product_id]': optionalId({ value: propsValue.productId, label: 'Product ID' }),
+ 'filter[variant_id]': optionalId({ value: propsValue.variantId, label: 'Variant ID' }),
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-orders.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-orders.ts
index 7b31249bdf3..45381575a3e 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-orders.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-orders.ts
@@ -1,8 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { lemonSqueezyAuth } from '../common/auth';
-import { LEMON_SQUEEZY_API_BASE, getLemonSqueezyHeaders, buildQueryString, fetchStoreOptions } from '../common/api';
-
+import { lsRequest, pageParams } from '../common/client';
+import { storeOptions } from '../common/props';
+import { rawSchemas } from '../common/output-schemas';
export const listOrders = createAction({
name: 'list_orders',
classification: 'SEARCH',
@@ -11,6 +11,7 @@ export const listOrders = createAction({
audience: 'both',
aiMetadata: { description: 'List orders from Lemon Squeezy, optionally narrowed by store (empty store spans all stores), customer email, and order status (pending, paid, refunded, etc.), with page-based pagination. Use to find or audit orders by criteria; pair with Get Order for full detail on a single order. Read-only and idempotent.', idempotent: true },
auth: lemonSqueezyAuth,
+ outputSchema: rawSchemas.orders,
props: {
storeId: Property.Dropdown({
displayName: 'Store',
@@ -18,13 +19,7 @@ export const listOrders = createAction({
required: false,
auth: lemonSqueezyAuth,
refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchStoreOptions(auth.secret_text);
- return { options };
- },
+ options: async ({ auth }) => storeOptions({ auth }),
}),
userEmail: Property.ShortText({
displayName: 'Customer Email',
@@ -68,15 +63,13 @@ export const listOrders = createAction({
if (propsValue.storeId) queryParams['filter[store_id]'] = propsValue.storeId;
if (propsValue.userEmail) queryParams['filter[user_email]'] = propsValue.userEmail;
if (propsValue.status) queryParams['filter[status]'] = propsValue.status;
- if (propsValue.page) queryParams['page[number]'] = String(propsValue.page);
- if (propsValue.perPage) queryParams['page[size]'] = String(propsValue.perPage);
-
- const url = `${LEMON_SQUEEZY_API_BASE}/orders${buildQueryString(queryParams)}`;
+ Object.assign(queryParams, pageParams(propsValue));
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url,
- headers: getLemonSqueezyHeaders(auth.secret_text),
+ const response = await lsRequest({
+ apiKey: auth.secret_text,
+ method: 'GET',
+ path: '/orders',
+ query: queryParams,
});
return response.body;
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-products.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-products.ts
index 79c0b213f64..e82cc99d220 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-products.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-products.ts
@@ -1,8 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { lemonSqueezyAuth } from '../common/auth';
-import { LEMON_SQUEEZY_API_BASE, getLemonSqueezyHeaders, buildQueryString, fetchStoreOptions } from '../common/api';
-
+import { lsRequest, pageParams } from '../common/client';
+import { storeOptions } from '../common/props';
+import { rawSchemas } from '../common/output-schemas';
export const listProducts = createAction({
name: 'list_products',
classification: 'SEARCH',
@@ -11,6 +11,7 @@ export const listProducts = createAction({
audience: 'both',
aiMetadata: { description: 'List products from Lemon Squeezy, optionally scoped to one store (leave the store empty to span all stores) with page-based pagination. Use to enumerate a catalog or look up products before referencing a variant in a checkout. Read-only and idempotent.', idempotent: true },
auth: lemonSqueezyAuth,
+ outputSchema: rawSchemas.products,
props: {
storeId: Property.Dropdown({
displayName: 'Store',
@@ -18,13 +19,7 @@ export const listProducts = createAction({
required: false,
auth: lemonSqueezyAuth,
refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchStoreOptions(auth.secret_text);
- return { options };
- },
+ options: async ({ auth }) => storeOptions({ auth }),
}),
page: Property.Number({
displayName: 'Page',
@@ -45,15 +40,13 @@ export const listProducts = createAction({
const queryParams: Record<string, string> = {};
if (propsValue.storeId) queryParams['filter[store_id]'] = propsValue.storeId;
- if (propsValue.page) queryParams['page[number]'] = String(propsValue.page);
- if (propsValue.perPage) queryParams['page[size]'] = String(propsValue.perPage);
-
- const url = `${LEMON_SQUEEZY_API_BASE}/products${buildQueryString(queryParams)}`;
+ Object.assign(queryParams, pageParams(propsValue));
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url,
- headers: getLemonSqueezyHeaders(auth.secret_text),
+ const response = await lsRequest({
+ apiKey: auth.secret_text,
+ method: 'GET',
+ path: '/products',
+ query: queryParams,
});
return response.body;
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-stores.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-stores.ts
new file mode 100644
index 00000000000..870d1731b6c
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-stores.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, pageParams } from '../common/client';
+import { pageProps } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listStores = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_stores',
+ displayName: 'List Stores',
+ description: 'List the stores your API key can access.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists the Lemon Squeezy stores the connected API key can access, with page-based pagination. Use to find a store ID for other actions (create customer, create discount, create checkout). Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.store, itemLabel: 'name' }),
+ props: {
+ ...pageProps('stores'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({ apiKey: auth.secret_text, path: '/stores', query: pageParams(propsValue) });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscription-invoices.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscription-invoices.ts
new file mode 100644
index 00000000000..7625ed43602
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscription-invoices.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps, storeDropdown } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listSubscriptionInvoices = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_subscription_invoices',
+ displayName: 'List Subscription Invoices',
+ description: 'List subscription invoices (renewal payments).',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy subscription invoices (initial, renewal and plan-change payments), optionally filtered by store, subscription ID, status (paid, pending, void, refunded, partial_refund) or refunded flag, with page-based pagination. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.subscriptionInvoice, itemLabel: 'total_formatted' }),
+ props: {
+ storeId: storeDropdown({ required: false, description: 'Filter by store. Leave empty to include every store the API key can see.' }),
+ subscriptionId: Property.ShortText({
+ displayName: 'Subscription ID',
+ description: 'Only invoices of this subscription.',
+ required: false,
+ }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: {
+ options: [
+ { label: 'Paid', value: 'paid' },
+ { label: 'Pending', value: 'pending' },
+ { label: 'Void', value: 'void' },
+ { label: 'Refunded', value: 'refunded' },
+ { label: 'Partially Refunded', value: 'partial_refund' },
+ ],
+ },
+ }),
+ ...pageProps('invoices'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/subscription-invoices',
+ query: {
+ 'filter[store_id]': optionalId({ value: propsValue.storeId, label: 'Store' }),
+ 'filter[subscription_id]': optionalId({ value: propsValue.subscriptionId, label: 'Subscription ID' }),
+ 'filter[status]': propsValue.status ?? undefined,
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscription-items.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscription-items.ts
new file mode 100644
index 00000000000..def8b98e53b
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscription-items.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listSubscriptionItems = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_subscription_items',
+ displayName: 'List Subscription Items',
+ description: 'List the price items (quantity, usage-based) of subscriptions.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy subscription items (the price line of a subscription: price ID, quantity, whether it is usage-based), optionally filtered by subscription ID or price ID, with page-based pagination. Use to read a subscription\'s seat count or find the item ID that usage-based billing needs. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.subscriptionItem, itemLabel: 'id' }),
+ props: {
+ subscriptionId: Property.ShortText({ displayName: 'Subscription ID', description: 'Only items of this subscription.', required: false }),
+ priceId: Property.ShortText({ displayName: 'Price ID', description: 'Only items on this price.', required: false }),
+ ...pageProps('items'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/subscription-items',
+ query: {
+ 'filter[subscription_id]': optionalId({ value: propsValue.subscriptionId, label: 'Subscription ID' }),
+ 'filter[price_id]': optionalId({ value: propsValue.priceId, label: 'Price ID' }),
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscriptions-ai.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscriptions-ai.ts
new file mode 100644
index 00000000000..b9d68fbea3b
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscriptions-ai.ts
@@ -0,0 +1,81 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listSubscriptionsAi = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_subscriptions_ai',
+ displayName: 'List Subscriptions (AI)',
+ description: 'List subscriptions filtered by IDs, email or status.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy subscriptions filtered by any of: store ID, order ID, order item ID, product ID, variant ID, exact customer email, status (on_trial, active, paused, past_due, unpaid, cancelled, expired). Page-based; check has_more. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.subscription, itemLabel: 'user_email' }),
+ props: {
+ storeId: Property.ShortText({
+ displayName: 'Store ID',
+ description: 'Numeric store ID.',
+ required: false,
+ }),
+ orderId: Property.ShortText({
+ displayName: 'Order ID',
+ description: 'Numeric order ID.',
+ required: false,
+ }),
+ orderItemId: Property.ShortText({
+ displayName: 'Order Item ID',
+ description: 'Numeric order item ID.',
+ required: false,
+ }),
+ productId: Property.ShortText({
+ displayName: 'Product ID',
+ description: 'Numeric product ID.',
+ required: false,
+ }),
+ variantId: Property.ShortText({
+ displayName: 'Variant ID',
+ description: 'Numeric variant ID.',
+ required: false,
+ }),
+ userEmail: Property.ShortText({ displayName: 'Customer Email', description: 'Exact customer email address.', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: {
+ options: [
+ { label: 'On Trial', value: 'on_trial' },
+ { label: 'Active', value: 'active' },
+ { label: 'Paused', value: 'paused' },
+ { label: 'Past Due', value: 'past_due' },
+ { label: 'Unpaid', value: 'unpaid' },
+ { label: 'Cancelled', value: 'cancelled' },
+ { label: 'Expired', value: 'expired' },
+ ],
+ },
+ }),
+ ...pageProps('subscriptions'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/subscriptions',
+ query: {
+ 'filter[store_id]': optionalId({ value: propsValue.storeId, label: 'Store ID' }),
+ 'filter[order_id]': optionalId({ value: propsValue.orderId, label: 'Order ID' }),
+ 'filter[order_item_id]': optionalId({ value: propsValue.orderItemId, label: 'Order Item ID' }),
+ 'filter[product_id]': optionalId({ value: propsValue.productId, label: 'Product ID' }),
+ 'filter[variant_id]': optionalId({ value: propsValue.variantId, label: 'Variant ID' }),
+ 'filter[user_email]': propsValue.userEmail?.trim() || undefined,
+ 'filter[status]': propsValue.status ?? undefined,
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscriptions.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscriptions.ts
index 7469f1fa034..30068836b59 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscriptions.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-subscriptions.ts
@@ -1,24 +1,16 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { lemonSqueezyAuth } from '../common/auth';
-import {
- LEMON_SQUEEZY_API_BASE,
- getLemonSqueezyHeaders,
- buildQueryString,
- fetchStoreOptions,
- fetchOrderOptions,
- fetchProductOptions,
- fetchVariantOptions,
-} from '../common/api';
-
+import { lsRequest, pageParams, seg } from '../common/client';
+import { storeOptions, orderOptions, productOptions, variantOptions } from '../common/props';
+import { rawSchemas } from '../common/output-schemas';
export const listSubscriptions = createAction({
name: 'list_subscriptions',
classification: 'SEARCH',
displayName: 'List Subscriptions',
description: 'Retrieve a paginated list of subscriptions from your Lemon Squeezy store.',
- audience: 'both',
- aiMetadata: { description: 'List subscriptions from Lemon Squeezy, optionally filtered by store, order, order item, product, variant, customer email, and status (active, on_trial, cancelled, expired, etc.), with page-based pagination. Use to find subscriptions matching criteria or to audit a customer\'s subscriptions. Read-only and idempotent.', idempotent: true },
+ audience: 'human',
auth: lemonSqueezyAuth,
+ outputSchema: rawSchemas.subscriptions,
props: {
storeId: Property.Dropdown({
displayName: 'Store',
@@ -26,13 +18,7 @@ export const listSubscriptions = createAction({
required: false,
auth: lemonSqueezyAuth,
refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchStoreOptions(auth.secret_text);
- return { options };
- },
+ options: async ({ auth }) => storeOptions({ auth }),
}),
orderId: Property.Dropdown({
displayName: 'Order',
@@ -40,13 +26,7 @@ export const listSubscriptions = createAction({
required: false,
auth: lemonSqueezyAuth,
refreshers: ['auth', 'storeId'],
- options: async ({ auth, storeId }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchOrderOptions(auth.secret_text, storeId as string | undefined);
- return { options };
- },
+ options: async ({ auth, storeId }) => orderOptions({ auth, storeId }),
}),
orderItemId: Property.ShortText({
displayName: 'Order Item ID',
@@ -59,13 +39,7 @@ export const listSubscriptions = createAction({
required: false,
auth: lemonSqueezyAuth,
refreshers: ['auth', 'storeId'],
- options: async ({ auth, storeId }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchProductOptions(auth.secret_text, storeId as string | undefined);
- return { options };
- },
+ options: async ({ auth, storeId }) => productOptions({ auth, storeId }),
}),
variantId: Property.Dropdown({
displayName: 'Variant',
@@ -73,13 +47,7 @@ export const listSubscriptions = createAction({
required: false,
auth: lemonSqueezyAuth,
refreshers: ['auth', 'productId'],
- options: async ({ auth, productId }) => {
- if (!auth) {
- return { disabled: true, placeholder: 'Connect your account first.', options: [] };
- }
- const options = await fetchVariantOptions(auth.secret_text, productId as string | undefined);
- return { options };
- },
+ options: async ({ auth, productId }) => variantOptions({ auth, productId }),
}),
userEmail: Property.ShortText({
displayName: 'Customer Email',
@@ -123,20 +91,18 @@ export const listSubscriptions = createAction({
if (propsValue.storeId) queryParams['filter[store_id]'] = propsValue.storeId;
if (propsValue.orderId) queryParams['filter[order_id]'] = propsValue.orderId;
- if (propsValue.orderItemId) queryParams['filter[order_item_id]'] = propsValue.orderItemId;
+ if (propsValue.orderItemId) queryParams['filter[order_item_id]'] = seg({ value: propsValue.orderItemId, label: 'Order Item ID' });
if (propsValue.productId) queryParams['filter[product_id]'] = propsValue.productId;
if (propsValue.variantId) queryParams['filter[variant_id]'] = propsValue.variantId;
if (propsValue.userEmail) queryParams['filter[user_email]'] = propsValue.userEmail;
if (propsValue.status) queryParams['filter[status]'] = propsValue.status;
- if (propsValue.page) queryParams['page[number]'] = String(propsValue.page);
- if (propsValue.perPage) queryParams['page[size]'] = String(propsValue.perPage);
-
- const url = `${LEMON_SQUEEZY_API_BASE}/subscriptions${buildQueryString(queryParams)}`;
+ Object.assign(queryParams, pageParams(propsValue));
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url,
- headers: getLemonSqueezyHeaders(auth.secret_text),
+ const response = await lsRequest({
+ apiKey: auth.secret_text,
+ method: 'GET',
+ path: '/subscriptions',
+ query: queryParams,
});
return response.body;
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/list-variants.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-variants.ts
new file mode 100644
index 00000000000..c2b11e89f58
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/list-variants.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { listRecords, optionalId, pageParams } from '../common/client';
+import { pageProps } from '../common/props';
+import { flatFields, listSchema } from '../common/output-schemas';
+
+export const listVariants = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'list_variants',
+ displayName: 'List Variants',
+ description: 'List product variants, optionally for one product.',
+ audience: 'both',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists Lemon Squeezy product variants (the purchasable price options), optionally for one product ID and status, with page-based pagination. Use to find a variant ID for checkouts or plan changes. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listSchema({ fields: flatFields.variant, itemLabel: 'name' }),
+ props: {
+ productId: Property.ShortText({
+ displayName: 'Product ID',
+ description: 'Only variants of this product.',
+ required: false,
+ }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: { options: [{ label: 'Published', value: 'published' }, { label: 'Draft', value: 'draft' }, { label: 'Pending', value: 'pending' }] },
+ }),
+ ...pageProps('variants'),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ return listRecords({
+ apiKey: auth.secret_text,
+ path: '/variants',
+ query: {
+ 'filter[product_id]': optionalId({ value: propsValue.productId, label: 'Product ID' }),
+ 'filter[status]': propsValue.status ?? undefined,
+ ...pageParams(propsValue),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/pause-subscription.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/pause-subscription.ts
new file mode 100644
index 00000000000..21195c280a3
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/pause-subscription.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { isoDateOrUndefined, numericId, patchRecord, seg } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const pauseSubscription = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'pause_subscription',
+ displayName: 'Pause Subscription',
+ description: 'Pause payment collection for a subscription.',
+ audience: 'both',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Pauses payment collection on a Lemon Squeezy subscription. Mode "void" stops access while paused; mode "free" keeps access for free. Optional resume date (ISO 8601); without it the pause lasts until Unpause Subscription. Idempotent.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.subscription),
+ props: {
+ subscriptionId: Property.ShortText({
+ displayName: 'Subscription ID',
+ description: 'The numeric ID of the subscription.',
+ required: true,
+ }),
+ mode: Property.StaticDropdown({
+ displayName: 'Pause Mode',
+ description: 'Void stops access while paused; Free keeps access without paying.',
+ required: true,
+ defaultValue: 'void',
+ options: { options: [{ label: 'Void (no access)', value: 'void' }, { label: 'Free (keep access)', value: 'free' }] },
+ }),
+ resumesAt: Property.ShortText({
+ displayName: 'Resumes At',
+ description: 'Auto-resume date (ISO 8601). Empty keeps it paused until unpaused.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ if (propsValue.mode !== 'void' && propsValue.mode !== 'free') throw new Error('Pause Mode must be "void" or "free".');
+ const resumesAt = isoDateOrUndefined({ value: propsValue.resumesAt, label: 'Resumes At' });
+ const id = numericId({ value: propsValue.subscriptionId, label: 'Subscription ID' });
+ return patchRecord({ apiKey: auth.secret_text, type: 'subscriptions', path: `/subscriptions/${seg({ value: id, label: 'Subscription ID' })}`, id: id, attributes: { pause: { mode: propsValue.mode, resumes_at: resumesAt ?? null } } });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/resume-subscription.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/resume-subscription.ts
new file mode 100644
index 00000000000..fad0a73e748
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/resume-subscription.ts
@@ -0,0 +1,31 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { numericId, patchRecord, seg } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const resumeSubscription = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'resume_subscription',
+ displayName: 'Resume Subscription',
+ description: 'Undo a cancellation during the grace period.',
+ audience: 'both',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Resumes a cancelled Lemon Squeezy subscription that is still in its grace period (status cancelled, ends_at in the future), so it renews again. Expired subscriptions cannot be resumed. Idempotent.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.subscription),
+ props: {
+ subscriptionId: Property.ShortText({
+ displayName: 'Subscription ID',
+ description: 'The numeric ID of the subscription.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const id = numericId({ value: propsValue.subscriptionId, label: 'Subscription ID' });
+ return patchRecord({ apiKey: auth.secret_text, type: 'subscriptions', path: `/subscriptions/${seg({ value: id, label: 'Subscription ID' })}`, id: id, attributes: { cancelled: false } });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/unpause-subscription.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/unpause-subscription.ts
new file mode 100644
index 00000000000..5aeb4b50997
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/unpause-subscription.ts
@@ -0,0 +1,31 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { numericId, patchRecord, seg } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const unpauseSubscription = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'unpause_subscription',
+ displayName: 'Unpause Subscription',
+ description: 'Resume payment collection on a paused subscription.',
+ audience: 'both',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Ends the pause on a paused Lemon Squeezy subscription so payment collection restarts. Idempotent: unpausing a subscription that is not paused changes nothing.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.subscription),
+ props: {
+ subscriptionId: Property.ShortText({
+ displayName: 'Subscription ID',
+ description: 'The numeric ID of the subscription.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const id = numericId({ value: propsValue.subscriptionId, label: 'Subscription ID' });
+ return patchRecord({ apiKey: auth.secret_text, type: 'subscriptions', path: `/subscriptions/${seg({ value: id, label: 'Subscription ID' })}`, id: id, attributes: { pause: null } });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/update-customer.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/update-customer.ts
new file mode 100644
index 00000000000..160236218ac
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/update-customer.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { numericId, patchRecord, seg } from '../common/client';
+import { countryCode } from '../common/validation';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const updateCustomer = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'update_customer',
+ displayName: 'Update Customer',
+ description: "Update a customer's details or archive the customer.",
+ audience: 'both',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Updates a Lemon Squeezy customer by ID: name, email, city, region, country (2-letter code), or archives the customer. Only the fields you provide change; at least one is required. Idempotent: repeating the same update leaves the customer unchanged.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.customer),
+ props: {
+ customerId: Property.ShortText({
+ displayName: 'Customer ID',
+ description: 'The numeric ID of the customer.',
+ required: true,
+ }),
+ name: Property.ShortText({ displayName: 'Name', description: 'The customer\'s full name.', required: false }),
+ email: Property.ShortText({ displayName: 'Email', description: 'The customer\'s email address.', required: false }),
+ city: Property.ShortText({ displayName: 'City', required: false }),
+ region: Property.ShortText({ displayName: 'Region', description: 'State, county or region.', required: false }),
+ country: Property.ShortText({ displayName: 'Country', description: 'ISO 3166-1 alpha-2 country code, for example US or DE.', required: false }),
+ archive: Property.Checkbox({
+ displayName: 'Archive Customer',
+ description: 'Archive the customer (it can be restored in the dashboard).',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const id = numericId({ value: propsValue.customerId, label: 'Customer ID' });
+ const attributes: Record<string, unknown> = {};
+ if (propsValue.name) attributes['name'] = propsValue.name;
+ if (propsValue.email) attributes['email'] = propsValue.email;
+ if (propsValue.city) attributes['city'] = propsValue.city;
+ if (propsValue.region) attributes['region'] = propsValue.region;
+ if (propsValue.country) attributes['country'] = countryCode(propsValue.country);
+ if (propsValue.archive === true) attributes['status'] = 'archived';
+ if (Object.keys(attributes).length === 0) {
+ throw new Error('Nothing to update: provide at least one field or tick Archive Customer.');
+ }
+ return patchRecord({ apiKey: auth.secret_text, type: 'customers', path: `/customers/${seg({ value: id, label: 'Customer ID' })}`, id: id, attributes: attributes });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/update-license-key.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/update-license-key.ts
new file mode 100644
index 00000000000..e96edf91dc3
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/update-license-key.ts
@@ -0,0 +1,57 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { isoDateOrUndefined, numericId, patchRecord, seg } from '../common/client';
+import { flatFields, recordSchema } from '../common/output-schemas';
+
+export const updateLicenseKey = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'update_license_key',
+ displayName: 'Update License Key',
+ description: "Change a license key's activation limit, expiry or disabled state.",
+ audience: 'both',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Updates a Lemon Squeezy license key by numeric ID: activation limit (or unlimited), expiry date (ISO 8601, or never), and enable/disable. Only the fields you set change; at least one is required. Disabling blocks activation and validation of the key. Idempotent.',
+ idempotent: true,
+ },
+ outputSchema: recordSchema(flatFields.licenseKey),
+ props: {
+ licenseKeyId: Property.ShortText({
+ displayName: 'License Key ID',
+ description: 'The numeric ID of the license key.',
+ required: true,
+ }),
+ activationLimit: Property.Number({ displayName: 'Activation Limit', description: 'New maximum number of activations.', required: false }),
+ unlimitedActivations: Property.Checkbox({ displayName: 'Unlimited Activations', description: 'Remove the activation limit.', required: false, defaultValue: false }),
+ expiresAt: Property.ShortText({ displayName: 'Expires At', description: 'New ISO 8601 expiry date-time, for example 2027-01-31T00:00:00Z.', required: false }),
+ neverExpires: Property.Checkbox({ displayName: 'Never Expires', description: 'Remove the expiry date.', required: false, defaultValue: false }),
+ disabled: Property.StaticDropdown({
+ displayName: 'Status',
+ description: 'Leave empty to keep the current state.',
+ required: false,
+ options: { options: [{ label: 'Disable key', value: 'disable' }, { label: 'Enable key', value: 'enable' }] },
+ }),
+ },
+ async run(context) {
+ const { auth, propsValue } = context;
+ const id = numericId({ value: propsValue.licenseKeyId, label: 'License Key ID' });
+ const attributes: Record<string, unknown> = {};
+ const hasLimit = propsValue.activationLimit !== undefined && propsValue.activationLimit !== null;
+ if (hasLimit && propsValue.unlimitedActivations) throw new Error('Set either Activation Limit or Unlimited Activations, not both.');
+ if (hasLimit) {
+ const limit = Number(propsValue.activationLimit);
+ if (!Number.isInteger(limit) || limit < 1) throw new Error('Activation Limit must be a whole number of 1 or more.');
+ attributes['activation_limit'] = limit;
+ }
+ if (propsValue.unlimitedActivations) attributes['activation_limit'] = null;
+ const expiresAt = isoDateOrUndefined({ value: propsValue.expiresAt, label: 'Expires At' });
+ if (expiresAt && propsValue.neverExpires) throw new Error('Set either Expires At or Never Expires, not both.');
+ if (expiresAt) attributes['expires_at'] = expiresAt;
+ if (propsValue.neverExpires) attributes['expires_at'] = null;
+ if (propsValue.disabled === 'disable') attributes['disabled'] = true;
+ if (propsValue.disabled === 'enable') attributes['disabled'] = false;
+ if (Object.keys(attributes).length === 0) throw new Error('Nothing to update: set at least one field.');
+ return patchRecord({ apiKey: auth.secret_text, type: 'license-keys', path: `/license-keys/${seg({ value: id, label: 'License Key ID' })}`, id: id, attributes: attributes });
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/actions/validate-license.ts b/packages/pieces/community/lemon-squeezy/src/lib/actions/validate-license.ts
new file mode 100644
index 00000000000..e119a82c126
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/actions/validate-license.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from '../common/auth';
+import { isRecord, readPath, validateLicenseKey } from '../common/client';
+import { validateLicenseSchema } from '../common/output-schemas';
+
+export const validateLicense = createAction({
+ auth: lemonSqueezyAuth,
+ name: 'validate_license',
+ displayName: 'Validate License Key',
+ description: 'Check whether a license key is valid, without activating it.',
+ audience: 'both',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Checks a Lemon Squeezy license key string (and optionally one activation instance ID) with the License API and returns valid true/false, the reason when invalid, its status, activation limit and usage, expiry, and the product and customer it belongs to. Does not activate the key or use up an activation, and the key itself is not returned. Use when a customer sends a key and you need to confirm it before granting access or support. Idempotent.',
+ idempotent: true,
+ },
+ outputSchema: validateLicenseSchema,
+ props: {
+ licenseKey: Property.ShortText({ displayName: 'License Key', description: 'The full license key to check.', required: true }),
+ instanceId: Property.ShortText({
+ displayName: 'Instance ID',
+ description: 'Also check this activation (instance) of the key.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { propsValue } = context;
+ const licenseKey = propsValue.licenseKey.trim();
+ if (!licenseKey) throw new Error('License Key is required.');
+ const instanceId = propsValue.instanceId?.trim() || undefined;
+ const body = await validateLicenseKey({ licenseKey, instanceId });
+ const key = readPath({ value: body, path: ['license_key'] });
+ const error = readPath({ value: body, path: ['error'] });
+ const instance = readPath({ value: body, path: ['instance'] });
+ const meta = readPath({ value: body, path: ['meta'] });
+ return {
+ valid: readPath({ value: body, path: ['valid'] }) === true,
+ error: typeof error === 'string' ? error : null,
+ license_key: isRecord(key)
+ ? {
+ id: key['id'] ?? null,
+ status: key['status'] ?? null,
+ activation_limit: key['activation_limit'] ?? null,
+ activation_usage: key['activation_usage'] ?? null,
+ expires_at: key['expires_at'] ?? null,
+ created_at: key['created_at'] ?? null,
+ test_mode: key['test_mode'] ?? null,
+ }
+ : null,
+ instance: isRecord(instance) ? instance : null,
+ meta: isRecord(meta) ? meta : null,
+ };
+ },
+});
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/common/api.ts b/packages/pieces/community/lemon-squeezy/src/lib/common/api.ts
deleted file mode 100644
index 74c5ef86287..00000000000
--- a/packages/pieces/community/lemon-squeezy/src/lib/common/api.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-
-export const LEMON_SQUEEZY_API_BASE = 'https://api.lemonsqueezy.com/v1';
-
-export function getLemonSqueezyHeaders(apiKey: string): Record<string, string> {
- return {
- Authorization: `Bearer ${apiKey}`,
- Accept: 'application/vnd.api+json',
- 'Content-Type': 'application/vnd.api+json',
- };
-}
-
-/**
- * Builds a query string that preserves bracket characters in parameter names.
- * URLSearchParams percent-encodes brackets (e.g. filter[store_id] becomes
- * filter%5Bstore_id%5D), which some JSON:API servers reject.
- */
-export function buildQueryString(params: Record<string, string>): string {
- const parts: string[] = [];
- for (const [key, value] of Object.entries(params)) {
- parts.push(`${key}=${encodeURIComponent(value)}`);
- }
- return parts.length > 0 ? `?${parts.join('&')}` : '';
-}
-
-export async function fetchStoreOptions(apiKey: string): Promise<{ label: string; value: string }[]> {
- const response = await httpClient.sendRequest<{ data: { id: string; attributes: { name: string } }[] }>({
- method: HttpMethod.GET,
- url: `${LEMON_SQUEEZY_API_BASE}/stores?page[size]=100`,
- headers: getLemonSqueezyHeaders(apiKey),
- });
- return response.body.data.map((store) => ({
- label: store.attributes.name,
- value: store.id,
- }));
-}
-
-export async function fetchOrderOptions(
- apiKey: string,
- storeId?: string,
-): Promise<{ label: string; value: string }[]> {
- const params: Record<string, string> = { 'page[size]': '100' };
- if (storeId) params['filter[store_id]'] = storeId;
- const response = await httpClient.sendRequest<{
- data: { id: string; attributes: { order_number: number; user_name: string; status_formatted: string } }[];
- }>({
- method: HttpMethod.GET,
- url: `${LEMON_SQUEEZY_API_BASE}/orders${buildQueryString(params)}`,
- headers: getLemonSqueezyHeaders(apiKey),
- });
- return response.body.data.map((order) => ({
- label: `#${order.attributes.order_number} — ${order.attributes.user_name} (${order.attributes.status_formatted})`,
- value: order.id,
- }));
-}
-
-export async function fetchProductOptions(
- apiKey: string,
- storeId?: string,
-): Promise<{ label: string; value: string }[]> {
- const params: Record<string, string> = { 'page[size]': '100' };
- if (storeId) params['filter[store_id]'] = storeId;
- const response = await httpClient.sendRequest<{
- data: { id: string; attributes: { name: string } }[];
- }>({
- method: HttpMethod.GET,
- url: `${LEMON_SQUEEZY_API_BASE}/products${buildQueryString(params)}`,
- headers: getLemonSqueezyHeaders(apiKey),
- });
- return response.body.data.map((product) => ({
- label: product.attributes.name,
- value: product.id,
- }));
-}
-
-export async function fetchVariantOptions(
- apiKey: string,
- productId?: string,
-): Promise<{ label: string; value: string }[]> {
- const params: Record<string, string> = { 'page[size]': '100' };
- if (productId) params['filter[product_id]'] = productId;
- const response = await httpClient.sendRequest<{
- data: { id: string; attributes: { name: string } }[];
- }>({
- method: HttpMethod.GET,
- url: `${LEMON_SQUEEZY_API_BASE}/variants${buildQueryString(params)}`,
- headers: getLemonSqueezyHeaders(apiKey),
- });
- return response.body.data.map((variant) => ({
- label: variant.attributes.name,
- value: variant.id,
- }));
-}
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/common/auth.ts b/packages/pieces/community/lemon-squeezy/src/lib/common/auth.ts
index f8187d9d7b3..83b4967c8d1 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/common/auth.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/common/auth.ts
@@ -1,6 +1,5 @@
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
import { PieceAuth } from '@activepieces/pieces-framework';
-import { LEMON_SQUEEZY_API_BASE } from './api';
+import { LemonSqueezyApiError, RATE_LIMIT_WAITS, lsRequest } from './client';
export const lemonSqueezyAuth = PieceAuth.SecretText({
displayName: 'API Key',
@@ -11,41 +10,24 @@ To get your API Key:
2. Navigate to Settings » API
3. Create a new API key
4. Copy the API key and paste it here
+
+Keys created in test mode only see test-mode data, and webhooks for this connection are created in the same mode.
`,
required: true,
validate: async ({ auth }) => {
- if (!auth) {
- return {
- valid: false,
- error: 'API key is required',
- };
+ if (!auth || !auth.trim()) {
+ return { valid: false, error: 'API key is required' };
}
-
try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `${LEMON_SQUEEZY_API_BASE}/stores`,
- headers: {
- Authorization: `Bearer ${auth}`,
- 'Accept': 'application/vnd.api+json',
- 'Content-Type': 'application/vnd.api+json',
- },
- });
-
- if (response.status === 200) {
- return {
- valid: true,
- };
+ await lsRequest({ apiKey: auth, method: 'GET', path: '/users/me', rateLimitWaitsMs: RATE_LIMIT_WAITS.interactive });
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof LemonSqueezyApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: 'Invalid API key. Please check your API key and try again.' };
}
-
- return {
- valid: false,
- error: 'Invalid API key',
- };
- } catch (error: any) {
return {
valid: false,
- error: 'Invalid API key. Please check your API key and try again.',
+ error: `Could not reach Lemon Squeezy to check the key: ${error instanceof Error ? error.message : String(error)}`,
};
}
},
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/common/client.ts b/packages/pieces/community/lemon-squeezy/src/lib/common/client.ts
new file mode 100644
index 00000000000..703d4363f0d
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/common/client.ts
@@ -0,0 +1,342 @@
+import { HttpMethod, HttpRequest, httpClient } from '@activepieces/pieces-common';
+
+export const LEMON_SQUEEZY_API_BASE = 'https://api.lemonsqueezy.com/v1';
+
+export const MAX_DROPDOWN_PAGES = 10;
+
+export class LemonSqueezyApiError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number,
+ public readonly responseBody?: unknown,
+ ) {
+ super(message);
+ this.name = 'LemonSqueezyApiError';
+ }
+}
+
+export function getLemonSqueezyHeaders(apiKey: string): Record<string, string> {
+ return {
+ Authorization: `Bearer ${apiKey.trim()}`,
+ Accept: 'application/vnd.api+json',
+ 'Content-Type': 'application/vnd.api+json',
+ };
+}
+
+export function numericId({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (!/^[1-9]\d{0,18}$/.test(text)) {
+ throw new Error(`${label} must be a numeric Lemon Squeezy ID (for example 12345), got "${String(value ?? '')}".`);
+ }
+ return text;
+}
+
+export function seg({ value, label }: { value: unknown; label: string }): string {
+ return encodeURIComponent(numericId({ value, label }));
+}
+
+export function optionalId({ value, label }: { value: unknown; label: string }): string | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ return numericId({ value, label });
+}
+
+export function isoDateOrUndefined({ value, label }: { value: unknown; label: string }): string | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const text = String(value).trim();
+ if (!/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/.test(text) || Number.isNaN(Date.parse(text))) {
+ throw new Error(`${label} must be an ISO 8601 date or date-time, for example 2026-12-31T23:59:59Z.`);
+ }
+ return new Date(text).toISOString();
+}
+
+export function buildQueryString(params: Record<string, string | undefined>): string {
+ const parts: string[] = [];
+ for (const [key, value] of Object.entries(params)) {
+ if (value === undefined || value === '') continue;
+ parts.push(`${key}=${encodeURIComponent(value)}`);
+ }
+ return parts.length > 0 ? `?${parts.join('&')}` : '';
+}
+
+export function pageParams({ page, perPage }: { page?: unknown; perPage?: unknown }): Record<string, string> {
+ const params: Record<string, string> = {};
+ if (page !== undefined && page !== null && page !== '') {
+ const n = Number(page);
+ if (!Number.isInteger(n) || n < 1) throw new Error('Page must be a whole number of 1 or more.');
+ params['page[number]'] = String(n);
+ }
+ if (perPage !== undefined && perPage !== null && perPage !== '') {
+ const n = Number(perPage);
+ if (!Number.isInteger(n) || n < 1 || n > 100) throw new Error('Per Page must be a whole number between 1 and 100.');
+ params['page[size]'] = String(n);
+ }
+ return params;
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+export function readPath({ value, path }: { value: unknown; path: string[] }): unknown {
+ let current: unknown = value;
+ for (const key of path) {
+ if (!isRecord(current)) return undefined;
+ current = current[key];
+ }
+ return current;
+}
+
+export async function lsRequest({
+ apiKey,
+ method,
+ path,
+ query,
+ body,
+ rateLimitWaitsMs = RATE_LIMIT_WAITS.action,
+}: {
+ apiKey: string;
+ method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
+ path: string;
+ query?: Record<string, string | undefined>;
+ body?: unknown;
+ rateLimitWaitsMs?: readonly number[];
+}): Promise<{ status: number; body: unknown }> {
+ if (!path.startsWith('/') || path.startsWith('//') || path.includes('..')) {
+ throw new Error(`Invalid Lemon Squeezy API path: ${path}`);
+ }
+ const url = `${LEMON_SQUEEZY_API_BASE}${path}${buildQueryString(query ?? {})}`;
+ for (let attempt = 0; ; attempt++) {
+ const response = await send({
+ method: HttpMethod[method],
+ url,
+ headers: getLemonSqueezyHeaders(apiKey),
+ body,
+ redactBodyInErrors: body !== undefined,
+ });
+ const wait = rateLimitWaitsMs[attempt];
+ if (response.status === 429 && wait !== undefined) {
+ await sleep(wait);
+ continue;
+ }
+ if (response.status >= 300 && response.status < 400) {
+ throw new LemonSqueezyApiError(`Lemon Squeezy answered with an unexpected redirect (${response.status}).`, response.status);
+ }
+ if (response.status < 200 || response.status >= 400) {
+ throw new LemonSqueezyApiError(messageForStatus({ status: response.status, detail: errorDetail(response.body) }), response.status, response.body);
+ }
+ return { status: response.status, body: response.body };
+ }
+}
+
+export function toResource(value: unknown): JsonApiResource {
+ if (!isRecord(value) || (typeof value['id'] !== 'string' && typeof value['id'] !== 'number')) {
+ throw new Error('Lemon Squeezy returned an unexpected response (no record).');
+ }
+ return {
+ id: String(value['id']),
+ type: typeof value['type'] === 'string' ? value['type'] : '',
+ attributes: isRecord(value['attributes']) ? value['attributes'] : {},
+ };
+}
+
+export function flatten(resource: JsonApiResource): Record<string, unknown> & { id: string } {
+ return { ...resource.attributes, id: resource.id };
+}
+
+export function flattenList(body: unknown) {
+ const data = readPath({ value: body, path: ['data'] });
+ const page = readPath({ value: body, path: ['meta', 'page'] });
+ const num = (key: string) => {
+ const value = readPath({ value: page, path: [key] });
+ return typeof value === 'number' ? value : undefined;
+ };
+ const currentPage = num('currentPage') ?? 1;
+ const lastPage = num('lastPage') ?? currentPage;
+ return {
+ items: (Array.isArray(data) ? data : []).map((item) => flatten(toResource(item))),
+ page: currentPage,
+ last_page: lastPage,
+ per_page: num('perPage') ?? null,
+ total: num('total') ?? null,
+ has_more: currentPage < lastPage,
+ };
+}
+
+export async function getRecord({ apiKey, path, query }: { apiKey: string; path: string; query?: Record<string, string | undefined> }) {
+ const { body } = await lsRequest({ apiKey, method: 'GET', path, query });
+ return flatten(toResource(readPath({ value: body, path: ['data'] })));
+}
+
+export async function listRecords({ apiKey, path, query }: { apiKey: string; path: string; query: Record<string, string | undefined> }) {
+ const { body } = await lsRequest({ apiKey, method: 'GET', path, query });
+ return flattenList(body);
+}
+
+export async function createRecord({
+ apiKey,
+ path,
+ type,
+ attributes,
+ relationships,
+}: {
+ apiKey: string;
+ path: string;
+ type: string;
+ attributes: Record<string, unknown>;
+ relationships: Record<string, { data: { type: string; id: string } }>;
+}) {
+ const { body } = await lsRequest({ apiKey, method: 'POST', path, body: { data: { type, attributes, relationships } } });
+ return flatten(toResource(readPath({ value: body, path: ['data'] })));
+}
+
+export async function patchRecord({
+ apiKey,
+ type,
+ path,
+ id,
+ attributes,
+}: {
+ apiKey: string;
+ type: string;
+ path: string;
+ id: string;
+ attributes: Record<string, unknown>;
+}) {
+ const { body } = await lsRequest({ apiKey, method: 'PATCH', path, body: { data: { type, id, attributes } } });
+ return flatten(toResource(readPath({ value: body, path: ['data'] })));
+}
+
+export async function deleteRecord({ apiKey, path }: { apiKey: string; path: string }) {
+ const { body } = await lsRequest({ apiKey, method: 'DELETE', path });
+ return body;
+}
+
+export async function listAllPages({
+ apiKey,
+ path,
+ query,
+ maxPages = MAX_DROPDOWN_PAGES,
+}: {
+ apiKey: string;
+ path: string;
+ query?: Record<string, string | undefined>;
+ maxPages?: number;
+}): Promise<{ items: JsonApiResource[]; truncated: boolean }> {
+ const items: JsonApiResource[] = [];
+ for (let pageNumber = 1; pageNumber <= maxPages; pageNumber++) {
+ const { body } = await lsRequest({
+ apiKey,
+ method: 'GET',
+ path,
+ query: { ...query, 'page[number]': String(pageNumber), 'page[size]': '100' },
+ rateLimitWaitsMs: RATE_LIMIT_WAITS.interactive,
+ });
+ const data = readPath({ value: body, path: ['data'] });
+ for (const item of Array.isArray(data) ? data : []) items.push(toResource(item));
+ const lastPage = readPath({ value: body, path: ['meta', 'page', 'lastPage'] });
+ if (pageNumber >= (typeof lastPage === 'number' ? lastPage : pageNumber)) return { items, truncated: false };
+ }
+ return { items, truncated: true };
+}
+
+export async function getTestModeForKey(apiKey: string): Promise<boolean> {
+ const { body } = await lsRequest({ apiKey, method: 'GET', path: '/users/me', rateLimitWaitsMs: RATE_LIMIT_WAITS.interactive });
+ return readPath({ value: body, path: ['meta', 'test_mode'] }) === true;
+}
+
+export async function validateLicenseKey({ licenseKey, instanceId }: { licenseKey: string; instanceId?: string }) {
+ const form = new URLSearchParams({ license_key: licenseKey });
+ if (instanceId) form.set('instance_id', instanceId);
+ const response = await send({
+ method: HttpMethod.POST,
+ url: `${LEMON_SQUEEZY_API_BASE}/licenses/validate`,
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: form.toString(),
+ redactBodyInErrors: true,
+ });
+ if (response.status !== 200 && response.status !== 400 && response.status !== 404 && response.status !== 422) {
+ const error = readPath({ value: response.body, path: ['error'] });
+ throw new LemonSqueezyApiError(
+ messageForStatus({ status: response.status, detail: typeof error === 'string' ? error : undefined }),
+ response.status,
+ undefined,
+ );
+ }
+ return response.body;
+}
+
+export async function lookupLicenseKeyId(licenseKey: string): Promise<string | undefined> {
+ const body = await validateLicenseKey({ licenseKey });
+ const id = readPath({ value: body, path: ['license_key', 'id'] });
+ return typeof id === 'number' || typeof id === 'string' ? String(id) : undefined;
+}
+
+const REQUEST_TIMEOUT_MS = 30_000;
+
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+function errorDetail(body: unknown): string | undefined {
+ const errors = readPath({ value: body, path: ['errors'] });
+ if (!Array.isArray(errors)) return undefined;
+ const details = errors
+ .map((e) => {
+ const detail = readPath({ value: e, path: ['detail'] });
+ const title = readPath({ value: e, path: ['title'] });
+ return typeof detail === 'string' ? detail : typeof title === 'string' ? title : undefined;
+ })
+ .filter((d): d is string => !!d);
+ return details.length > 0 ? details.join('; ') : undefined;
+}
+
+function messageForStatus({ status, detail }: { status: number; detail: string | undefined }): string {
+ const suffix = detail ? `: ${detail}` : '';
+ switch (status) {
+ case 401:
+ return `Lemon Squeezy rejected the API key (401). Check that the key is valid and not revoked${suffix}`;
+ case 403:
+ return `The API key is not allowed to do this (403)${suffix}`;
+ case 404:
+ return `Lemon Squeezy could not find that record (404)${suffix}`;
+ case 422:
+ return `Lemon Squeezy rejected the request (422)${suffix}`;
+ case 429:
+ return `Lemon Squeezy rate limit reached (429). Try again in a minute${suffix}`;
+ default:
+ return `Lemon Squeezy API error (${status})${suffix}`;
+ }
+}
+
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function failureOf(error: unknown): RawResponse | null {
+ const status = readPath({ value: error, path: ['response', 'status'] });
+ return typeof status === 'number' ? { status, body: readPath({ value: error, path: ['response', 'body'] }) } : null;
+}
+
+async function send(request: HttpRequest): Promise<RawResponse> {
+ const dispatcher = await verifiedTls();
+ try {
+ const response = await httpClient.sendRequest(
+ { ...request, timeout: REQUEST_TIMEOUT_MS, followRedirects: false, responseType: 'json' },
+ { dispatcher },
+ );
+ return { status: response.status, body: response.body };
+ } catch (error) {
+ const failure = failureOf(error);
+ if (failure) return failure;
+ throw error;
+ }
+}
+
+export const RATE_LIMIT_WAITS: { action: readonly number[]; interactive: readonly number[] } = { action: [20_000, 40_000], interactive: [] };
+
+export type JsonApiResource = { id: string; type: string; attributes: Record<string, unknown> };
+
+type RawResponse = { status: number; body: unknown };
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/common/output-schemas.ts b/packages/pieces/community/lemon-squeezy/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..8d95e9a976f
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/common/output-schemas.ts
@@ -0,0 +1,502 @@
+import { FieldFormat, OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+
+type Spec = [key: string, label: string, format?: FieldFormat, description?: string];
+const CENTS = 'In cents (smallest currency unit).';
+
+const fields = (specs: Spec[]): OutputSchemaField[] =>
+ specs.map(([key, label, format, description]) => ({
+ key,
+ label,
+ ...(format ? { format } : {}),
+ ...(description ? { description } : {}),
+ }));
+
+const timestamps: Spec[] = [
+ ['created_at', 'Created At', 'datetime'],
+ ['updated_at', 'Updated At', 'datetime'],
+];
+const testMode: Spec = ['test_mode', 'Test Mode', 'boolean'];
+
+const storeSpecs: Spec[] = [
+ ['name', 'Name'],
+ ['slug', 'Slug'],
+ ['domain', 'Domain'],
+ ['url', 'URL', 'url'],
+ ['avatar_url', 'Avatar URL', 'image'],
+ ['plan', 'Plan'],
+ ['country', 'Country'],
+ ['country_nicename', 'Country Name'],
+ ['currency', 'Currency'],
+ ['total_sales', 'Total Sales', 'number'],
+ ['total_revenue', 'Total Revenue', 'number', CENTS],
+ ['thirty_day_sales', '30-Day Sales', 'number'],
+ ['thirty_day_revenue', '30-Day Revenue', 'number', CENTS],
+ ...timestamps,
+];
+
+const customerSpecs: Spec[] = [
+ ['store_id', 'Store ID', 'number'],
+ ['name', 'Name'],
+ ['email', 'Email', 'email'],
+ ['status', 'Status', undefined, 'subscribed, unsubscribed, archived, requires_verification, invalid_email or bounced.'],
+ ['status_formatted', 'Status (Formatted)'],
+ ['city', 'City'],
+ ['region', 'Region'],
+ ['country', 'Country'],
+ ['country_formatted', 'Country (Formatted)'],
+ ['total_revenue_currency', 'Total Revenue', 'number', CENTS],
+ ['total_revenue_currency_formatted', 'Total Revenue (Formatted)'],
+ ['mrr', 'MRR', 'number', CENTS],
+ ['mrr_formatted', 'MRR (Formatted)'],
+ ...timestamps,
+ testMode,
+];
+const customerUrls: OutputSchemaField = { key: 'urls', label: 'URLs', children: fields([['customer_portal', 'Customer Portal', 'url']]) };
+
+const orderItemSpecs: Spec[] = [
+ ['order_id', 'Order ID', 'number'],
+ ['product_id', 'Product ID', 'number'],
+ ['variant_id', 'Variant ID', 'number'],
+ ['price_id', 'Price ID', 'number'],
+ ['product_name', 'Product Name'],
+ ['variant_name', 'Variant Name'],
+ ['price', 'Price', 'number', CENTS],
+ ['quantity', 'Quantity', 'number'],
+ ...timestamps,
+ testMode,
+];
+
+const orderSpecs: Spec[] = [
+ ['store_id', 'Store ID', 'number'],
+ ['customer_id', 'Customer ID', 'number'],
+ ['identifier', 'Identifier'],
+ ['order_number', 'Order Number', 'number'],
+ ['user_name', 'Customer Name'],
+ ['user_email', 'Customer Email', 'email'],
+ ['currency', 'Currency'],
+ ['currency_rate', 'Currency Rate'],
+ ['subtotal', 'Subtotal', 'number', CENTS],
+ ['setup_fee', 'Setup Fee', 'number', CENTS],
+ ['discount_total', 'Discount Total', 'number', CENTS],
+ ['tax', 'Tax', 'number', CENTS],
+ ['total', 'Total', 'number', CENTS],
+ ['refunded_amount', 'Refunded Amount', 'number', CENTS],
+ ['subtotal_usd', 'Subtotal (USD cents)', 'number'],
+ ['discount_total_usd', 'Discount Total (USD cents)', 'number'],
+ ['tax_usd', 'Tax (USD cents)', 'number'],
+ ['total_usd', 'Total (USD cents)', 'number'],
+ ['refunded_amount_usd', 'Refunded Amount (USD cents)', 'number'],
+ ['setup_fee_usd', 'Setup Fee (USD cents)', 'number'],
+ ['setup_fee_formatted', 'Setup Fee (Formatted)'],
+ ['affiliate_id', 'Affiliate ID', 'number'],
+ ['referral_amount', 'Referral Amount', 'number', CENTS],
+ ['tax_name', 'Tax Name'],
+ ['tax_rate', 'Tax Rate'],
+ ['tax_inclusive', 'Tax Inclusive', 'boolean'],
+ ['status', 'Status', undefined, 'pending, failed, paid, refunded, partial_refund or fraudulent.'],
+ ['status_formatted', 'Status (Formatted)'],
+ ['refunded', 'Refunded', 'boolean'],
+ ['refunded_at', 'Refunded At', 'datetime'],
+ ['subtotal_formatted', 'Subtotal (Formatted)'],
+ ['discount_total_formatted', 'Discount Total (Formatted)'],
+ ['tax_formatted', 'Tax (Formatted)'],
+ ['total_formatted', 'Total (Formatted)'],
+ ['refunded_amount_formatted', 'Refunded Amount (Formatted)'],
+ ...timestamps,
+ testMode,
+];
+const orderNested: OutputSchemaField[] = [
+ {
+ key: 'first_order_item',
+ label: 'First Order Item',
+ children: fields([['id', 'ID', 'number'], ...orderItemSpecs]),
+ },
+ { key: 'urls', label: 'URLs', children: fields([['receipt', 'Receipt', 'url']]) },
+];
+
+const productSpecs: Spec[] = [
+ ['store_id', 'Store ID', 'number'],
+ ['name', 'Name'],
+ ['slug', 'Slug'],
+ ['description', 'Description', 'html'],
+ ['status', 'Status', undefined, 'draft or published.'],
+ ['status_formatted', 'Status (Formatted)'],
+ ['thumb_url', 'Thumbnail URL', 'image'],
+ ['large_thumb_url', 'Large Thumbnail URL', 'image'],
+ ['price', 'Price', 'number', CENTS],
+ ['price_formatted', 'Price (Formatted)'],
+ ['from_price', 'From Price', 'number', CENTS],
+ ['to_price', 'To Price', 'number', CENTS],
+ ['pay_what_you_want', 'Pay What You Want', 'boolean'],
+ ['buy_now_url', 'Buy Now URL', 'url'],
+ ...timestamps,
+ testMode,
+];
+
+const variantSpecs: Spec[] = [
+ ['product_id', 'Product ID', 'number'],
+ ['name', 'Name'],
+ ['slug', 'Slug'],
+ ['description', 'Description', 'html'],
+ ['price', 'Price', 'number', CENTS],
+ ['is_subscription', 'Is Subscription', 'boolean'],
+ ['interval', 'Interval', undefined, 'day, week, month or year.'],
+ ['interval_count', 'Interval Count', 'number'],
+ ['has_free_trial', 'Has Free Trial', 'boolean'],
+ ['trial_interval', 'Trial Interval'],
+ ['trial_interval_count', 'Trial Interval Count', 'number'],
+ ['pay_what_you_want', 'Pay What You Want', 'boolean'],
+ ['min_price', 'Minimum Price', 'number', CENTS],
+ ['suggested_price', 'Suggested Price', 'number', CENTS],
+ ['has_license_keys', 'Has License Keys', 'boolean'],
+ ['license_activation_limit', 'License Activation Limit', 'number'],
+ ['is_license_limit_unlimited', 'License Limit Unlimited', 'boolean'],
+ ['license_length_value', 'License Length', 'number'],
+ ['license_length_unit', 'License Length Unit'],
+ ['is_license_length_unlimited', 'License Length Unlimited', 'boolean'],
+ ['sort', 'Sort', 'number'],
+ ['status', 'Status', undefined, 'pending, draft or published.'],
+ ['status_formatted', 'Status (Formatted)'],
+ ...timestamps,
+ testMode,
+];
+
+const subscriptionSpecs: Spec[] = [
+ ['store_id', 'Store ID', 'number'],
+ ['customer_id', 'Customer ID', 'number'],
+ ['order_id', 'Order ID', 'number'],
+ ['order_item_id', 'Order Item ID', 'number'],
+ ['product_id', 'Product ID', 'number'],
+ ['variant_id', 'Variant ID', 'number'],
+ ['product_name', 'Product Name'],
+ ['variant_name', 'Variant Name'],
+ ['user_name', 'Customer Name'],
+ ['user_email', 'Customer Email', 'email'],
+ ['status', 'Status', undefined, 'on_trial, active, paused, past_due, unpaid, cancelled or expired.'],
+ ['status_formatted', 'Status (Formatted)'],
+ ['card_brand', 'Card Brand'],
+ ['card_last_four', 'Card Last Four'],
+ ['payment_processor', 'Payment Processor', undefined, 'stripe or paypal.'],
+ ['cancelled', 'Cancelled', 'boolean'],
+ ['trial_ends_at', 'Trial Ends At', 'datetime'],
+ ['billing_anchor', 'Billing Anchor (day of month)', 'number'],
+ ['renews_at', 'Renews At', 'datetime'],
+ ['ends_at', 'Ends At', 'datetime'],
+ ...timestamps,
+ testMode,
+];
+const subscriptionNested: OutputSchemaField[] = [
+ {
+ key: 'pause',
+ label: 'Pause',
+ description: 'Null when the subscription is not paused.',
+ children: fields([
+ ['mode', 'Mode', undefined, 'void or free.'],
+ ['resumes_at', 'Resumes At', 'datetime'],
+ ]),
+ },
+ {
+ key: 'first_subscription_item',
+ label: 'First Subscription Item',
+ children: fields([
+ ['id', 'ID', 'number'],
+ ['subscription_id', 'Subscription ID', 'number'],
+ ['price_id', 'Price ID', 'number'],
+ ['quantity', 'Quantity', 'number'],
+ ['is_usage_based', 'Is Usage Based', 'boolean'],
+ ['created_at', 'Created At', 'datetime'],
+ ['updated_at', 'Updated At', 'datetime'],
+ ]),
+ },
+ {
+ key: 'urls',
+ label: 'URLs',
+ children: fields([
+ ['update_payment_method', 'Update Payment Method', 'url'],
+ ['customer_portal', 'Customer Portal', 'url'],
+ ['customer_portal_update_subscription', 'Customer Portal (Update Subscription)', 'url'],
+ ]),
+ },
+];
+
+const subscriptionInvoiceSpecs: Spec[] = [
+ ['store_id', 'Store ID', 'number'],
+ ['subscription_id', 'Subscription ID', 'number'],
+ ['customer_id', 'Customer ID', 'number'],
+ ['user_name', 'Customer Name'],
+ ['user_email', 'Customer Email', 'email'],
+ ['billing_reason', 'Billing Reason', undefined, 'initial, renewal or updated.'],
+ ['card_brand', 'Card Brand'],
+ ['card_last_four', 'Card Last Four'],
+ ['currency', 'Currency'],
+ ['currency_rate', 'Currency Rate'],
+ ['status', 'Status', undefined, 'pending, paid, void, refunded or partial_refund.'],
+ ['status_formatted', 'Status (Formatted)'],
+ ['refunded', 'Refunded', 'boolean'],
+ ['refunded_at', 'Refunded At', 'datetime'],
+ ['subtotal', 'Subtotal', 'number', CENTS],
+ ['discount_total', 'Discount Total', 'number', CENTS],
+ ['tax', 'Tax', 'number', CENTS],
+ ['tax_inclusive', 'Tax Inclusive', 'boolean'],
+ ['total', 'Total', 'number', CENTS],
+ ['refunded_amount', 'Refunded Amount', 'number', CENTS],
+ ['subtotal_usd', 'Subtotal (USD cents)', 'number'],
+ ['discount_total_usd', 'Discount Total (USD cents)', 'number'],
+ ['tax_usd', 'Tax (USD cents)', 'number'],
+ ['total_usd', 'Total (USD cents)', 'number'],
+ ['refunded_amount_usd', 'Refunded Amount (USD cents)', 'number'],
+ ['affiliate_id', 'Affiliate ID', 'number'],
+ ['referral_amount', 'Referral Amount', 'number', CENTS],
+ ['subtotal_formatted', 'Subtotal (Formatted)'],
+ ['discount_total_formatted', 'Discount Total (Formatted)'],
+ ['tax_formatted', 'Tax (Formatted)'],
+ ['total_formatted', 'Total (Formatted)'],
+ ['refunded_amount_formatted', 'Refunded Amount (Formatted)'],
+ ...timestamps,
+ testMode,
+];
+const invoiceUrls: OutputSchemaField = { key: 'urls', label: 'URLs', children: fields([['invoice_url', 'Invoice URL', 'url']]) };
+
+const discountSpecs: Spec[] = [
+ ['store_id', 'Store ID', 'number'],
+ ['name', 'Name'],
+ ['code', 'Code'],
+ ['amount', 'Amount', 'number', 'Percent (0–100) when amount_type is percent, cents when fixed.'],
+ ['amount_type', 'Amount Type', undefined, 'percent or fixed.'],
+ ['is_limited_to_products', 'Limited to Products', 'boolean'],
+ ['is_limited_redemptions', 'Limited Redemptions', 'boolean'],
+ ['max_redemptions', 'Max Redemptions', 'number'],
+ ['starts_at', 'Starts At', 'datetime'],
+ ['expires_at', 'Expires At', 'datetime'],
+ ['duration', 'Duration', undefined, 'once, repeating or forever.'],
+ ['duration_in_months', 'Duration in Months', 'number'],
+ ['status', 'Status', undefined, 'draft or published.'],
+ ['status_formatted', 'Status (Formatted)'],
+ ...timestamps,
+ testMode,
+];
+
+const licenseKeySpecs: Spec[] = [
+ ['store_id', 'Store ID', 'number'],
+ ['customer_id', 'Customer ID', 'number'],
+ ['order_id', 'Order ID', 'number'],
+ ['order_item_id', 'Order Item ID', 'number'],
+ ['product_id', 'Product ID', 'number'],
+ ['user_name', 'Customer Name'],
+ ['user_email', 'Customer Email', 'email'],
+ ['key', 'License Key', undefined, 'The full license key.'],
+ ['key_short', 'License Key (Short)', undefined, 'Last 4 characters prefixed with XXXX.'],
+ ['activation_limit', 'Activation Limit', 'number', 'Null when unlimited.'],
+ ['instances_count', 'Activations', 'number'],
+ ['disabled', 'Disabled', 'boolean'],
+ ['status', 'Status', undefined, 'inactive, active, expired or disabled.'],
+ ['status_formatted', 'Status (Formatted)'],
+ ['expires_at', 'Expires At', 'datetime'],
+ ...timestamps,
+ testMode,
+];
+
+const licenseKeyInstanceSpecs: Spec[] = [
+ ['license_key_id', 'License Key ID', 'number'],
+ ['identifier', 'Instance Identifier'],
+ ['name', 'Instance Name'],
+ ...timestamps,
+];
+
+const discountRedemptionSpecs: Spec[] = [
+ ['discount_id', 'Discount ID', 'number'],
+ ['order_id', 'Order ID', 'number'],
+ ['discount_name', 'Discount Name'],
+ ['discount_code', 'Discount Code'],
+ ['discount_amount', 'Discount Amount', 'number', 'Percent or cents, depending on the amount type.'],
+ ['discount_amount_type', 'Discount Amount Type', undefined, 'percent or fixed.'],
+ ['amount', 'Amount Saved', 'number', CENTS],
+ ...timestamps,
+];
+
+const subscriptionItemSpecs: Spec[] = [
+ ['subscription_id', 'Subscription ID', 'number'],
+ ['price_id', 'Price ID', 'number'],
+ ['quantity', 'Quantity', 'number'],
+ ['is_usage_based', 'Is Usage Based', 'boolean'],
+ ...timestamps,
+];
+
+const affiliateSpecs: Spec[] = [
+ ['store_id', 'Store ID', 'number'],
+ ['user_id', 'User ID', 'number'],
+ ['user_name', 'Name'],
+ ['user_email', 'Email', 'email'],
+ ['share_domain', 'Share Domain'],
+ ['status', 'Status'],
+ ['application_note', 'Application Note'],
+ ['total_earnings', 'Total Earnings', 'number', CENTS],
+ ['unpaid_earnings', 'Unpaid Earnings', 'number', CENTS],
+ ...timestamps,
+];
+
+const flat = ({ specs, nested = [] }: { specs: Spec[]; nested?: OutputSchemaField[] }): OutputSchemaField[] => [
+ { key: 'id', label: 'ID' },
+ ...fields(specs),
+ ...nested,
+];
+
+export const flatFields = {
+ store: flat({ specs: storeSpecs }),
+ customer: flat({ specs: customerSpecs, nested: [customerUrls] }),
+ order: flat({ specs: orderSpecs, nested: orderNested }),
+ orderItem: flat({ specs: orderItemSpecs }),
+ product: flat({ specs: productSpecs }),
+ variant: flat({ specs: variantSpecs }),
+ subscription: flat({ specs: subscriptionSpecs, nested: subscriptionNested }),
+ subscriptionInvoice: flat({ specs: subscriptionInvoiceSpecs, nested: [invoiceUrls] }),
+ discount: flat({ specs: discountSpecs }),
+ licenseKey: flat({ specs: licenseKeySpecs }),
+ licenseKeyInstance: flat({ specs: licenseKeyInstanceSpecs }),
+ discountRedemption: flat({ specs: discountRedemptionSpecs }),
+ subscriptionItem: flat({ specs: subscriptionItemSpecs }),
+ affiliate: flat({ specs: affiliateSpecs }),
+};
+
+export const recordSchema = (f: OutputSchemaField[]): OutputSchema => ({ fields: f });
+
+export const listSchema = ({ fields: f, itemLabel }: { fields: OutputSchemaField[]; itemLabel: string }): OutputSchema => ({
+ fields: [
+ { key: 'items', label: 'Items', listItems: f, labelKey: itemLabel },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'last_page', label: 'Last Page', format: 'number' },
+ { key: 'per_page', label: 'Per Page', format: 'number' },
+ { key: 'total', label: 'Total Matches', format: 'number' },
+ { key: 'has_more', label: 'Has More Pages', format: 'boolean' },
+ ],
+});
+
+const rawResource = ({ specs, nested = [] }: { specs: Spec[]; nested?: OutputSchemaField[] }): OutputSchemaField[] => [
+ { key: 'type', label: 'Type' },
+ { key: 'id', label: 'ID' },
+ { key: 'attributes', label: 'Attributes', children: [...fields(specs), ...nested] },
+];
+
+const rawPageMeta: OutputSchemaField = {
+ key: 'meta',
+ label: 'Meta',
+ children: [
+ {
+ key: 'page',
+ label: 'Page',
+ children: fields([
+ ['currentPage', 'Current Page', 'number'],
+ ['from', 'From', 'number'],
+ ['lastPage', 'Last Page', 'number'],
+ ['perPage', 'Per Page', 'number'],
+ ['to', 'To', 'number'],
+ ['total', 'Total', 'number'],
+ ]),
+ },
+ ],
+};
+
+const rawListSchema = ({ specs, nested = [] }: { specs: Spec[]; nested?: OutputSchemaField[] }): OutputSchema => ({
+ fields: [rawPageMeta, { key: 'data', label: 'Data', listItems: rawResource({ specs, nested }) }],
+});
+
+export const rawSchemas = {
+ products: rawListSchema({ specs: productSpecs }),
+ orders: rawListSchema({ specs: orderSpecs, nested: orderNested }),
+ subscriptions: rawListSchema({ specs: subscriptionSpecs, nested: subscriptionNested }),
+ customers: rawListSchema({ specs: customerSpecs, nested: [customerUrls] }),
+ order: { fields: [{ key: 'data', label: 'Data', children: rawResource({ specs: orderSpecs, nested: orderNested }) }] },
+ checkout: {
+ fields: [
+ {
+ key: 'data',
+ label: 'Data',
+ children: rawResource({
+ specs: [
+ ['store_id', 'Store ID', 'number'],
+ ['variant_id', 'Variant ID', 'number'],
+ ['custom_price', 'Custom Price', 'number', CENTS],
+ ['expires_at', 'Expires At', 'datetime'],
+ ['url', 'Checkout URL', 'url'],
+ ...timestamps,
+ testMode,
+ ],
+ }),
+ },
+ ],
+ },
+} satisfies Record<string, OutputSchema>;
+
+const webhookSchema = ({ specs, nested = [] }: { specs: Spec[]; nested?: OutputSchemaField[] }): OutputSchema => ({
+ fields: [
+ {
+ key: 'meta',
+ label: 'Meta',
+ children: [
+ ...fields([
+ ['event_name', 'Event Name'],
+ ['test_mode', 'Test Mode', 'boolean'],
+ ['webhook_id', 'Webhook ID'],
+ ]),
+ { key: 'custom_data', label: 'Custom Data', description: 'Custom data passed at checkout, if any.' },
+ ],
+ },
+ { key: 'data', label: 'Data', children: rawResource({ specs, nested }) },
+ ],
+});
+
+export const validateLicenseSchema: OutputSchema = {
+ fields: [
+ { key: 'valid', label: 'Valid', format: 'boolean' },
+ { key: 'error', label: 'Error', description: 'Why the key is not valid. Null when valid.' },
+ {
+ key: 'license_key',
+ label: 'License Key',
+ description: 'Null when the key does not exist. The key itself is not returned.',
+ children: fields([
+ ['id', 'License Key ID', 'number'],
+ ['status', 'Status', undefined, 'inactive, active, expired or disabled.'],
+ ['activation_limit', 'Activation Limit', 'number'],
+ ['activation_usage', 'Activations Used', 'number'],
+ ['expires_at', 'Expires At', 'datetime'],
+ ['created_at', 'Created At', 'datetime'],
+ ['test_mode', 'Test Mode', 'boolean'],
+ ]),
+ },
+ {
+ key: 'instance',
+ label: 'Instance',
+ description: 'Null unless an instance ID was given and matched.',
+ children: fields([
+ ['id', 'Instance ID'],
+ ['name', 'Name'],
+ ['created_at', 'Created At', 'datetime'],
+ ]),
+ },
+ {
+ key: 'meta',
+ label: 'Purchase',
+ children: fields([
+ ['store_id', 'Store ID', 'number'],
+ ['order_id', 'Order ID', 'number'],
+ ['order_item_id', 'Order Item ID', 'number'],
+ ['product_id', 'Product ID', 'number'],
+ ['product_name', 'Product Name'],
+ ['variant_id', 'Variant ID', 'number'],
+ ['variant_name', 'Variant Name'],
+ ['customer_id', 'Customer ID', 'number'],
+ ['customer_name', 'Customer Name'],
+ ['customer_email', 'Customer Email', 'email'],
+ ]),
+ },
+ ],
+};
+
+export const webhookSchemas = {
+ order: webhookSchema({ specs: orderSpecs, nested: orderNested }),
+ subscription: webhookSchema({ specs: subscriptionSpecs, nested: subscriptionNested }),
+ subscriptionInvoice: webhookSchema({ specs: subscriptionInvoiceSpecs, nested: [invoiceUrls] }),
+ licenseKey: webhookSchema({ specs: licenseKeySpecs }),
+ affiliate: webhookSchema({ specs: affiliateSpecs }),
+};
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/common/props.ts b/packages/pieces/community/lemon-squeezy/src/lib/common/props.ts
new file mode 100644
index 00000000000..033a1c1a5de
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/common/props.ts
@@ -0,0 +1,100 @@
+import { Property } from '@activepieces/pieces-framework';
+import { lemonSqueezyAuth } from './auth';
+import { JsonApiResource, listAllPages } from './client';
+
+export async function storeOptions({ auth }: { auth: ConnectionAuth }) {
+ return dropdownOptions({ auth, path: '/stores', label: (s) => String(attr({ item: s, key: 'name' }) ?? s.id) });
+}
+
+export async function orderOptions({ auth, storeId }: { auth: ConnectionAuth; storeId?: unknown }) {
+ return dropdownOptions({
+ auth,
+ path: '/orders',
+ query: { 'filter[store_id]': storeId ? String(storeId) : undefined },
+ label: (o) =>
+ `#${String(attr({ item: o, key: 'order_number' }) ?? o.id)} — ${String(attr({ item: o, key: 'user_name' }) ?? '')} (${String(
+ attr({ item: o, key: 'status_formatted' }) ?? '',
+ )})`,
+ });
+}
+
+export async function productOptions({ auth, storeId }: { auth: ConnectionAuth; storeId?: unknown }) {
+ return dropdownOptions({
+ auth,
+ path: '/products',
+ query: { 'filter[store_id]': storeId ? String(storeId) : undefined },
+ label: (p) => String(attr({ item: p, key: 'name' }) ?? p.id),
+ });
+}
+
+export async function variantOptions({ auth, productId }: { auth: ConnectionAuth; productId?: unknown }) {
+ return dropdownOptions({
+ auth,
+ path: '/variants',
+ query: { 'filter[product_id]': productId ? String(productId) : undefined },
+ label: (v) => String(attr({ item: v, key: 'name' }) ?? v.id),
+ });
+}
+
+export const storeDropdown = ({ required, description }: { required: boolean; description: string }) =>
+ Property.Dropdown({
+ displayName: 'Store',
+ description,
+ required,
+ auth: lemonSqueezyAuth,
+ refreshers: ['auth'],
+ options: async ({ auth }) => storeOptions({ auth }),
+ });
+
+export const pageProps = (noun: string) => ({
+ page: Property.Number({
+ displayName: 'Page',
+ description: 'Page number for pagination (starts at 1).',
+ required: false,
+ defaultValue: 1,
+ }),
+ perPage: Property.Number({
+ displayName: 'Per Page',
+ description: `Number of ${noun} to return per page (1–100). Default is 10.`,
+ required: false,
+ defaultValue: 10,
+ }),
+});
+
+async function dropdownOptions({
+ auth,
+ path,
+ query,
+ label,
+}: {
+ auth: ConnectionAuth;
+ path: string;
+ query?: Record<string, string | undefined>;
+ label: (item: JsonApiResource) => string;
+}): Promise<DropdownState> {
+ if (!auth) {
+ return { disabled: true, placeholder: 'Connect your account first.', options: [] };
+ }
+ try {
+ const { items, truncated } = await listAllPages({ apiKey: auth.secret_text, path, query });
+ return {
+ disabled: false,
+ options: items.map((item) => ({ label: label(item), value: item.id })),
+ placeholder: truncated ? 'Showing the first 1,000 results. Use the ID field or a narrower filter for others.' : undefined,
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: `Could not load options: ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+}
+
+function attr({ item, key }: { item: JsonApiResource; key: string }): unknown {
+ return item.attributes[key];
+}
+
+type ConnectionAuth = { secret_text: string } | undefined;
+
+type DropdownState = { disabled: boolean; placeholder?: string; options: { label: string; value: string }[] };
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/common/validation.ts b/packages/pieces/community/lemon-squeezy/src/lib/common/validation.ts
new file mode 100644
index 00000000000..9dc090c3fbd
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/src/lib/common/validation.ts
@@ -0,0 +1,7 @@
+export function countryCode(value: string): string {
+ const code = value.trim().toUpperCase();
+ if (!/^[A-Z]{2}$/.test(code)) {
+ throw new Error('Country must be a 2-letter ISO 3166-1 alpha-2 code, for example US, GB or DE.');
+ }
+ return code;
+}
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/common/webhook.ts b/packages/pieces/community/lemon-squeezy/src/lib/common/webhook.ts
index 18137ced13c..6ca4d8e03bc 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/common/webhook.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/common/webhook.ts
@@ -1,103 +1,203 @@
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { createHmac, randomBytes, timingSafeEqual } from 'crypto';
import { Property } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from './auth';
-import { LEMON_SQUEEZY_API_BASE } from './api';
-
-export const subscribeWebhook = async (auth: string, storeId: string, events: string[], targetUrl: string, secret: string) => {
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `${LEMON_SQUEEZY_API_BASE}/webhooks`,
- headers: {
- 'Authorization': `Bearer ${auth}`,
- 'Accept': 'application/vnd.api+json',
- 'Content-Type': 'application/vnd.api+json',
- },
+import { LemonSqueezyApiError, RATE_LIMIT_WAITS, getTestModeForKey, isRecord, lsRequest, numericId, readPath, seg } from './client';
+import { storeOptions } from './props';
+
+export const createWebhookTriggerKey = (eventName: string) => `_${eventName}_trigger`;
+
+export const generateWebhookSecret = () => randomBytes(20).toString('hex');
+
+export const createStoreDropdownProperty = () =>
+ Property.Dropdown({
+ displayName: 'Store',
+ required: true,
+ refreshers: ['auth'],
+ auth: lemonSqueezyAuth,
+ options: async ({ auth }) => storeOptions({ auth }),
+ });
+
+export async function subscribeWebhook({
+ apiKey,
+ storeId,
+ events,
+ targetUrl,
+ secret,
+ testMode,
+}: {
+ apiKey: string;
+ storeId: string;
+ events: string[];
+ targetUrl: string;
+ secret: string;
+ testMode: boolean;
+}): Promise<string> {
+ const { body } = await lsRequest({
+ apiKey,
+ method: 'POST',
+ path: '/webhooks',
+ rateLimitWaitsMs: RATE_LIMIT_WAITS.interactive,
body: {
data: {
type: 'webhooks',
- attributes: {
- url: targetUrl,
- events: events,
- secret: secret,
- test_mode: false
- },
- relationships: {
- store: {
- data: {
- type: 'stores',
- id: storeId
- }
- }
- }
- }
- }
+ attributes: { url: targetUrl, events, secret, test_mode: testMode },
+ relationships: { store: { data: { type: 'stores', id: numericId({ value: storeId, label: 'Store' }) } } },
+ },
+ },
});
- return response.body;
-};
+ const id = readPath({ value: body, path: ['data', 'id'] });
+ if (typeof id !== 'string' && typeof id !== 'number') {
+ throw new Error('Lemon Squeezy did not return a webhook ID.');
+ }
+ return String(id);
+}
-export const unsubscribeWebhook = async (auth: string, webhookId: string) => {
- await httpClient.sendRequest({
- method: HttpMethod.DELETE,
- url: `${LEMON_SQUEEZY_API_BASE}/webhooks/${webhookId}`,
- headers: {
- 'Authorization': `Bearer ${auth}`,
- 'Accept': 'application/vnd.api+json',
- 'Content-Type': 'application/vnd.api+json',
- }
+export async function unsubscribeWebhook({ apiKey, webhookId }: { apiKey: string; webhookId: string }): Promise<void> {
+ try {
+ await lsRequest({
+ apiKey,
+ method: 'DELETE',
+ path: `/webhooks/${seg({ value: webhookId, label: 'Webhook ID' })}`,
+ rateLimitWaitsMs: RATE_LIMIT_WAITS.interactive,
+ });
+ } catch (error) {
+ if (error instanceof LemonSqueezyApiError && error.status === 404) return;
+ throw error;
+ }
+}
+
+export async function enableWebhook({
+ auth,
+ store,
+ storeId,
+ webhookUrl,
+ eventName,
+}: {
+ auth: { secret_text: string };
+ store: TriggerStore;
+ storeId: unknown;
+ webhookUrl: string;
+ eventName: string;
+}): Promise<void> {
+ const apiKey = auth.secret_text;
+ const testMode = await getTestModeForKey(apiKey);
+ const secret = generateWebhookSecret();
+ const webhookId = await subscribeWebhook({
+ apiKey,
+ storeId: String(storeId ?? ''),
+ events: [eventName],
+ targetUrl: webhookUrl,
+ secret,
+ testMode,
});
-};
+ try {
+ await store.put(createWebhookTriggerKey(eventName), { webhookId, secret, storeId: String(storeId ?? ''), testMode });
+ } catch (error) {
+ await unsubscribeWebhook({ apiKey, webhookId }).catch(() => undefined);
+ throw error;
+ }
+}
-export const getStores = async (auth: string) => {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `${LEMON_SQUEEZY_API_BASE}/stores`,
- headers: {
- 'Authorization': `Bearer ${auth}`,
- 'Accept': 'application/vnd.api+json',
- 'Content-Type': 'application/vnd.api+json',
- }
+export async function disableWebhook({
+ auth,
+ store,
+ eventName,
+}: {
+ auth: { secret_text: string };
+ store: TriggerStore;
+ eventName: string;
+}): Promise<void> {
+ const stored = toStoredWebhook(await store.get(createWebhookTriggerKey(eventName)));
+ if (stored) {
+ await unsubscribeWebhook({ apiKey: auth.secret_text, webhookId: stored.webhookId });
+ }
+ await store.delete(createWebhookTriggerKey(eventName));
+ await store.delete(seenKey(eventName));
+}
+
+export function verifyLemonSqueezySignature({
+ secret,
+ signature,
+ rawBody,
+}: {
+ secret: string | undefined;
+ signature: string | undefined;
+ rawBody: unknown;
+}): boolean {
+ const body = rawBodyBuffer(rawBody);
+ if (!secret || !signature || !body || !/^[0-9a-f]+$/i.test(signature)) return false;
+ const expected = createHmac('sha256', secret).update(body).digest();
+ const received = Buffer.from(signature, 'hex');
+ return received.length === expected.length && timingSafeEqual(received, expected);
+}
+
+export async function handleWebhook({
+ payload,
+ store,
+ eventName,
+}: {
+ payload: { body: unknown; headers: Record<string, unknown>; rawBody?: unknown };
+ store: TriggerStore;
+ eventName: string;
+}): Promise<unknown[]> {
+ const stored = toStoredWebhook(await store.get(createWebhookTriggerKey(eventName)));
+ const valid = verifyLemonSqueezySignature({
+ secret: stored?.secret,
+ signature: headerValue({ headers: payload.headers, name: 'x-signature' }),
+ rawBody: payload.rawBody,
});
- return response.body.data;
-};
+ if (!valid) return [];
-export const createStoreDropdownProperty = () => {
- return Property.Dropdown({
- displayName: 'Store',
- required: true,
- refreshers: ['auth'],
- auth: lemonSqueezyAuth,
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please authenticate first'
- };
- }
-
- try {
- const stores = await getStores(auth.secret_text);
- return {
- options: stores.map((store: any) => ({
- label: store.attributes.name,
- value: store.id
- }))
- };
- } catch (error) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Failed to load stores'
- };
- }
+ const body = payload.body;
+ if (readPath({ value: body, path: ['meta', 'event_name'] }) !== eventName) return [];
+
+ const dataId = readPath({ value: body, path: ['data', 'id'] });
+ if (typeof dataId !== 'string' && typeof dataId !== 'number') return [body];
+ const updatedAt = readPath({ value: body, path: ['data', 'attributes', 'updated_at'] });
+ const dedupeId = `${String(dataId)}:${typeof updatedAt === 'string' ? updatedAt : ''}`;
+ const seenRaw = await store.get(seenKey(eventName));
+ const seen = Array.isArray(seenRaw) ? seenRaw.filter((s): s is string => typeof s === 'string') : [];
+ if (seen.includes(dedupeId)) return [];
+ await store.put(seenKey(eventName), [...seen, dedupeId].slice(-SEEN_LIMIT));
+
+ return [body];
+}
+
+const SEEN_LIMIT = 200;
+
+function seenKey(eventName: string): string {
+ return `_${eventName}_seen`;
+}
+
+function toStoredWebhook(value: unknown): StoredWebhook | null {
+ if (!isRecord(value)) return null;
+ const { webhookId, secret } = value;
+ if (typeof webhookId !== 'string' || typeof secret !== 'string') return null;
+ return { webhookId, secret };
+}
+
+function headerValue({ headers, name }: { headers: Record<string, unknown> | undefined; name: string }): string | undefined {
+ if (!headers) return undefined;
+ const wanted = name.toLowerCase();
+ for (const [key, value] of Object.entries(headers)) {
+ if (key.toLowerCase() === wanted) {
+ return Array.isArray(value) ? String(value[0]) : typeof value === 'string' ? value : undefined;
}
- });
-};
+ }
+ return undefined;
+}
-export const generateWebhookSecret = () => {
- return `lemonsqueezy_${Date.now()}_${Math.random().toString(36).substring(2)}`;
-};
+function rawBodyBuffer(rawBody: unknown): Buffer | undefined {
+ if (Buffer.isBuffer(rawBody)) return rawBody;
+ if (typeof rawBody === 'string') return Buffer.from(rawBody, 'utf8');
+ if (rawBody instanceof Uint8Array) return Buffer.from(rawBody);
+ return undefined;
+}
-export const createWebhookTriggerKey = (eventName: string) => {
- return `_${eventName}_trigger`;
+type TriggerStore = {
+ get<T>(key: string): Promise<T | null>;
+ put<T>(key: string, value: T): Promise<T>;
+ delete(key: string): Promise<void>;
};
+
+type StoredWebhook = { webhookId: string; secret: string };
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/affiliate-activated.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/affiliate-activated.ts
index 02cb8b18dfc..8d011b49df2 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/affiliate-activated.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/affiliate-activated.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const affiliateActivatedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const affiliateActivatedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['affiliate_activated'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('affiliate_activated'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'affiliate_activated',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('affiliate_activated'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'affiliate_activated' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'affiliate_activated' });
},
+ outputSchema: webhookSchemas.affiliate,
sampleData: {
meta: {
event_name: 'affiliate_activated',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/license-key-created.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/license-key-created.ts
index 51ac3b6c2e2..f2963634912 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/license-key-created.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/license-key-created.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const licenseKeyCreatedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const licenseKeyCreatedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['license_key_created'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('license_key_created'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'license_key_created',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('license_key_created'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'license_key_created' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'license_key_created' });
},
+ outputSchema: webhookSchemas.licenseKey,
sampleData: {
meta: {
event_name: 'license_key_created',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/license-key-updated.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/license-key-updated.ts
index c51bccad9ae..2c9ac06d6a5 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/license-key-updated.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/license-key-updated.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const licenseKeyUpdatedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const licenseKeyUpdatedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['license_key_updated'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('license_key_updated'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'license_key_updated',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('license_key_updated'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'license_key_updated' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'license_key_updated' });
},
+ outputSchema: webhookSchemas.licenseKey,
sampleData: {
meta: {
event_name: 'license_key_updated',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/order-created.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/order-created.ts
index 6e5332324f8..295edec431b 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/order-created.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/order-created.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const orderCreatedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const orderCreatedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['order_created'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('order_created'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'order_created',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('order_created'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'order_created' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'order_created' });
},
+ outputSchema: webhookSchemas.order,
sampleData: {
meta: {
event_name: 'order_created',
@@ -73,8 +63,8 @@ export const orderCreatedTrigger = createTrigger({
discount_total_formatted: '$0.00',
tax_formatted: '$2.00',
total_formatted: '$11.99',
- status: 'pending',
- status_formatted: 'Pending',
+ status: 'paid',
+ status_formatted: 'Paid',
created_at: '2021-08-17T09:45:53.000000Z',
updated_at: '2021-08-17T09:45:53.000000Z',
test_mode: false,
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/order-refunded.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/order-refunded.ts
index bc949122f72..6a0b42749ca 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/order-refunded.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/order-refunded.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const orderRefundedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const orderRefundedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['order_refunded'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('order_refunded'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'order_refunded',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('order_refunded'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'order_refunded' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'order_refunded' });
},
+ outputSchema: webhookSchemas.order,
sampleData: {
meta: {
event_name: 'order_refunded',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-cancelled.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-cancelled.ts
index 762c92a913e..3250b6012af 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-cancelled.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-cancelled.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionCancelledTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionCancelledTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_cancelled'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_cancelled'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_cancelled',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_cancelled'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_cancelled' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_cancelled' });
},
+ outputSchema: webhookSchemas.subscription,
sampleData: {
meta: {
event_name: 'subscription_cancelled',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-created.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-created.ts
index 148c1df1a8c..f1f013bcea1 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-created.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-created.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionCreatedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionCreatedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_created'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_created'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_created',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_created'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_created' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_created' });
},
+ outputSchema: webhookSchemas.subscription,
sampleData: {
meta: {
event_name: 'subscription_created',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-expired.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-expired.ts
index 415b2955176..086a5d80ecf 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-expired.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-expired.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionExpiredTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionExpiredTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_expired'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_expired'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_expired',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_expired'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_expired' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_expired' });
},
+ outputSchema: webhookSchemas.subscription,
sampleData: {
meta: {
event_name: 'subscription_expired',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-paused.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-paused.ts
index 59561acc2f8..7a45a861c2f 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-paused.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-paused.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionPausedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionPausedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_paused'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_paused'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_paused',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_paused'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_paused' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_paused' });
},
+ outputSchema: webhookSchemas.subscription,
sampleData: {
meta: {
event_name: 'subscription_paused',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-failed.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-failed.ts
index 40d5c7336f4..4186fb4aa4e 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-failed.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-failed.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionPaymentFailedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionPaymentFailedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_payment_failed'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_payment_failed'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_payment_failed',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_payment_failed'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_payment_failed' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_payment_failed' });
},
+ outputSchema: webhookSchemas.subscriptionInvoice,
sampleData: {
meta: {
event_name: 'subscription_payment_failed',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-recovered.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-recovered.ts
index ab17ead23ca..53271bfb1fc 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-recovered.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-recovered.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionPaymentRecoveredTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionPaymentRecoveredTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_payment_recovered'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_payment_recovered'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_payment_recovered',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_payment_recovered'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_payment_recovered' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_payment_recovered' });
},
+ outputSchema: webhookSchemas.subscriptionInvoice,
sampleData: {
meta: {
event_name: 'subscription_payment_recovered',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-refunded.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-refunded.ts
index 3fbba790af9..f8686bfe723 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-refunded.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-refunded.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionPaymentRefundedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionPaymentRefundedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_payment_refunded'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_payment_refunded'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_payment_refunded',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_payment_refunded'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_payment_refunded' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_payment_refunded' });
},
+ outputSchema: webhookSchemas.subscriptionInvoice,
sampleData: {
meta: {
event_name: 'subscription_payment_refunded',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-success.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-success.ts
index 9b16fc647bc..3180dfffb54 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-success.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-payment-success.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionPaymentSuccessTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionPaymentSuccessTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_payment_success'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_payment_success'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_payment_success',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_payment_success'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_payment_success' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_payment_success' });
},
+ outputSchema: webhookSchemas.subscriptionInvoice,
sampleData: {
meta: {
event_name: 'subscription_payment_success',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-resumed.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-resumed.ts
index ca649609935..8aae9acd7d8 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-resumed.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-resumed.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionResumedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionResumedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_resumed'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_resumed'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_resumed',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_resumed'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_resumed' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_resumed' });
},
+ outputSchema: webhookSchemas.subscription,
sampleData: {
meta: {
event_name: 'subscription_resumed',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-unpaused.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-unpaused.ts
index f5669c1c57c..75da9cad080 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-unpaused.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-unpaused.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionUnpausedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionUnpausedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_unpaused'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_unpaused'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_unpaused',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_unpaused'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_unpaused' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_unpaused' });
},
+ outputSchema: webhookSchemas.subscription,
sampleData: {
meta: {
event_name: 'subscription_unpaused',
diff --git a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-updated.ts b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-updated.ts
index 8a53f59f733..53b7a1b133d 100644
--- a/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-updated.ts
+++ b/packages/pieces/community/lemon-squeezy/src/lib/triggers/subscription-updated.ts
@@ -1,6 +1,7 @@
import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { lemonSqueezyAuth } from '../common/auth';
-import { subscribeWebhook, unsubscribeWebhook, createStoreDropdownProperty, generateWebhookSecret, createWebhookTriggerKey } from '../common/webhook';
+import { createStoreDropdownProperty, disableWebhook, enableWebhook, handleWebhook } from '../common/webhook';
+import { webhookSchemas } from '../common/output-schemas';
export const subscriptionUpdatedTrigger = createTrigger({
auth: lemonSqueezyAuth,
@@ -16,32 +17,21 @@ export const subscriptionUpdatedTrigger = createTrigger({
store_id: createStoreDropdownProperty()
},
async onEnable(context) {
- const webhookSecret = generateWebhookSecret();
-
- const webhookData = await subscribeWebhook(
- context.auth.secret_text,
- context.propsValue.store_id as unknown as string,
- ['subscription_updated'],
- context.webhookUrl,
- webhookSecret
- );
-
- await context.store?.put(createWebhookTriggerKey('subscription_updated'), {
- webhookId: webhookData.data.id,
- secret: webhookSecret,
- storeId: context.propsValue.store_id
+ await enableWebhook({
+ auth: context.auth,
+ store: context.store,
+ storeId: context.propsValue.store_id,
+ webhookUrl: context.webhookUrl,
+ eventName: 'subscription_updated',
});
},
async onDisable(context) {
- const response: { webhookId: string } | null = await context.store?.get(createWebhookTriggerKey('subscription_updated'));
-
- if (response !== null && response !== undefined) {
- await unsubscribeWebhook(context.auth.secret_text, response.webhookId);
- }
+ await disableWebhook({ auth: context.auth, store: context.store, eventName: 'subscription_updated' });
},
async run(context) {
- return [context.payload.body];
+ return handleWebhook({ payload: context.payload, store: context.store, eventName: 'subscription_updated' });
},
+ outputSchema: webhookSchemas.subscription,
sampleData: {
meta: {
event_name: 'subscription_updated',
diff --git a/packages/pieces/community/lemon-squeezy/test/actions.test.ts b/packages/pieces/community/lemon-squeezy/test/actions.test.ts
new file mode 100644
index 00000000000..c89f6355bee
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/test/actions.test.ts
@@ -0,0 +1,333 @@
+import { getDiscount } from '../src/lib/actions/get-discount';
+import { listAffiliates } from '../src/lib/actions/list-affiliates';
+import { listDiscountRedemptions } from '../src/lib/actions/list-discount-redemptions';
+import { listLicenseKeyInstances } from '../src/lib/actions/list-license-key-instances';
+import { listSubscriptionItems } from '../src/lib/actions/list-subscription-items';
+import { validateLicense } from '../src/lib/actions/validate-license';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { lemonSqueezy } from '../src/index';
+import { createCheckout } from '../src/lib/actions/create-checkout';
+import { createCustomer } from '../src/lib/actions/create-customer';
+import { createDiscount } from '../src/lib/actions/create-discount';
+import { deleteDiscount } from '../src/lib/actions/delete-discount';
+import { findCustomerByEmail } from '../src/lib/actions/find-customer-by-email';
+import { generateOrderInvoice } from '../src/lib/actions/generate-order-invoice';
+import { getLicenseKey } from '../src/lib/actions/get-license-key';
+import { getOrder } from '../src/lib/actions/get-order';
+import { getOrderAi } from '../src/lib/actions/get-order-ai';
+import { listOrders } from '../src/lib/actions/list-orders';
+import { listSubscriptionsAi } from '../src/lib/actions/list-subscriptions-ai';
+import { cancelSubscription } from '../src/lib/actions/cancel-subscription';
+import { pauseSubscription } from '../src/lib/actions/pause-subscription';
+import { unpauseSubscription } from '../src/lib/actions/unpause-subscription';
+import { resumeSubscription } from '../src/lib/actions/resume-subscription';
+import { changeSubscriptionPlan } from '../src/lib/actions/change-subscription-plan';
+import { updateCustomer } from '../src/lib/actions/update-customer';
+import { updateLicenseKey } from '../src/lib/actions/update-license-key';
+import { lemonSqueezyAuth } from '../src/lib/common/auth';
+import { attributesOf, installFetch, jsonResponse, resource, runAction } from './helpers';
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('piece metadata', () => {
+ const actions = Object.values(lemonSqueezy.actions());
+ const triggers = Object.values(lemonSqueezy.triggers());
+
+ it('has 36 actions + custom API call and 16 triggers', () => {
+ expect(actions).toHaveLength(37);
+ expect(triggers).toHaveLength(16);
+ expect(lemonSqueezy.minimumSupportedRelease).toBe('0.88.2');
+ });
+
+ it('gives every action except Custom API Call and every trigger an outputSchema', () => {
+ for (const action of actions.filter((a) => a.name !== 'custom_api_call')) {
+ expect(action.outputSchema, action.name).toBeDefined();
+ }
+ for (const trigger of triggers) expect(trigger.outputSchema, trigger.name).toBeDefined();
+ });
+
+ it('has the expected audiences', () => {
+ const byAudience = (aud: string) => actions.filter((a) => Reflect.get(a, 'audience') === aud).map((a) => a.name).sort();
+ expect(byAudience('ai')).toEqual(['get_order_ai', 'list_subscriptions_ai']);
+ expect(byAudience('human')).toEqual(['change_subscription_plan', 'custom_api_call', 'get_order', 'list_subscriptions']);
+ });
+});
+
+describe('auth.validate', () => {
+ it('reports invalid only on 401/403', async () => {
+ installFetch({ 'GET /users/me': () => jsonResponse({ value: { errors: [{ detail: 'Unauthenticated.' }] }, status: 401 }) });
+ expect(await validate('bad')).toMatchObject({ valid: false, error: expect.stringContaining('Invalid API key') });
+ installFetch({ 'GET /users/me': () => jsonResponse({ value: {}, status: 503 }) });
+ expect(await validate('k')).toMatchObject({ valid: false, error: expect.stringContaining('Could not reach') });
+ installFetch({ 'GET /users/me': () => jsonResponse({ value: { meta: { test_mode: true }, data: { id: '1', type: 'users' } } }) });
+ expect(await validate('k')).toEqual({ valid: true });
+ });
+});
+
+describe('existing actions', () => {
+ it('get_order encodes the ID and refuses a path', async () => {
+ const { calls } = installFetch({ 'GET /orders/12': () => jsonResponse({ value: { data: resource({ type: 'orders', id: '12' }) } }) });
+ await runAction({ action: getOrder, props: { orderId: '12' } });
+ expect(calls[0].url.pathname).toBe('/v1/orders/12');
+ await expect(runAction({ action: getOrder, props: { orderId: '../webhooks' } })).rejects.toThrow(/numeric/);
+ });
+
+ it('list_orders validates paging and keeps the raw body', async () => {
+ const raw = { meta: { page: { currentPage: 1, lastPage: 1 } }, data: [] };
+ const { calls } = installFetch({ 'GET /orders': () => jsonResponse({ value: raw }) });
+ expect(await runAction({ action: listOrders, props: { userEmail: '[email protected]', page: 1, perPage: 5 } })).toEqual(raw);
+ expect(calls[0].url.search).toBe('?filter%5Buser_email%5D=a%40b.co&page%5Bnumber%5D=1&page%5Bsize%5D=5');
+ await expect(runAction({ action: listOrders, props: { page: 0 } })).rejects.toThrow(/Page/);
+ });
+
+ it('create_checkout sends the documented body', async () => {
+ const { calls } = installFetch({ 'POST /checkouts': () => jsonResponse({ value: { data: resource({ type: 'checkouts', id: 'c1', attributes: { url: 'https://x' } }) }, status: 201 }) });
+ await runAction({ action: createCheckout, props: {
+ storeId: '1',
+ variantId: '2',
+ customerEmail: '[email protected]',
+ customPrice: 999,
+ redirectUrl: 'https://ok.example',
+ expiresAt: '2026-12-31T23:59:59Z',
+ customData: { user_id: '7' },
+ } });
+ expect(calls[0].body).toEqual({
+ data: {
+ type: 'checkouts',
+ attributes: {
+ checkout_data: { email: '[email protected]', custom: { user_id: '7' } },
+ product_options: { redirect_url: 'https://ok.example' },
+ custom_price: 999,
+ expires_at: '2026-12-31T23:59:59.000Z',
+ },
+ relationships: { store: { data: { type: 'stores', id: '1' } }, variant: { data: { type: 'variants', id: '2' } } },
+ },
+ });
+ });
+
+ it('create_checkout rejects bad input before any request', async () => {
+ const { calls } = installFetch({});
+ await expect(runAction({ action: createCheckout, props: { storeId: '1', variantId: '2', expiresAt: 'tomorrow' } })).rejects.toThrow(/ISO 8601/);
+ await expect(runAction({ action: createCheckout, props: { storeId: '1', variantId: '2', customData: [1, 2] } })).rejects.toThrow(/JSON object/);
+ await expect(runAction({ action: createCheckout, props: { storeId: '1', variantId: '2', customPrice: 9.5 } })).rejects.toThrow(/cents/);
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('customers', () => {
+ it('find_customer_by_email returns found=false without error', async () => {
+ installFetch({ 'GET /customers': () => jsonResponse({ value: { meta: { page: { currentPage: 1, lastPage: 1, total: 0 } }, data: [] } }) });
+ expect(await runAction({ action: findCustomerByEmail, props: { email: '[email protected]' } })).toEqual({ found: false, customer: null, matches: [] });
+ });
+
+ it('create_customer posts to the store and flattens', async () => {
+ const { calls } = installFetch({ 'POST /customers': () => jsonResponse({ value: { data: resource({ type: 'customers', id: '9', attributes: { email: '[email protected]' } }) }, status: 201 }) });
+ expect(await runAction({ action: createCustomer, props: { storeId: '3', name: 'A', email: '[email protected]', country: 'us' } })).toEqual({ id: '9', email: '[email protected]' });
+ expect(calls[0].body).toEqual({
+ data: { type: 'customers', attributes: { name: 'A', email: '[email protected]', country: 'US' }, relationships: { store: { data: { type: 'stores', id: '3' } } } },
+ });
+ });
+
+ it('update_customer sends only provided fields and refuses an empty update', async () => {
+ const { calls } = installFetch({ 'PATCH /customers/9': () => jsonResponse({ value: { data: resource({ type: 'customers', id: '9', attributes: { status: 'archived' } }) } }) });
+ await runAction({ action: updateCustomer, props: { customerId: '9', archive: true } });
+ expect(calls[0].body).toEqual({ data: { type: 'customers', id: '9', attributes: { status: 'archived' } } });
+ await expect(runAction({ action: updateCustomer, props: { customerId: '9' } })).rejects.toThrow(/Nothing to update/);
+ });
+});
+
+describe('orders', () => {
+ it('get_order_ai includes order items', async () => {
+ const { calls } = installFetch({
+ 'GET /orders/5': () =>
+ jsonResponse({ value: { data: resource({ type: 'orders', id: '5', attributes: { total: 100 } }), included: [resource({ type: 'order-items', id: '8', attributes: { product_name: 'P' } })] } }),
+ });
+ expect(await runAction({ action: getOrderAi, props: { orderId: '5' } })).toEqual({ id: '5', total: 100, order_items: [{ id: '8', product_name: 'P' }] });
+ expect(calls[0].url.search).toBe('?include=order-items');
+ });
+
+ it('generate_order_invoice returns the download URL', async () => {
+ const { calls } = installFetch({
+ 'POST /orders/5/generate-invoice': () => jsonResponse({ value: { meta: { urls: { download_invoice: 'https://app.lemonsqueezy.com/i.pdf' } } } }),
+ });
+ expect(await runAction({ action: generateOrderInvoice, props: { orderId: '5', name: 'A', address: 'St 1', city: 'C', zipCode: '1', country: 'de' } })).toEqual({
+ order_id: '5',
+ invoice_url: 'https://app.lemonsqueezy.com/i.pdf',
+ });
+ expect(calls[0].url.searchParams.get('country')).toBe('DE');
+ });
+});
+
+describe('subscriptions', () => {
+ it('cancel uses DELETE; resume/pause/unpause PATCH the documented attributes', async () => {
+ const sub = () => jsonResponse({ value: { data: resource({ type: 'subscriptions', id: '4', attributes: { status: 'active' } }) } });
+ const { calls } = installFetch({ 'DELETE /subscriptions/4': sub, 'PATCH /subscriptions/4': sub });
+ await runAction({ action: cancelSubscription, props: { subscriptionId: '4' } });
+ await runAction({ action: resumeSubscription, props: { subscriptionId: '4' } });
+ await runAction({ action: pauseSubscription, props: { subscriptionId: '4', mode: 'free', resumesAt: '2026-12-01' } });
+ await runAction({ action: unpauseSubscription, props: { subscriptionId: '4' } });
+ expect(calls[0].method).toBe('DELETE');
+ expect(calls.slice(1).map((c) => attributesOf(c))).toEqual([
+ { cancelled: false },
+ { pause: { mode: 'free', resumes_at: '2026-12-01T00:00:00.000Z' } },
+ { pause: null },
+ ]);
+ });
+
+ it('change plan refuses conflicting proration options', async () => {
+ installFetch({});
+ await expect(runAction({ action: changeSubscriptionPlan, props: { subscriptionId: '4', variantId: '2', invoiceImmediately: true, disableProrations: true } })).rejects.toThrow(/either/);
+ });
+
+ it('list_subscriptions_ai validates ID filters and returns has_more', async () => {
+ const { calls } = installFetch({
+ 'GET /subscriptions': () => jsonResponse({ value: { meta: { page: { currentPage: 1, lastPage: 3, perPage: 10, total: 25 } }, data: [resource({ type: 'subscriptions', id: '1' })] } }),
+ });
+ expect(await runAction({ action: listSubscriptionsAi, props: { productId: '7', status: 'active' } })).toMatchObject({ has_more: true, total: 25, items: [{ id: '1' }] });
+ expect(calls[0].url.search).toBe('?filter%5Bproduct_id%5D=7&filter%5Bstatus%5D=active');
+ await expect(runAction({ action: listSubscriptionsAi, props: { storeId: 'abc' } })).rejects.toThrow(/numeric/);
+ });
+});
+
+describe('discounts', () => {
+ it('create_discount validates and posts', async () => {
+ const { calls } = installFetch({ 'POST /discounts': () => jsonResponse({ value: { data: resource({ type: 'discounts', id: '3', attributes: { code: 'SAVE10' } }) }, status: 201 }) });
+ await runAction({ action: createDiscount, props: { storeId: '1', name: 'Ten', code: 'SAVE10', amountType: 'percent', amount: 10, maxRedemptions: 5, duration: 'repeating', durationInMonths: 3 } });
+ expect(attributesOf(calls[0])).toEqual({
+ name: 'Ten', code: 'SAVE10', amount: 10, amount_type: 'percent', is_limited_redemptions: true, max_redemptions: 5, duration: 'repeating', duration_in_months: 3,
+ });
+ await expect(runAction({ action: createDiscount, props: { storeId: '1', name: 'x', code: 'bad code', amountType: 'percent', amount: 10 } })).rejects.toThrow(/Code/);
+ await expect(runAction({ action: createDiscount, props: { storeId: '1', name: 'x', code: 'OK1', amountType: 'percent', amount: 150 } })).rejects.toThrow(/percent/);
+ await expect(runAction({ action: createDiscount, props: { storeId: '1', name: 'x', code: 'OK1', amountType: 'fixed', amount: 5, duration: 'repeating' } })).rejects.toThrow(/Months/);
+ });
+
+ it('delete_discount treats 404 as already deleted', async () => {
+ installFetch({ 'DELETE /discounts/3': () => jsonResponse({ value: null, status: 204 }), 'DELETE /discounts/4': () => jsonResponse({ value: { errors: [{ detail: 'nf' }] }, status: 404 }) });
+ expect(await runAction({ action: deleteDiscount, props: { discountId: '3' } })).toEqual({ id: '3', deleted: true, already_deleted: false });
+ expect(await runAction({ action: deleteDiscount, props: { discountId: '4' } })).toEqual({ id: '4', deleted: true, already_deleted: true });
+ });
+});
+
+describe('license keys', () => {
+ it('get_license_key by key resolves the ID then reads it with auth', async () => {
+ const { calls } = installFetch({
+ 'POST /licenses/validate': () => jsonResponse({ value: { valid: true, license_key: { id: 11 } } }),
+ 'GET /license-keys/11': () => jsonResponse({ value: { data: resource({ type: 'license-keys', id: '11', attributes: { key: 'ABC' } }) } }),
+ });
+ expect(await runAction({ action: getLicenseKey, props: { licenseKey: 'ABC' } })).toEqual({ found: true, license_key: { id: '11', key: 'ABC' } });
+ expect(calls[0].body).toBe('license_key=ABC');
+ expect(calls[0].headers['authorization']).toBeUndefined();
+ });
+
+ it('get_license_key looks the key up when the ID field arrives blank', async () => {
+ const { calls } = installFetch({
+ 'POST /licenses/validate': () => jsonResponse({ value: { valid: true, license_key: { id: 11 } } }),
+ 'GET /license-keys/11': () => jsonResponse({ value: { data: resource({ type: 'license-keys', id: '11' }) } }),
+ });
+ expect(await runAction({ action: getLicenseKey, props: { licenseKeyId: ' ', licenseKey: 'ABC' } })).toEqual({ found: true, license_key: { id: '11' } });
+ expect(calls).toHaveLength(2);
+ });
+
+ it('get_license_key returns found=false for an unknown key and needs exactly one input', async () => {
+ installFetch({ 'POST /licenses/validate': () => jsonResponse({ value: { valid: false, error: 'license_key not found.', license_key: null }, status: 404 }) });
+ expect(await runAction({ action: getLicenseKey, props: { licenseKey: 'NOPE' } })).toEqual({ found: false, license_key: null });
+ await expect(runAction({ action: getLicenseKey, props: {} })).rejects.toThrow(/exactly one/);
+ await expect(runAction({ action: getLicenseKey, props: { licenseKey: 'A', licenseKeyId: '1' } })).rejects.toThrow(/exactly one/);
+ });
+
+ it('update_license_key has three states per field', async () => {
+ const { calls } = installFetch({ 'PATCH /license-keys/11': () => jsonResponse({ value: { data: resource({ type: 'license-keys', id: '11' }) } }) });
+ await runAction({ action: updateLicenseKey, props: { licenseKeyId: '11', unlimitedActivations: true, neverExpires: true, disabled: 'disable' } });
+ await runAction({ action: updateLicenseKey, props: { licenseKeyId: '11', activationLimit: 3, expiresAt: '2027-01-31T00:00:00Z' } });
+ expect(calls.map((c) => attributesOf(c))).toEqual([
+ { activation_limit: null, expires_at: null, disabled: true },
+ { activation_limit: 3, expires_at: '2027-01-31T00:00:00.000Z' },
+ ]);
+ await expect(runAction({ action: updateLicenseKey, props: { licenseKeyId: '11' } })).rejects.toThrow(/Nothing/);
+ await expect(runAction({ action: updateLicenseKey, props: { licenseKeyId: '11', activationLimit: 2, unlimitedActivations: true } })).rejects.toThrow(/either/);
+ });
+});
+
+describe('gap actions', () => {
+ const page = { meta: { page: { currentPage: 1, lastPage: 1, perPage: 10, total: 1 } } };
+
+ it('get_discount reads one discount by numeric ID', async () => {
+ const { calls } = installFetch({ 'GET /discounts/3': () => jsonResponse({ value: { data: resource({ type: 'discounts', id: '3', attributes: { code: 'SAVE10' } }) } }) });
+ expect(await runAction({ action: getDiscount, props: { discountId: '3' } })).toEqual({ id: '3', code: 'SAVE10' });
+ expect(calls[0].method).toBe('GET');
+ await expect(runAction({ action: getDiscount, props: { discountId: 'SAVE10' } })).rejects.toThrow(/numeric/);
+ });
+
+ it('list_license_key_instances filters by license key', async () => {
+ const { calls } = installFetch({
+ 'GET /license-key-instances': () => jsonResponse({ value: { ...page, data: [resource({ type: 'license-key-instances', id: '9', attributes: { name: 'laptop' } })] } }),
+ });
+ expect(await runAction({ action: listLicenseKeyInstances, props: { licenseKeyId: '11' } })).toMatchObject({ items: [{ id: '9', name: 'laptop' }], total: 1 });
+ expect(calls[0].url.searchParams.get('filter[license_key_id]')).toBe('11');
+ });
+
+ it('list_affiliates filters by store and email', async () => {
+ const { calls } = installFetch({ 'GET /affiliates': () => jsonResponse({ value: { ...page, data: [] } }) });
+ await runAction({ action: listAffiliates, props: { storeId: '5', userEmail: ' [email protected] ', perPage: 20 } });
+ expect(calls[0].url.searchParams.get('filter[store_id]')).toBe('5');
+ expect(calls[0].url.searchParams.get('filter[user_email]')).toBe('[email protected]');
+ expect(calls[0].url.searchParams.get('page[size]')).toBe('20');
+ });
+
+ it('list_discount_redemptions filters by discount and order', async () => {
+ const { calls } = installFetch({ 'GET /discount-redemptions': () => jsonResponse({ value: { ...page, data: [] } }) });
+ await runAction({ action: listDiscountRedemptions, props: { discountId: '3', orderId: '7' } });
+ expect(calls[0].url.searchParams.get('filter[discount_id]')).toBe('3');
+ expect(calls[0].url.searchParams.get('filter[order_id]')).toBe('7');
+ await expect(runAction({ action: listDiscountRedemptions, props: { orderId: '#7' } })).rejects.toThrow(/numeric/);
+ });
+
+ it('list_subscription_items filters by subscription', async () => {
+ const { calls } = installFetch({
+ 'GET /subscription-items': () => jsonResponse({ value: { ...page, data: [resource({ type: 'subscription-items', id: '4', attributes: { quantity: 2 } })] } }),
+ });
+ expect(await runAction({ action: listSubscriptionItems, props: { subscriptionId: '2601139' } })).toMatchObject({ items: [{ id: '4', quantity: 2 }] });
+ expect(calls[0].url.searchParams.get('filter[subscription_id]')).toBe('2601139');
+ });
+
+ it('validate_license posts the key form-encoded without auth and never returns the key', async () => {
+ const { calls } = installFetch({
+ 'POST /licenses/validate': () =>
+ jsonResponse({
+ value: {
+ valid: true,
+ error: null,
+ license_key: { id: 11, status: 'inactive', key: 'SECRET-KEY', activation_limit: 3, activation_usage: 0, expires_at: null, created_at: '2026-10-12T00:00:00Z', test_mode: true },
+ instance: null,
+ meta: { store_id: 5, product_name: 'P', customer_email: '[email protected]' },
+ },
+ }),
+ });
+ const result = await runAction({ action: validateLicense, props: { licenseKey: ' SECRET-KEY ', instanceId: 'inst-1' } });
+ expect(result).toMatchObject({ valid: true, error: null, license_key: { id: 11, activation_limit: 3 }, instance: null, meta: { store_id: 5 } });
+ expect(JSON.stringify(result)).not.toContain('SECRET-KEY');
+ expect(calls[0].body).toBe('license_key=SECRET-KEY&instance_id=inst-1');
+ expect(calls[0].headers['authorization']).toBeUndefined();
+ expect(calls).toHaveLength(1);
+ });
+
+ it('validate_license reports an unknown key as invalid, not as a failure', async () => {
+ installFetch({ 'POST /licenses/validate': () => jsonResponse({ value: { valid: false, error: 'license_key not found.', license_key: null }, status: 404 }) });
+ expect(await runAction({ action: validateLicense, props: { licenseKey: 'NOPE' } })).toEqual({
+ valid: false,
+ error: 'license_key not found.',
+ license_key: null,
+ instance: null,
+ meta: null,
+ });
+ });
+
+ it('validate_license fails on a server error', async () => {
+ installFetch({ 'POST /licenses/validate': () => jsonResponse({ value: {}, status: 500 }) });
+ await expect(runAction({ action: validateLicense, props: { licenseKey: 'K' } })).rejects.toThrow(/500/);
+ });
+});
+
+function validate(auth: string) {
+ return lemonSqueezyAuth.validate?.({ auth, server: { apiUrl: 'http://localhost:3000', publicUrl: 'http://localhost:4200', mintOidcToken: async () => '' } });
+}
diff --git a/packages/pieces/community/lemon-squeezy/test/client.test.ts b/packages/pieces/community/lemon-squeezy/test/client.test.ts
new file mode 100644
index 00000000000..e6358083067
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/test/client.test.ts
@@ -0,0 +1,135 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { LemonSqueezyApiError, buildQueryString, lsRequest, listAllPages, numericId, pageParams, seg } from '../src/lib/common/client';
+import { lemonSqueezyAuth } from '../src/lib/common/auth';
+import { storeOptions } from '../src/lib/common/props';
+import { installFetch, jsonResponse } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe('IDs and query building', () => {
+ it('accepts numeric IDs and rejects path tricks', () => {
+ expect(seg({ value: '123', label: 'X' })).toBe('123');
+ expect(seg({ value: 45, label: 'X' })).toBe('45');
+ expect(numericId({ value: ' 7 ', label: 'X' })).toBe('7');
+ for (const bad of ['../webhooks', '1/../2', '1?x=1', '0', '-1', 'abc', '', '1.5', '%2e%2e', undefined]) {
+ expect(() => seg({ value: bad, label: 'Order' })).toThrow(/Order must be a numeric/);
+ }
+ });
+
+ it('keeps brackets in keys and encodes values, skipping empties', () => {
+ expect(buildQueryString({ 'filter[user_email]': '[email protected]', 'filter[x]': undefined, y: '' })).toBe('?filter[user_email]=a%2Bb%40x.com');
+ });
+
+ it('validates page and per page', () => {
+ expect(pageParams({ page: 2, perPage: 100 })).toEqual({ 'page[number]': '2', 'page[size]': '100' });
+ expect(pageParams({})).toEqual({});
+ expect(() => pageParams({ page: 0 })).toThrow(/Page/);
+ expect(() => pageParams({ page: -3 })).toThrow(/Page/);
+ expect(() => pageParams({ perPage: 101 })).toThrow(/Per Page/);
+ expect(() => pageParams({ perPage: 2.5 })).toThrow(/Per Page/);
+ });
+});
+
+describe('lsRequest', () => {
+ it('sends JSON:API headers to the fixed base URL', async () => {
+ const { calls } = installFetch({ 'GET /stores': () => jsonResponse({ value: { data: [] } }) });
+ await lsRequest({ apiKey: ' key ', method: 'GET', path: '/stores', query: { 'page[size]': '5' } });
+ expect(calls[0].url.toString()).toBe('https://api.lemonsqueezy.com/v1/stores?page%5Bsize%5D=5');
+ expect(calls[0].headers['authorization']).toBe('Bearer key');
+ expect(calls[0].headers['accept']).toBe('application/vnd.api+json');
+ });
+
+ it('refuses paths that could leave the API', async () => {
+ installFetch({});
+ await expect(lsRequest({ apiKey: 'k', method: 'GET', path: '//evil.io/x' })).rejects.toThrow(/Invalid/);
+ await expect(lsRequest({ apiKey: 'k', method: 'GET', path: 'stores' })).rejects.toThrow(/Invalid/);
+ await expect(lsRequest({ apiKey: 'k', method: 'GET', path: '/a/../b' })).rejects.toThrow(/Invalid/);
+ });
+
+ it('maps JSON:API errors to a readable message with status and responseBody', async () => {
+ installFetch({ 'GET /orders/9': () => jsonResponse({ value: { errors: [{ detail: 'The order was not found.' }] }, status: 404 }) });
+ const error = await lsRequest({ apiKey: 'k', method: 'GET', path: '/orders/9' }).catch((e) => e);
+ expect(error).toBeInstanceOf(LemonSqueezyApiError);
+ expect(error.status).toBe(404);
+ expect(error.message).toContain('The order was not found.');
+ expect(error.responseBody).toEqual({ errors: [{ detail: 'The order was not found.' }] });
+ expect('body' in error).toBe(false);
+ });
+
+ it('retries 429 at most twice, waiting 20 s then 40 s for the one-minute window', async () => {
+ vi.useFakeTimers();
+ let n = 0;
+ installFetch({ 'GET /stores': () => (++n < 3 ? jsonResponse({ value: {}, status: 429 }) : jsonResponse({ value: { data: [] } })) });
+ const promise = lsRequest({ apiKey: 'k', method: 'GET', path: '/stores' });
+ await vi.advanceTimersByTimeAsync(19_999);
+ expect(n).toBe(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(n).toBe(2);
+ await vi.advanceTimersByTimeAsync(39_999);
+ expect(n).toBe(2);
+ await vi.advanceTimersByTimeAsync(1);
+ await expect(promise).resolves.toEqual({ status: 200, body: { data: [] } });
+ expect(n).toBe(3);
+ });
+
+ it('does not retry 429 for connection checks and dropdowns (they must finish well inside 60 s)', async () => {
+ vi.useFakeTimers();
+ let n = 0;
+ installFetch({
+ 'GET /users/me': () => {
+ n++;
+ return jsonResponse({ value: {}, status: 429 });
+ },
+ 'GET /stores': () => {
+ n++;
+ return jsonResponse({ value: {}, status: 429 });
+ },
+ });
+ const started = Date.now();
+ const validation = await validate('k');
+ expect(validation).toMatchObject({ valid: false, error: expect.stringContaining('rate limit') });
+ const dropdown = await storeOptions({ auth: { secret_text: 'k' } });
+ expect(dropdown).toMatchObject({ disabled: true, placeholder: expect.stringContaining('rate limit') });
+ expect(n).toBe(2);
+ expect(Date.now() - started).toBe(0);
+ });
+
+ it('fails after the retries are used up', async () => {
+ vi.useFakeTimers();
+ installFetch({ 'GET /stores': () => jsonResponse({ value: {}, status: 429 }) });
+ const promise = lsRequest({ apiKey: 'k', method: 'GET', path: '/stores' }).catch((e) => e);
+ await vi.runAllTimersAsync();
+ expect((await promise).status).toBe(429);
+ });
+
+ it('treats a redirect as an error and handles 204', async () => {
+ installFetch({
+ 'GET /x': () => new Response(null, { status: 302, headers: { location: 'https://evil.io' } }),
+ 'DELETE /discounts/1': () => jsonResponse({ value: null, status: 204 }),
+ });
+ await expect(lsRequest({ apiKey: 'k', method: 'GET', path: '/x' })).rejects.toThrow(/redirect/);
+ await expect(lsRequest({ apiKey: 'k', method: 'DELETE', path: '/discounts/1' })).resolves.toEqual({ status: 204, body: undefined });
+ });
+});
+
+describe('listAllPages', () => {
+ it('follows pages to the end and flags truncation at the cap', async () => {
+ const { calls } = installFetch({
+ 'GET /stores': (call) => {
+ const page = Number(call.url.searchParams.get('page[number]'));
+ return jsonResponse({ value: { meta: { page: { currentPage: page, lastPage: 12 } }, data: [{ id: String(page), type: 'stores' }] } });
+ },
+ });
+ const result = await listAllPages({ apiKey: 'k', path: '/stores' });
+ expect(result.items).toHaveLength(10);
+ expect(result.truncated).toBe(true);
+ expect(calls).toHaveLength(10);
+ });
+});
+
+function validate(auth: string) {
+ return lemonSqueezyAuth.validate?.({ auth, server: { apiUrl: 'http://localhost:3000', publicUrl: 'http://localhost:4200', mintOidcToken: async () => '' } });
+}
diff --git a/packages/pieces/community/lemon-squeezy/test/helpers.ts b/packages/pieces/community/lemon-squeezy/test/helpers.ts
new file mode 100644
index 00000000000..e4a6011c517
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/test/helpers.ts
@@ -0,0 +1,78 @@
+import { vi } from 'vitest';
+import { readPath } from '../src/lib/common/client';
+
+export function jsonResponse({ value, status = 200, headers = {} }: { value: unknown; status?: number; headers?: Record<string, string> }): Response {
+ return new Response(status === 204 ? null : JSON.stringify(value), {
+ status,
+ headers: { 'content-type': 'application/vnd.api+json', ...headers },
+ });
+}
+
+export function installFetch(routes: Record<string, Handler>) {
+ const calls: Call[] = [];
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(String(input));
+ const method = (init?.method ?? 'GET').toUpperCase();
+ const raw = typeof init?.body === 'string' ? init.body : undefined;
+ const call: Call = { method, url, body: parseBody(raw), headers: headersOf(init?.headers) };
+ calls.push(call);
+ const handler = routes[`${method} ${url.pathname.replace(/^\/v1/, '')}`];
+ if (!handler) return jsonResponse({ value: { errors: [{ detail: `no fake for ${method} ${url.pathname}` }] }, status: 501 });
+ return handler(call);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return { calls, fetchMock };
+}
+
+export function memoryStore(initial: Record<string, unknown> = {}) {
+ const data = new Map<string, unknown>(Object.entries(initial));
+ return {
+ data,
+ get: async <T>(key: string): Promise<T | null> => {
+ const value: unknown = data.get(key);
+ return value === undefined ? null : identity<T>(value);
+ },
+ put: async <T>(key: string, value: T) => {
+ data.set(key, value);
+ return value;
+ },
+ delete: async (key: string) => {
+ data.delete(key);
+ },
+ };
+}
+
+export async function runAction({ action, props }: { action: { run: unknown }; props: Record<string, unknown> }) {
+ return Reflect.apply(Function.prototype.call, action.run, [action, { auth: AUTH, propsValue: props, store: memoryStore() }]);
+}
+
+export function resource({ type, id, attributes = {} }: { type: string; id: string; attributes?: Record<string, unknown> }) {
+ return { type, id, attributes };
+}
+
+export function attributesOf(call: Call): unknown {
+ return readPath({ value: call.body, path: ['data', 'attributes'] });
+}
+
+export const AUTH = { secret_text: 'test-key', type: 'SECRET_TEXT' };
+
+function parseBody(raw: string | undefined): unknown {
+ if (!raw) return undefined;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return raw;
+ }
+}
+
+function headersOf(headers: RequestInit['headers']): Record<string, string> {
+ return Object.fromEntries(new Headers(headers ?? {}).entries());
+}
+
+function identity<T>(value: unknown): T {
+ return Reflect.apply((v: unknown) => v, undefined, [value]);
+}
+
+export type Call = { method: string; url: URL; body: unknown; headers: Record<string, string> };
+
+type Handler = (call: Call) => Response | Promise<Response>;
diff --git a/packages/pieces/community/lemon-squeezy/test/webhook.test.ts b/packages/pieces/community/lemon-squeezy/test/webhook.test.ts
new file mode 100644
index 00000000000..85853669362
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/test/webhook.test.ts
@@ -0,0 +1,166 @@
+import { createHmac } from 'crypto';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ createWebhookTriggerKey,
+ disableWebhook,
+ enableWebhook,
+ generateWebhookSecret,
+ handleWebhook,
+ verifyLemonSqueezySignature,
+} from '../src/lib/common/webhook';
+import { readPath } from '../src/lib/common/client';
+import { orderCreatedTrigger } from '../src/lib/triggers/order-created';
+import { AUTH, installFetch, jsonResponse, memoryStore } from './helpers';
+
+afterEach(() => vi.unstubAllGlobals());
+
+const SECRET = 'a'.repeat(40);
+const EVENT = 'order_created';
+
+describe('signature verification', () => {
+ it('accepts a valid HMAC-SHA256 of the raw body (string or Buffer)', () => {
+ const raw = delivery({});
+ expect(verifyLemonSqueezySignature({ secret: SECRET, signature: sign({ raw }), rawBody: raw })).toBe(true);
+ expect(verifyLemonSqueezySignature({ secret: SECRET, signature: sign({ raw }), rawBody: Buffer.from(raw) })).toBe(true);
+ });
+
+ it('rejects forged, missing, malformed or wrong-length signatures', () => {
+ const raw = delivery({});
+ expect(verifyLemonSqueezySignature({ secret: SECRET, signature: sign({ raw, secret: 'other' }), rawBody: raw })).toBe(false);
+ expect(verifyLemonSqueezySignature({ secret: SECRET, signature: undefined, rawBody: raw })).toBe(false);
+ expect(verifyLemonSqueezySignature({ secret: SECRET, signature: 'zz', rawBody: raw })).toBe(false);
+ expect(verifyLemonSqueezySignature({ secret: SECRET, signature: sign({ raw }).slice(0, 10), rawBody: raw })).toBe(false);
+ expect(verifyLemonSqueezySignature({ secret: undefined, signature: sign({ raw }), rawBody: raw })).toBe(false);
+ expect(verifyLemonSqueezySignature({ secret: SECRET, signature: sign({ raw }), rawBody: undefined })).toBe(false);
+ expect(verifyLemonSqueezySignature({ secret: SECRET, signature: sign({ raw }), rawBody: raw + ' ' })).toBe(false);
+ });
+});
+
+describe('handleWebhook', () => {
+ it('emits a signed delivery once and drops the replay', async () => {
+ const store = storeWithSecret();
+ const raw = delivery({});
+ expect(await handleWebhook({ ...signed({ raw }), store, eventName: EVENT })).toEqual([JSON.parse(raw)]);
+ expect(await handleWebhook({ ...signed({ raw }), store, eventName: EVENT })).toEqual([]);
+ const later = delivery({ updatedAt: '2026-10-12T11:00:00.000000Z' });
+ expect(await handleWebhook({ ...signed({ raw: later }), store, eventName: EVENT })).toHaveLength(1);
+ });
+
+ it('drops forged and unsigned deliveries', async () => {
+ const raw = delivery({});
+ expect(await handleWebhook({ ...signed({ raw, secret: 'attacker' }), store: storeWithSecret(), eventName: EVENT })).toEqual([]);
+ expect(await handleWebhook({ payload: { body: JSON.parse(raw), rawBody: raw, headers: {} }, store: storeWithSecret(), eventName: EVENT })).toEqual([]);
+ });
+
+ it('drops a signed delivery for another event', async () => {
+ const raw = delivery({ event: 'order_refunded' });
+ expect(await handleWebhook({ ...signed({ raw }), store: storeWithSecret(), eventName: EVENT })).toEqual([]);
+ });
+
+ it('bounds the dedupe list', async () => {
+ const store = storeWithSecret();
+ for (let i = 1; i <= 205; i++) {
+ await handleWebhook({ ...signed({ raw: delivery({ id: String(i) }) }), store, eventName: EVENT });
+ }
+ const seen = store.data.get('_order_created_seen');
+ expect(Array.isArray(seen) ? seen.length : 0).toBe(200);
+ });
+
+ it('is wired into the triggers', async () => {
+ const raw = delivery({});
+ const context = { ...signed({ raw, secret: 'attacker' }), store: storeWithSecret() };
+ expect(await Reflect.apply(orderCreatedTrigger.run, orderCreatedTrigger, [context])).toEqual([]);
+ });
+});
+
+describe('enable / disable', () => {
+ it('creates the webhook in the key mode with a 40-character random secret', async () => {
+ const { calls } = installFetch({
+ 'GET /users/me': () => jsonResponse({ value: { meta: { test_mode: true }, data: { id: '1', type: 'users' } } }),
+ 'POST /webhooks': () => jsonResponse({ value: { data: { id: '77', type: 'webhooks' } }, status: 201 }),
+ });
+ const store = memoryStore();
+ await enableWebhook({ auth: AUTH, store, storeId: '5', webhookUrl: 'https://ap.test/hook', eventName: EVENT });
+ const attributes = readPath({ value: calls[1].body, path: ['data', 'attributes'] });
+ expect(readPath({ value: attributes, path: ['test_mode'] })).toBe(true);
+ expect(readPath({ value: attributes, path: ['events'] })).toEqual([EVENT]);
+ const secret = readPath({ value: attributes, path: ['secret'] });
+ expect(secret).toMatch(/^[0-9a-f]{40}$/);
+ expect(readPath({ value: calls[1].body, path: ['data', 'relationships', 'store', 'data', 'id'] })).toBe('5');
+ expect(store.data.get('_order_created_trigger')).toMatchObject({ webhookId: '77', secret, testMode: true });
+ });
+
+ it('keeps the signing secret out of error logs when creating the webhook fails', async () => {
+ installFetch({
+ 'GET /users/me': () => jsonResponse({ value: { meta: { test_mode: true } } }),
+ 'POST /webhooks': () => jsonResponse({ value: { errors: [{ detail: 'The url field is invalid.' }] }, status: 422 }),
+ });
+ const logSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ const error = await enableWebhook({ auth: AUTH, store: memoryStore(), storeId: '5', webhookUrl: 'u', eventName: EVENT }).catch((e) => e);
+ const logged = JSON.stringify(logSpy.mock.calls.map((call) => call.map((arg) => (arg instanceof Error ? arg.message : arg))));
+ logSpy.mockRestore();
+ expect(error.message).toContain('The url field is invalid.');
+ expect(logged).not.toMatch(/[0-9a-f]{40}/);
+ expect(logged).not.toContain('"secret"');
+ });
+
+ it('uses live mode for a live key', async () => {
+ const { calls } = installFetch({
+ 'GET /users/me': () => jsonResponse({ value: { meta: { test_mode: false }, data: { id: '1', type: 'users' } } }),
+ 'POST /webhooks': () => jsonResponse({ value: { data: { id: '77', type: 'webhooks' } }, status: 201 }),
+ });
+ await enableWebhook({ auth: AUTH, store: memoryStore(), storeId: '5', webhookUrl: 'https://ap.test/hook', eventName: EVENT });
+ expect(readPath({ value: calls[1].body, path: ['data', 'attributes', 'test_mode'] })).toBe(false);
+ });
+
+ it('deletes the new webhook when saving it fails', async () => {
+ const { calls } = installFetch({
+ 'GET /users/me': () => jsonResponse({ value: { meta: { test_mode: true } } }),
+ 'POST /webhooks': () => jsonResponse({ value: { data: { id: '77', type: 'webhooks' } }, status: 201 }),
+ 'DELETE /webhooks/77': () => jsonResponse({ value: null, status: 204 }),
+ });
+ const store = {
+ ...memoryStore(),
+ put: async () => {
+ throw new Error('store down');
+ },
+ };
+ await expect(enableWebhook({ auth: AUTH, store, storeId: '5', webhookUrl: 'u', eventName: EVENT })).rejects.toThrow('store down');
+ expect(calls.map((c) => `${c.method} ${c.url.pathname}`)).toContain('DELETE /v1/webhooks/77');
+ });
+
+ it('generates different 40-character secrets (Lemon Squeezy max)', () => {
+ expect(generateWebhookSecret()).toHaveLength(40);
+ expect(generateWebhookSecret()).not.toBe(generateWebhookSecret());
+ });
+
+ it('treats a 404 on delete as already removed and clears state', async () => {
+ installFetch({ 'DELETE /webhooks/77': () => jsonResponse({ value: { errors: [{ detail: 'Not found' }] }, status: 404 }) });
+ const store = memoryStore({ _order_created_trigger: { webhookId: '77', secret: SECRET, storeId: '5' }, _order_created_seen: ['x'] });
+ await disableWebhook({ auth: AUTH, store, eventName: EVENT });
+ expect(store.data.size).toBe(0);
+ });
+
+ it('keeps state when delete fails for another reason', async () => {
+ installFetch({ 'DELETE /webhooks/77': () => jsonResponse({ value: {}, status: 500 }) });
+ const store = memoryStore({ _order_created_trigger: { webhookId: '77', secret: SECRET, storeId: '5' } });
+ await expect(disableWebhook({ auth: AUTH, store, eventName: EVENT })).rejects.toThrow(/500/);
+ expect(store.data.has('_order_created_trigger')).toBe(true);
+ });
+});
+
+function sign({ raw, secret = SECRET }: { raw: string; secret?: string }): string {
+ return createHmac('sha256', secret).update(raw).digest('hex');
+}
+
+function delivery({ event = EVENT, id = '42', updatedAt = '2026-10-12T10:00:00.000000Z' }: { event?: string; id?: string; updatedAt?: string }): string {
+ return JSON.stringify({ meta: { event_name: event, test_mode: true }, data: { type: 'orders', id, attributes: { updated_at: updatedAt } } });
+}
+
+function signed({ raw, secret }: { raw: string; secret?: string }) {
+ return { payload: { body: JSON.parse(raw), rawBody: raw, headers: { 'X-Signature': sign({ raw, secret }) } } };
+}
+
+function storeWithSecret() {
+ return memoryStore({ [createWebhookTriggerKey(EVENT)]: { webhookId: '1', secret: SECRET, storeId: '5' } });
+}
diff --git a/packages/pieces/community/lemon-squeezy/vitest.config.ts b/packages/pieces/community/lemon-squeezy/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/lemon-squeezy/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})