================ CODE SNIPPETS ================ TITLE: Install Autumn npm Packages DESCRIPTION: Installs the necessary autumn-js and @useautumn/convex packages using npm, pnpm, yarn, or bun. SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: bash CODE: ``` npm install autumn-js @useautumn/convex ``` -------------------------------- TITLE: Frontend AutumnProvider Setup DESCRIPTION: Sets up the AutumnProvider on the frontend in AutumnWrapper.tsx to enable React hooks and components, connecting them to the Convex backend. SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: typescript CODE: ``` "use client"; import { AutumnProvider } from "autumn-js/react"; import { api } from "../convex/_generated/api"; import { useConvex } from "convex/react"; export function AutumnWrapper({ children }: { children: React.ReactNode }) { const convex = useConvex(); return ( {children} ); } ``` -------------------------------- TITLE: Install Autumn JS SDK DESCRIPTION: Installs the `autumn-js` package using npm. This is required for both backend and frontend integration. SOURCE: https://docs.useautumn.com/setup LANGUAGE: bash CODE: ``` npm install autumn-js ``` -------------------------------- TITLE: Upgrade User with useCustomer Hook DESCRIPTION: Demonstrates using the useCustomer hook from autumn-js/react to trigger a checkout process for upgrading a user to a 'pro' product. SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: typescript CODE: ``` import { useCustomer, CheckoutDialog } from "autumn-js/react"; export default function Home() { const { customer, track, check, checkout } = useCustomer(); return ( ); } ``` -------------------------------- TITLE: Initialize Autumn Client in Convex DESCRIPTION: Initializes the Autumn client in convex/autumn.ts, configuring it with Convex components and a custom identify function to map users to customers. SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: typescript CODE: ``` import { components } from "./_generated/api"; import { Autumn } from "@useautumn/convex"; export const autumn = new Autumn(components.autumn, { secretKey: process.env.AUTUMN_SECRET_KEY ?? "", identify: async (ctx: any) => { const user = await ctx.auth.getUserIdentity(); if (!user) return null; const userId = user.subject.split("|")[0]; return { customerId: user.subject as string, customerData: { name: user.name as string, email: user.email as string, }, }; }, }); /** * These exports are required for our react hooks and components */ export const { track, cancel, query, attach, check, checkout, usage, setupPayment, createCustomer, listProducts, billingPortal, createReferralCode, redeemReferralCode, createEntity, getEntity, } = autumn.api(); ``` -------------------------------- TITLE: Display Pricing Table Component DESCRIPTION: Renders the PricingTable component from autumn-js/react in the main page component (src/app/page.tsx). SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: typescript CODE: ``` import { PricingTable } from "autumn-js/react"; export default function Home() { return ( ); } ``` -------------------------------- TITLE: shadcn/ui Pricing Table Installation DESCRIPTION: Installs the pricing-table component from shadcn/ui using npx. This command downloads the component into your project's /components/autumn directory, making it available for customization. SOURCE: https://docs.useautumn.com/setup/shadcn LANGUAGE: bash CODE: ``` npx shadcn@latest add https://ui.useautumn.com/pricing-table ``` -------------------------------- TITLE: Initialize Autumn Project DESCRIPTION: Initializes a new Autumn project in the root directory. This command prompts for login/account creation and sets up the `autumn.config.ts` file. SOURCE: https://docs.useautumn.com/setup LANGUAGE: bash CODE: ``` npx atmn init ``` -------------------------------- TITLE: Push Changes to Autumn Sandbox DESCRIPTION: Pushes local configuration changes to Autumn's sandbox environment for testing and deployment. SOURCE: https://docs.useautumn.com/setup LANGUAGE: bash CODE: ``` npx atmn push ``` -------------------------------- TITLE: Install Paywall Dialog using npx DESCRIPTION: This command installs the `paywall-dialog` component from a specified URL using `npx shadcn@latest add`. The component is downloaded into the `/components/autumn` directory of your project. SOURCE: https://docs.useautumn.com/setup/shadcn LANGUAGE: bash CODE: ``` npx shadcn@latest add https://ui.useautumn.com/paywall-dialog ``` -------------------------------- TITLE: shadcn/ui Checkout Dialog Installation DESCRIPTION: Installs the checkout-dialog component from shadcn/ui using npx. This command downloads the component into your project's /components/autumn directory, enabling its use in your application. SOURCE: https://docs.useautumn.com/setup/shadcn LANGUAGE: bash CODE: ``` npx shadcn@latest add https://ui.useautumn.com/checkout-dialog ``` -------------------------------- TITLE: Check Feature Access with Autumn Client DESCRIPTION: Shows how to use the Autumn client on the backend to check if a user has access to a specific feature, like 'messages'. SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: typescript CODE: ``` import { autumn } from "convex/autumn"; const { data, error } = await autumn.check(ctx, { featureId: "messages" }); if (data.allowed) { // Action to perform if user is allowed messages } ``` -------------------------------- TITLE: Configure Convex with Autumn Component DESCRIPTION: Adds the Autumn Convex component to your convex/convex.config.ts file to integrate Autumn's functionality. SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: typescript CODE: ``` import { defineApp } from "convex/server"; import autumn from "@useautumn/convex/convex.config"; const app = defineApp(); app.use(autumn); export default app; ``` -------------------------------- TITLE: Initialize Autumn CLI DESCRIPTION: Initializes the Autumn CLI in your project's root directory. This command prompts for account login or creation and generates an `autumn.config.ts` file. SOURCE: https://docs.useautumn.com/setup/backend LANGUAGE: bash CODE: ``` npx atmn init ``` -------------------------------- TITLE: Push Configuration to Autumn DESCRIPTION: Pushes your local Autumn configuration changes to the sandbox environment. Use `npx atmn pull` to retrieve existing products from the dashboard. SOURCE: https://docs.useautumn.com/setup/backend LANGUAGE: bash CODE: ``` npx atmn push ``` -------------------------------- TITLE: Get Product by ID Response (JSON) DESCRIPTION: Example JSON response for retrieving a product by its ID. It includes fields like `autumn_id`, `created_at`, `id`, `name`, `env`, `is_add_on`, `is_default`, `group`, `version`, `items`, and `free_trial` details. SOURCE: https://docs.useautumn.com/api-reference/products/get LANGUAGE: json CODE: ``` { "autumn_id": "", "created_at": 123, "id": "", "name": "", "env": "production", "is_add_on": true, "is_default": true, "group": "", "version": 123, "items": [ { "feature_id": "", "feature_type": "single_use", "included_usage": 123, "interval": "", "usage_model": "prepaid", "price": 123, "billing_units": 123, "entity_feature_id": "", "reset_usage_when_enabled": true, "tiers": [ { "to": 123, "amount": 123 } ] } ], "free_trial": { "duration": "", "length": 123, "unique_fingerprint": true } } ``` -------------------------------- TITLE: Track Feature Usage in Convex DESCRIPTION: This snippet demonstrates how to track the usage of a specific feature within your Convex application using the Autumn SDK. It requires the Convex context and a feature ID with an associated value. SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: TypeScript CODE: ``` import { autumn } from "convex/autumn"; const { data, error } = await autumn.track(ctx, { featureId: "messages", value: 10 }); ``` -------------------------------- TITLE: Set Autumn Secret Key DESCRIPTION: Sets the AUTUMN_SECRET_KEY environment variable in your Convex environment using the Convex CLI. SOURCE: https://docs.useautumn.com/setup/convex LANGUAGE: bash CODE: ``` npx convex env set AUTUMN_SECRET_KEY=am_sk_xxx ``` -------------------------------- TITLE: Product Details Configuration for Pricing Table DESCRIPTION: Provides an example of the `productDetails` prop used with the PricingTable component. This data structure defines the content, pricing, and features for each product displayed in the pricing table. SOURCE: https://docs.useautumn.com/setup/shadcn LANGUAGE: javascript CODE: ``` const productDetails = [ { id: "free", description: "A great free plan to get started with", }, { id: "pro", description: "For all your extra messaging needs", recommendText: "Most Popular", price: { primaryText: "$10/month", secondaryText: "billed monthly", }, items: [ { featureId: "messages", }, { primaryText: "Premium support", secondaryText: "Get help from our team", }, ], }, { id: "pro_annual", }, { id: "premium", description: "For those of you who are really serious", }, { id: "premium_annual", }, ]; ``` -------------------------------- TITLE: React Pricing Table Usage Example DESCRIPTION: Demonstrates how to use the PricingTable component in a React application. It shows how to import the component and pass custom product details to configure the displayed pricing cards. SOURCE: https://docs.useautumn.com/setup/shadcn LANGUAGE: javascript CODE: ``` import { PricingTable } from "@components/autumn/pricing-table"; export const PricingTableExample = () => (
); ``` -------------------------------- TITLE: Integrate Paywall Dialog with useCustomer Hook DESCRIPTION: Demonstrates how to import and use the `PaywallDialog` component with the `useCustomer` hook's `check` function. This setup automatically enables preview mode and displays relevant upgrade or purchase information when a feature is not accessible. SOURCE: https://docs.useautumn.com/setup/shadcn LANGUAGE: javascript CODE: ``` import PaywallDialog from "@/components/autumn/paywall-dialog"; // or import { PaywallDialog } from "autumn-js/react"; import { useCustomer } from "autumn-js/react"; const { check } = useCustomer(); const { data, error } = await check({ featureId: "ai-messages", dialog: PaywallDialog, }); ``` -------------------------------- TITLE: Configure Autumn Products and Features (TypeScript) DESCRIPTION: Defines product configurations for a free and a pro plan, specifying included features like message limits and pricing intervals using Autumn's TypeScript SDK. SOURCE: https://docs.useautumn.com/setup LANGUAGE: typescript CODE: ``` import { feature, product, featureItem, pricedFeatureItem, priceItem, } from "atmn"; // Features export const messages = feature({ id: "messages", name: "Messages", type: "single_use", }); // Products export const free = product({ id: "free", name: "Free", items: [ // 5 messages per month featureItem({ feature_id: messages.id, included_usage: 5, interval: "month", }), ], }); export const pro = product({ id: "pro", name: "Pro", items: [ // 100 messages per month featureItem({ feature_id: messages.id, included_usage: 100, interval: "month", }), // $20 per month priceItem({ price: 20, interval: "month", }), ], }); ``` -------------------------------- TITLE: Node.js: Check Feature Access, Track Usage, and Get Customer Data with Autumn DESCRIPTION: This Node.js code demonstrates how to use the Autumn SDK to check feature access for a customer, track a usage event, and fetch customer subscription and usage data. It includes checking if a user is allowed to send a message and logging the remaining message balance. SOURCE: https://docs.useautumn.com/setup/backend LANGUAGE: javascript CODE: ``` import { Autumn as autumn } from "autumn-js"; // check feature access const { data } = await autumn.check({ customer_id: "user_123", feature_id: "messages", }); if (!data.allowed) { console.log("No more messages!"); return; } // ... your own function to send the message // then record the usage in Autumn await autumn.track({ customer_id: "user_123", feature_id: "messages", }); // fetch customer usage + billing data const customer = await autumn.customers.get("user_123"); const messages = customer?.features.messages; console.log("Remaining messages: " + messages?.balance); ``` -------------------------------- TITLE: Wrap Application with Autumn Provider (Next.js Layout) DESCRIPTION: Wraps the entire application with the `AutumnProvider` component in Next.js to enable client-side integration with Autumn. The `backendUrl` prop can be specified if the backend is hosted separately. SOURCE: https://docs.useautumn.com/setup LANGUAGE: tsx CODE: ``` //layout.tsx import { AutumnProvider } from "autumn-js/react"; export default function RootLayout({ children, }: { children: React.ReactNode, }) { return ( {children} ); } ``` -------------------------------- TITLE: Configure Autumn Products (TypeScript) DESCRIPTION: Defines 'Free' and 'Pro' products with feature items for message limits and price items for monthly subscription costs. This configuration is used by the Autumn CLI. SOURCE: https://docs.useautumn.com/setup/backend LANGUAGE: TypeScript CODE: ``` import { feature, product, featureItem, pricedFeatureItem, priceItem, } from "atmn"; // Features export const messages = feature({ id: "messages", name: "Messages", type: "single_use", }); // Products export const free = product({ id: "free", name: "Free", items: [ // 5 messages per month featureItem({ feature_id: messages.id, included_usage: 5, interval: "month", }), ], }); export const pro = product({ id: "pro", name: "Pro", items: [ // 100 messages per month featureItem({ feature_id: messages.id, included_usage: 100, interval: "month", }), // $20 per month priceItem({ price: 20, interval: "month", }), ], }); ``` -------------------------------- TITLE: Attach Product for Payment (Node.js) DESCRIPTION: Uses the `attach` function from `autumn-js` to enable a product for a customer when payment details are already on file. This function can also charge the customer if applicable. SOURCE: https://docs.useautumn.com/setup/backend LANGUAGE: JavaScript CODE: ``` import { Autumn } from "autumn-js"; const autumn = new Autumn({ secretKey: "am_sk_..." }); const { data } = await autumn.attach({ customer_id: "internal_user_or_org_id_from_auth", product_id: "pro", }); ``` -------------------------------- TITLE: Initiate Stripe Checkout (Node.js) DESCRIPTION: Calls the `checkout` function from the `autumn-js` library to generate a Stripe checkout page for a customer purchasing a specific product. It requires a customer ID and product ID. SOURCE: https://docs.useautumn.com/setup/backend LANGUAGE: JavaScript CODE: ``` import { Autumn } from "autumn-js"; const autumn = new Autumn({ secretKey: "am_sk_..." }); const { data } = await autumn.checkout({ customer_id: "internal_user_or_org_id_from_auth", product_id: "pro", }); ``` -------------------------------- TITLE: React: Initiate Stripe Checkout for Pro Plan Upgrade DESCRIPTION: This React component uses the `useCustomer` hook from `autumn-js/react` to initiate the Stripe checkout process for upgrading to the Pro plan. It redirects the customer to a Stripe checkout page or opens a dialog if payment details are on file. SOURCE: https://docs.useautumn.com/setup LANGUAGE: javascript CODE: ``` import { useCustomer, CheckoutDialog } from "autumn-js/react"; export default function PurchaseButton() { const { checkout } = useCustomer(); return ( ); } ``` -------------------------------- TITLE: Configure Autumn Secret Key DESCRIPTION: Sets the `AUTUMN_SECRET_KEY` environment variable, which is necessary for authenticating with the Autumn API. This is typically added to the backend's `.env` file. SOURCE: https://docs.useautumn.com/setup LANGUAGE: env CODE: ``` AUTUMN_SECRET_KEY=am_sk_1234567890 ``` -------------------------------- TITLE: Create Product Response DESCRIPTION: Example JSON response for the 'Create Product' API endpoint. It details the newly created product, including its Autumn ID, creation timestamp, ID, name, environment, add-on status, default status, group, version, items, and free trial configuration. SOURCE: https://docs.useautumn.com/api-reference/products/post LANGUAGE: json CODE: ``` { "autumn_id": "", "created_at": 123, "id": "", "name": "", "env": "production", "is_add_on": true, "is_default": true, "group": "", "version": 123, "items": [ { "feature_id": "", "feature_type": "single_use", "included_usage": 123, "interval": "", "usage_model": "prepaid", "price": 123, "billing_units": 123, "entity_feature_id": "", "reset_usage_when_enabled": true, "tiers": [ { "to": 123, "amount": 123 } ] } ], "free_trial": { "duration": "", "length": 123, "unique_fingerprint": true } } ``` -------------------------------- TITLE: Get Product by ID (cURL) DESCRIPTION: Retrieves a specific product by its unique identifier. This operation requires authentication via a Bearer token and specifies the product ID in the URL path. The response includes detailed product information such as its ID, name, version, and associated items. SOURCE: https://docs.useautumn.com/api-reference/products/get LANGUAGE: bash CODE: ``` curl --request GET \ --url https://api.useautumn.com/v1/products/{id} \ --header 'Authorization: Bearer ' ``` -------------------------------- TITLE: Customer Features JSON Response DESCRIPTION: Example JSON response detailing a customer's features, including feature ID, included usage, current usage, balance, unlimited status, interval, and next reset timestamp. SOURCE: https://docs.useautumn.com/features/balances LANGUAGE: JSON CODE: ``` { "features": [ { "feature_id": "ai-messages", //metered feature "included_usage": 100, "usage": 60, "balance": 40, "unlimited": false, "interval": "month", "next_reset_at": 1745193600011 }, { "feature_id": "seats", //metered feature "included_usage": 0, "usage": 6, "balance": -6, "unlimited": false, "interval": "month", "next_reset_at": null }, { "feature_id": "premium-support" //boolean feature } ] } ``` -------------------------------- TITLE: Get Customer Features with cURL DESCRIPTION: Retrieves a list of a customer's available features and their balances using a GET request to the /v1/customers/{id} endpoint. Requires an Authorization header. SOURCE: https://docs.useautumn.com/features/balances LANGUAGE: cURL CODE: ``` curl --request GET \ --url https://api.useautumn.com/v1/customers/user_123 \ --header 'Authorization: Bearer am_sk_1234567890' ``` -------------------------------- TITLE: Attach Product Response Example DESCRIPTION: Illustrates the JSON response received after attempting to attach a product. This response includes a checkout URL if a payment method is not present, customer details, product IDs, and a status message. SOURCE: https://docs.useautumn.com/products/enabling-product LANGUAGE: json CODE: ``` { "checkout_url": "https://checkout.stripe.com/cx/", "customer_id": "123", "product_ids": ["pro"], "code": "checkout_created", "message": "Successfully created checkout for customer 123, product(s) Pro", } ``` -------------------------------- TITLE: Example Usage Data Response DESCRIPTION: This is an example of the JSON response structure returned by the Autumn API when querying feature usage. It includes a list of usage data points, each with a period timestamp and usage count for the requested feature. SOURCE: https://docs.useautumn.com/api-reference/core/query LANGUAGE: JSON CODE: ``` { "list": [ { "period": 1672531200000, "messages": 45 }, { "period": 1672617600000, "messages": 32 }, { "period": 1672704000000, "messages": 18 } ] } ``` -------------------------------- TITLE: Attach Product using cURL DESCRIPTION: Provides an example of how to attach a product to a customer using a cURL command. This typically involves making a POST request to the Autumn API endpoint with the necessary customer and product identifiers. SOURCE: https://docs.useautumn.com/products/enabling-product LANGUAGE: bash CODE: ``` curl -X POST https://api.useautumn.com/customers/{customer_id}/attach \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"product_id": "pro"}' ``` -------------------------------- TITLE: Attach Top-up Minutes Product DESCRIPTION: Attaches a top-up product to a customer, specifying the quantity of minutes to purchase. This is used to generate a payment link for prepaid services. The example shows purchasing 420 minutes. SOURCE: https://docs.useautumn.com/guides/prepaid LANGUAGE: cURL CODE: ``` curl -X POST "https://api.useautumn.com/v1/attach" \ -H "Authorization: Bearer am_sk_1234567890" \ -H "Content-Type: application/json" \ -d '{ "customer_id": "john-yeo", "product_id": "top-up-minutes", "quantity": 420 }' ``` -------------------------------- TITLE: Check Feature Access Response Example DESCRIPTION: This is an example of a successful response from the Autumn API's check endpoint. It indicates that the feature is found and the customer is allowed access, along with balance details. SOURCE: https://docs.useautumn.com/api-reference/core/check LANGUAGE: JSON CODE: ``` { "customer_id": "user_123", "feature_id": "messages", "code": "feature_found", "allowed": true, "balance": { "balance": 100, "required_balance": 12 } } ``` -------------------------------- TITLE: Create Entity with Autumn JS DESCRIPTION: Provides an example of creating one or more entities for a customer using the `createEntity` function from the `useCustomer` hook. It requires `id`, `name`, and `featureId` as parameters. SOURCE: https://docs.useautumn.com/api-reference/hooks/useCustomer LANGUAGE: javascript CODE: ``` import { useCustomer } from "autumn-js/react"; export default function CreateUserSeat() { const { createEntity } = useCustomer(); const handleCreateSeat = async () => { const { data, error } = await createEntity({ id: "user_abc", name: "John Doe", featureId: "seats", }); console.log("Created entity:", data); }; } return ; ``` -------------------------------- TITLE: Client-side: Check Feature Access and Display Usage with Autumn.js (React) DESCRIPTION: This React component utilizes the `useCustomer` hook from `autumn-js/react` to manage customer billing data, including feature permissions and usage balances. It implements a client-side check for feature access ('messages') to gate features and display paywalls. The `refetch` function is used to update customer usage data after an action, and the remaining message balance is logged. SOURCE: https://docs.useautumn.com/setup LANGUAGE: javascript CODE: ``` import { useCustomer } from "autumn-js/react"; export default function SendChatMessage() { const { customer, check, refetch } = useCustomer(); return ( <> ); } ``` -------------------------------- TITLE: Track Endpoint Response Example DESCRIPTION: This example shows a successful response from the POST /track endpoint. It includes a unique event ID, a status code, and the customer and feature IDs associated with the tracked event. SOURCE: https://docs.useautumn.com/api-reference/core/track LANGUAGE: JSON CODE: ``` { "id": "evt_2w5dzidzFD1cESxOGnn9frVuVcm", "code": "event_received", "customer_id": "user_123", "feature_id": "messages" } ``` -------------------------------- TITLE: Mount Autumn Handler in Next.js DESCRIPTION: Integrates the Autumn handler into a Next.js application's API route. The `identify` function extracts user information from the request headers to associate activity with a specific customer. SOURCE: https://docs.useautumn.com/setup LANGUAGE: javascript CODE: ``` //app/api/autumn/[...all]/route.ts import { autumnHandler } from "autumn-js/next"; import { auth } from "@/lib/auth"; export const { GET, POST } = autumnHandler({ identify: async (request) => { // get the user from your auth provider (example: better-auth) const session = await auth.api.getSession({ headers: request.headers, }); return { customerId: session?.user.id, //or org ID customerData: { name: session?.user.name, email: session?.user.email, }, }; }, }); ``` -------------------------------- TITLE: Server-side: Check Feature Access and Track Usage with Autumn.js DESCRIPTION: This TypeScript code demonstrates how to perform a server-side check for feature access ('messages') using Autumn.js. It makes an API call to Autumn's database to verify if the customer is allowed to use the feature. If allowed, it proceeds with the intended action (e.g., sending a message) and then tracks the usage event in Autumn. SOURCE: https://docs.useautumn.com/setup LANGUAGE: typescript CODE: ``` import { Autumn as autumn } from "autumn-js"; // same user id from auth as in the autumn handler const { data } = await autumn.check({ customer_id: "user_123", feature_id: "messages", }); if (!data?.allowed) { console.log("No more messages for you buddy!"); return; } // ... your own function to send the message // then record the usage in Autumn await autumn.track({ customer_id: "user_123", feature_id: "messages", }); ``` -------------------------------- TITLE: Handle Failed Payments (React) DESCRIPTION: Provides a React example for detecting failed payments using the `useCustomer` hook from `autumn-js/react`. It checks if a customer's product status is 'past_due' and suggests redirecting the user to a billing portal to update their payment method. SOURCE: https://docs.useautumn.com/setup/ai-builders LANGUAGE: javascript CODE: ``` import { useCustomer } from "autumn-js/react"; const failed_payment = customer.products.find((p) => p.status === "past_due"); ``` -------------------------------- TITLE: Define Continuous-use Feature DESCRIPTION: Defines a 'continuous_use' feature for ongoing usage that does not reset periodically. Examples include seats or storage, which may be prorated. SOURCE: https://docs.useautumn.com/api-reference/cli/config LANGUAGE: typescript CODE: ``` export const messages = feature({ id: "seats", name: "Seats", type: "continuous_use", }); ``` -------------------------------- TITLE: Get Billing Portal URL - TypeScript DESCRIPTION: Retrieves the URL for a customer's billing portal. Requires the customer ID and a return URL. The response contains the billing portal session URL. SOURCE: https://docs.useautumn.com/api-reference/customers/billing-portal LANGUAGE: TypeScript CODE: ``` import { Autumn as autumn } from 'autumn-js'; const response = await autumn.customers.billingPortal('user_123', { return_url: 'https://example.com/account' }); ``` -------------------------------- TITLE: TypeScript Function to Get Pricing Table Content DESCRIPTION: A TypeScript function that determines the button text for pricing table cards based on product properties like trial availability, one-off status, and subscription scenario. It uses a switch statement to handle various states like 'active', 'new', 'upgrade', etc. SOURCE: https://docs.useautumn.com/setup/shadcn LANGUAGE: typescript CODE: ``` import { Product } from "autumn-js"; export const getPricingTableContent = (product: Product) => { const { scenario, free_trial, properties } = product; const { is_one_off, has_prepaid, has_trial } = properties; if (has_trial) { return { buttonText:

Start Free Trial

, }; } switch (scenario) { case "scheduled": return { buttonText:

Plan Scheduled

, }; case "active": if (has_prepaid) { return { buttonText:

Update Plan

, }; } return { buttonText:

Current Plan

, }; case "new": if (is_one_off) { return { buttonText:

Purchase

, }; } return { buttonText:

Get started

, }; case "renew": return { buttonText:

Renew

, }; case "upgrade": return { buttonText:

Upgrade

, }; case "downgrade": return { buttonText:

Downgrade

, }; case "cancel": return { buttonText:

Cancel Plan

, }; default: return { buttonText:

Get Started

, }; } }; ``` -------------------------------- TITLE: Check Metered Feature Access with Quantity (React) DESCRIPTION: Checks if a customer has access to a feature, specifying a required quantity. This prevents users from starting processes that would consume more than their allowance. It defaults to a required quantity of 1. SOURCE: https://docs.useautumn.com/features/check LANGUAGE: javascript CODE: ``` const { allowed, check } = useCustomer(); const canSendMessage = allowed({ featureId: "messages", requiredQuantity: 3 }); const { data } = await check({ featureId: "messages", requiredQuantity: 3 }); ``` -------------------------------- TITLE: Get Customer - TypeScript DESCRIPTION: Retrieves a specific customer's details using their unique identifier. This operation requires authentication with a secret key. The response includes customer information such as their ID, name, email, associated products, and feature entitlements. SOURCE: https://docs.useautumn.com/api-reference/customers/get LANGUAGE: TypeScript CODE: ``` import { Autumn as autumn } from 'autumn-js'; const { data } = await autumn.customers.get('user_123'); ``` -------------------------------- TITLE: Define Free Product with Features DESCRIPTION: Defines a 'Free' product that includes several features: 5 messages per month, 3 seats, and SSO authentication. This demonstrates how to bundle features into a product. SOURCE: https://docs.useautumn.com/api-reference/cli/config LANGUAGE: typescript CODE: ``` export const free = product({ id: "free", name: "Free", is_default: true, items: [ // 5 messages per month featureItem({ feature_id: messages.id, included_usage: 5, interval: "month", }), // 3 seats (no reset) featureItem({ feature_id: seats.id, included_usage: 3, }), // SSO Auth (boolean) featureItem({ feature_id: sso.id, }), ], }); ``` -------------------------------- TITLE: Create Product DESCRIPTION: Creates a new product in the Autumn platform. This endpoint requires authentication and accepts product details in JSON format, including ID, name, add-on status, default status, items, and free trial information. The response includes the created product's details. SOURCE: https://docs.useautumn.com/api-reference/products/post LANGUAGE: bash CODE: ``` curl --request POST \ --url https://api.useautumn.com/v1/products \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ \ "id": "", \ "name": "", \ "is_add_on": false, \ "is_default": false, \ "items": [ \ { \ "feature_id": "", \ "feature_type": "single_use", \ "included_usage": 123, \ "interval": "", \ "usage_model": "prepaid", \ "price": 123, \ "billing_units": 123, \ "entity_feature_id": "", \ "reset_usage_when_enabled": true, \ "tiers": [ \ { \ "to": 123, \ "amount": 123 \ } \ ] \ } \ ], \ "free_trial": { \ "duration": "", \ "length": 123, \ "unique_fingerprint": true \ } \ }' ``` -------------------------------- TITLE: Configure Product and Feature Builders in TypeScript DESCRIPTION: This TypeScript code defines features and products using the Autumn library. It shows how to set up features with different types (boolean, metered) and products with various pricing tiers, included usage, and billing models. SOURCE: https://docs.useautumn.com/products/create-product LANGUAGE: typescript CODE: ``` import { feature, product, featureItem, pricedFeatureItem, priceItem, } from 'atmn'; // Features export const canUseTokens = feature({ id: 'can_use_tokens', name: 'Can Use Tokens', type: 'boolean', }) export const message = feature({ id: "message", name: "Messages", type: "metered", }); export const taskRuns = feature({ id: "task_runs", name: "Task Runs", type: "metered", }); // Products export const freePlan = product({ id: 'free', name: 'Free', items: [ featureItem({ feature_id: message.id, included_usage: 200, interval: 'month', }), ] }) export const ultraPlan = product({ id: "ultra", name: "Ultra", items: [ priceItem({ price: 300, interval: "year", }), pricedFeatureItem({ feature_id: message.id, price: 200, interval: "month", included_usage: 80, billing_units: 100, usage_model: "pay_per_use", }), featureItem({ feature_id: message.id, included_usage: 900, interval: "year", }), featureItem({ feature_id: taskRuns.id, included_usage: 900, interval: "year", }), ], }); export const proPlan = product({ id: "pro", name: "Pro", items: [ priceItem({ price: 200, interval: "year", }), pricedFeatureItem({ feature_id: canUseTokens.id, price: 200, interval: "month", included_usage: 1, billing_units: 1, usage_model: "prepaid", }), pricedFeatureItem({ feature_id: message.id, price: 200, interval: "month", included_usage: 30, billing_units: 100, usage_model: "pay_per_use", }), featureItem({ feature_id: message.id, included_usage: 650, interval: "year", }), featureItem({ feature_id: taskRuns.id, included_usage: 650, interval: "year", }), ], }); // Remember to update this when you make changes! export default { products: [freePlan, ultraPlan, proPlan], features: [canUseTokens, message, taskRuns] } ``` -------------------------------- TITLE: Fetching Customer Data with useCustomer Hook DESCRIPTION: This JavaScript code snippet shows how to use the `useCustomer` hook from `autumn-js/react` to fetch and log customer data within your React application. This is useful for verifying that the customer has been successfully created in Autumn. SOURCE: https://docs.useautumn.com/setup/ai-builders LANGUAGE: javascript CODE: ``` import { useCustomer } from "autumn-js/react"; const { customer } = useCustomer(); console.log("Autumn Customer", customer); ``` -------------------------------- TITLE: Open Billing Portal (React) DESCRIPTION: Demonstrates how to open the Autumn.io billing portal using the `openBillingPortal` function from the `useCustomer` hook in `autumn-js/react`. This allows users to manage their subscriptions, update payment methods, or cancel their service. SOURCE: https://docs.useautumn.com/setup/ai-builders LANGUAGE: javascript CODE: ``` import { useCustomer } from "autumn-js/react"; export default function BillingSettings() { const { openBillingPortal } = useCustomer(); return ( ); } ``` -------------------------------- TITLE: Upgrade User to Pro with Stripe Checkout DESCRIPTION: Initiates a user upgrade to the Pro plan by obtaining a Stripe Checkout URL. This involves a POST request to the `/v1/attach` endpoint with customer and product details. The response contains a `checkout_url` to redirect the user for payment. SOURCE: https://docs.useautumn.com/guides/credits LANGUAGE: cURL CODE: ``` curl -X POST "https://api.useautumn.com/v1/attach" \ -H "Authorization: Bearer am_sk_1234567890" \ -H "Content-Type: application/json" \ -d '{ "customer_id": "john-yeo", "product_id": "pro" }' ``` LANGUAGE: Typescript CODE: ``` { "customer_id": "john-yeo", "product_ids": [ "pro" ], "code": "checkout_created", "message": "Successfully created checkout for customer john-yeo, product(s) Pro", "checkout_url": "https://checkout.stripe.com/c/pay/abcdefghijklmnopqrstuvwxyz" } ``` -------------------------------- TITLE: Implement Paywall Logic with Upgrade (React) DESCRIPTION: This React component demonstrates a practical implementation of the paywall logic. It uses the `check` and `attach` functions from `autumn-js/react`. When a feature is not allowed and preview data is available, it prompts the user to upgrade via a confirmation dialog and then attaches the relevant product. SOURCE: https://docs.useautumn.com/setup/roll LANGUAGE: javascript CODE: ``` import { useCustomer } from "autumn-js/react"; export default function FeatureButton() { const { check, attach } = useCustomer(); return ( ); } ``` -------------------------------- TITLE: Integrate Autumn with 3 Functions DESCRIPTION: Autumn simplifies pricing model integration by requiring only three core functions. This approach eliminates the need for complex webhook handling and database synchronization typically associated with direct payment gateway integrations. SOURCE: https://docs.useautumn.com/api-reference/check LANGUAGE: javascript CODE: ``` import { checkout, hasAccess, trackUsage } from "autumn"; // Example usage: async function handlePurchase(customerId, productId) { const checkoutUrl = await checkout(customerId, productId); // Redirect user to checkoutUrl } async function checkFeatureAccess(customerId, featureId) { const access = await hasAccess(customerId, featureId); // Grant or deny access based on 'access' boolean } async function recordUsage(customerId, featureId, quantity) { await trackUsage(customerId, featureId, quantity); // Usage is tracked and reflected in billing } ``` -------------------------------- TITLE: React UI Components for Pricing DESCRIPTION: Autumn provides pre-built React components for common pricing UI elements like pricing tables, purchase confirmation dialogs, and paywalls. These components can be used directly or customized as shadcn/ui files. SOURCE: https://docs.useautumn.com/api-reference/check LANGUAGE: javascript CODE: ``` import React from 'react'; import { PricingTable, PurchaseDialog, Paywall } from '@autumn/react-ui'; function App() { const pricingPlans = [ { name: 'Free', price: 0 }, { name: 'Pro', price: 10 }, { name: 'Enterprise', price: 50 } ]; return (
{/* Example of a paywall for a specific feature */} {/* PurchaseDialog would typically be triggered by a button click */}
); } ``` -------------------------------- TITLE: Check Product Access (React) DESCRIPTION: Retrieves customer product information using the `useCustomer` hook from `autumn-js/react`. It demonstrates how to find a specific product (e.g., 'pro') within the customer's products array to gate features. It emphasizes checking for product presence rather than just active status. SOURCE: https://docs.useautumn.com/setup/ai-builders LANGUAGE: javascript CODE: ``` import { useCustomer } from "autumn-js/react"; const premiumUser = customer.products.find((p) => p.id === "pro"); ``` -------------------------------- TITLE: Create or Retrieve Referral Code DESCRIPTION: This endpoint creates or retrieves a unique referral code for a customer within a specific referral program. A referral code is unique per customer within each program. On the first call, a new code is created, but subsequent calls will return the same existing code for that customer and program combination. SOURCE: https://docs.useautumn.com/api-reference/products/referral-code LANGUAGE: bash CODE: ``` curl --request POST \ --url https://api.useautumn.com/v1/referrals/code \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ \ "customer_id": "", \ "program_id": "" \ }' ``` -------------------------------- TITLE: Attach Product using React DESCRIPTION: Demonstrates how to attach a product to a customer using the `useCustomer` hook from the `autumn-js/react` library. This involves calling the `attach` function with the product ID. SOURCE: https://docs.useautumn.com/products/enabling-product LANGUAGE: javascript CODE: ``` import { useCustomer } from "autumn-js/react"; const { attach } = useCustomer();