added example folder and added referral demo screen

This commit is contained in:
Ayush Rodrigues
2025-04-16 17:15:31 +01:00
parent 4a57d7b05a
commit ebb2fcbfc6
30 changed files with 7925 additions and 0 deletions

2
example/.env.local Normal file
View File

@@ -0,0 +1,2 @@
# AUTUMN_SECRET_KEY=am_sk_test_OAFUOL0meFCjpMMmFeU13gHnrEOGAHWp2YTLECyY7k
AUTUMN_SECRET_KEY=am_sk_test_RCM3U5M8ptWm6AWhE68hTeVn0sACxX6JE0zpHJi3SV # Recase Org

43
example/.gitignore vendored Normal file
View File

@@ -0,0 +1,43 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# Remove .env.local from gitignore
!.env.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

87
example/README.md Normal file
View File

@@ -0,0 +1,87 @@
# Next.js Autumn Starter Template
[Autumn](https://useautumn.com) is an open-source layer between Stripe and your application, allowing you to create any pricing model and embed it with a couple lines of code.
This template demonstrates how you can set up pricing in just 3 lines of code using Autumn. The example used is a simple AI chat message app.
View the example app here: https://nextjs-autumn-template.vercel.app/
## Getting Started
1. Clone the repository:
```bash
git clone https://github.com/useautumn/nextjs-autumn-template.git
npm install
npm run dev
```
2. Create an account at [app.useautumn.com](https://app.useautumn.com)
3. Get your Autumn secret key from the [sandbox environment](https://app.useautumn.com/sandbox/dev) and add it to `.env.local`:
```env
AUTUMN_SECRET_KEY=am_sk_test_OAFUOL0meFCjpMMmFeU13gHnrEOGAHWp2YTLECyY7k
```
4. Connect your Stripe account in the [integrations page](https://app.useautumn.com/sandbox/integrations/stripe)
## Understanding the Implementation
This template implements a simple AI chat message app where users can:
- Send messages (with usage limits)
- Upgrade to a pro plan
- View their usage and subscription details
### Key Endpoints
1. **Check if a user can access a feature** (`/entitled`)
```typescript
// Check if user can send a message
const allowed = await entitled({
customerId: CUSTOMER_ID,
featureId: FEATURE_ID,
});
if (!allowed) {
toast.error("You're out of messages!");
return;
}
```
2. **Track a user's usage of a feature** (`/events`)
```typescript
// Record that a message was sent
await sendEvent({
customerId: CUSTOMER_ID,
featureId: FEATURE_ID,
});
```
3. **Get a Stripe Checkout URL so the customer can purchase a plan** (`/attach`)
```typescript
// Upgrade user to pro plan
const res = await attachProduct({
customerId: CUSTOMER_ID,
productId: "pro",
});
window.open(res.checkout_url, "_blank");
```
<!-- ### Additional Features
The template also includes `getOrCreateCustomer` to fetch customer details, entitlements, and subscription status, which is used in the customer details card in the UI:
```typescript
const customer = await getOrCreateCustomer(CUSTOMER_ID);
// Returns: customer details, product subscriptions, and feature entitlements
``` -->
## Learn More
- [Autumn Documentation](https://docs.useautumn.com)
- [Next.js Documentation](https://nextjs.org/docs)

21
example/components.json Normal file
View File

@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

21
example/eslint.config.mjs Normal file
View File

@@ -0,0 +1,21 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
{
rules: {
"@typescript-eslint/no-explicit-any": "off",
},
},
];
export default eslintConfig;

7
example/next.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

6456
example/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
example/package.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "nextjs-autumn-template",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/react-separator": "^1.1.2",
"@radix-ui/react-slot": "^1.1.2",
"@radix-ui/react-tooltip": "^1.1.8",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.483.0",
"next": "15.2.3",
"next-themes": "^0.4.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"sonner": "^2.0.1",
"tailwind-merge": "^3.0.2",
"tw-animate-css": "^1.2.4"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"eslint": "^9",
"eslint-config-next": "15.2.3",
"tailwindcss": "^4",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

1
example/public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
example/public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
example/public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,104 @@
"use server";
import { Autumn } from "@/sdk/autumn";
// ONLY 3 ENDPOINTS NEEDED TO GET STARTED
// Entitled: Check if your user should be allowed to use a feature
export const entitled = async ({
customerId,
featureId,
}: {
customerId: string;
featureId: string;
}) => {
const response = await fetch(`https://api.useautumn.com/v1/entitled`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AUTUMN_SECRET_KEY}`,
},
body: JSON.stringify({
customer_id: customerId,
feature_id: featureId,
}),
});
const data = await response.json();
return data.allowed;
};
//Events: send a usage event to Autumn to track a user's usage of a feature
export const sendEvent = async ({
customerId,
featureId,
}: {
customerId: string;
featureId: string;
}) => {
await fetch("https://api.useautumn.com/v1/events", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AUTUMN_SECRET_KEY}`,
},
body: JSON.stringify({
customer_id: customerId,
feature_id: featureId,
}),
});
};
//Attach: get a checkout URL from Autumn so the user can upgrade
export const attachProduct = async ({
customerId,
productId,
}: {
customerId: string;
productId: string;
}) => {
const response = await fetch(`https://api.useautumn.com/v1/attach`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AUTUMN_SECRET_KEY}`,
},
body: JSON.stringify({
customer_id: customerId,
product_id: productId,
force_checkout: true,
}),
});
const data = await response.json();
if (response.status !== 200) {
throw new Error(data.message || "Failed to attach pro product");
}
return data;
};
// ADDITIONAL ENDPOINT TO FETCH CUSTOMER DETAILS
export const getOrCreateCustomer = async (customerId: string) => {
const response = await fetch(`https://api.useautumn.com/v1/customers`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AUTUMN_SECRET_KEY}`,
},
body: JSON.stringify({
id: customerId,
}),
});
const data = await response.json();
return data;
};
export const getCustomer = async (customerId: string) => {
const autumn = new Autumn();
const data = await autumn.customers.get(customerId);
const { entitlements, invoices } = data;
return data;
};

BIN
example/src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

135
example/src/app/globals.css Normal file
View File

@@ -0,0 +1,135 @@
@import "tailwindcss";
@import "tw-animate-css";
button {
padding: 5px 10px;
background-color: #8838ff;
color: white;
cursor: pointer;
border-radius: 5px;
font-weight: 500;
}
button:hover {
background-color: #413652;
}
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

View File

@@ -0,0 +1,36 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Toaster } from "@/components/ui/sonner";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Next.js Autumn App",
description: "Starter Next.js app with Autumn",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<Toaster position="top-right" />
{children}
</body>
</html>
);
}

42
example/src/app/page.tsx Normal file
View File

@@ -0,0 +1,42 @@
"use client";
import { getOrCreateCustomer } from "./autumn-functions";
import { useState } from "react";
import { useEffect } from "react";
import Intro from "@/components/introduction";
import CustomerDetailsExample from "@/components/billing";
import Application from "@/components/application";
// Replace this with your internal user ID
const CUSTOMER_ID = "theo";
export default function Home() {
const [customerData, setCustomerData] = useState<any>(null);
const fetchCustomer = async () => {
const customer = await getOrCreateCustomer(CUSTOMER_ID);
setCustomerData(customer);
};
useEffect(() => {
fetchCustomer();
}, []);
if (!customerData) {
return <></>;
}
return (
<div className="min-h-screen w-full p-6 flex flex-col gap-8 max-w-7xl mx-auto">
<Intro />
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Application
customerId={CUSTOMER_ID}
fetchCustomer={fetchCustomer}
/>
<CustomerDetailsExample customerData={customerData} />
</div>
</div>
);
}

View File

@@ -0,0 +1,30 @@
"use server";
import { Autumn } from "@/sdk/autumn";
export const getReferralCode = async (customerId: string) => {
console.log("Getting referral code");
const autumn = new Autumn();
const referralCode = await autumn.referrals.createCode({
customerId,
referralId: "referral",
});
return referralCode;
};
export const redeemReferralCode = async ({
customerId,
referralCode,
}: {
customerId: string;
referralCode: string;
}) => {
const autumn = new Autumn();
const redemption = await autumn.referrals.redeem({
customerId,
code: referralCode,
});
console.log("Referral code redeemed");
console.log("Redemption", redemption);
return redemption;
};

View File

@@ -0,0 +1,173 @@
"use client";
import { useEffect, useState } from "react";
import { getReferralCode, redeemReferralCode } from "./functions";
import { toast } from "sonner";
import { attachProduct, getCustomer } from "../autumn-functions";
import { Input } from "@/components/ui/input";
const useReferralCode = (referrerId: string) => {
const [referralCode, setReferralCode] = useState<string | null>(null);
const [loading, setLoading] = useState<boolean>(false);
useEffect(() => {
const fetchReferralCode = async () => {
setLoading(true);
try {
const { code } = await getReferralCode(referrerId);
setReferralCode(code);
} catch (error) {
console.log("Failed to get referral code", error);
toast.error(`Error fetching referral code: ${error}`);
}
setLoading(false);
};
fetchReferralCode();
}, []);
return { referralCode, isLoading: loading };
};
const useCustomer = (customerId: string) => {
const [customer, setCustomer] = useState<any>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
const fetchCustomer = async () => {
setIsLoading(true);
const customerData = await getCustomer(customerId);
setCustomer(customerData);
setIsLoading(false);
};
const refresh = async () => {
const customerData = await getCustomer(customerId);
setCustomer(customerData);
};
useEffect(() => {
fetchCustomer();
}, []);
return { ...customer, isLoading, refresh };
};
export default function ReferralsPage() {
const { referralCode, isLoading } = useReferralCode("ayush");
const {
entitlements,
refresh,
isLoading: isCustomerLoading,
} = useCustomer("ayush");
let referrerId = "ayush";
let referee1Id = "john";
let [referral1Code, setReferral1Code] = useState<string>("");
return (
<div className="min-h-screen bg-zinc-50 p-8">
<div className="max-w-6xl mx-auto">
<h1 className="text-2xl font-mono mb-8 text-zinc-800">
Referral Program
</h1>
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
{/* Referrer Section */}
<div className="bg-white border border-zinc-200 rounded-lg p-6 shadow-sm">
<div className="space-y-4">
<div className="flex items-center space-x-2 pb-2 border-b border-zinc-100">
<span className="text-xs font-mono text-zinc-500">
USER ID:
</span>
<span className="font-mono text-sm text-zinc-800 bg-zinc-100 px-2 py-0.5 rounded">
{referrerId}
</span>
</div>
<h2 className="text-lg font-mono text-zinc-700">
Your Referral Code
</h2>
<div className="bg-zinc-50 p-4 rounded-md border border-zinc-200">
<p className="font-mono text-lg tracking-wide text-zinc-800">
{isLoading
? "Loading..."
: referralCode || "No code available"}
</p>
</div>
{entitlements && (
<div className="mt-6 space-y-3">
<h3 className="text-sm font-mono text-zinc-600">
Your Features
</h3>
{entitlements.map((entitlement: any, index: number) => (
<div
key={index}
className="flex items-center justify-between py-2 px-3 bg-zinc-50 rounded-md"
>
<span className="font-mono text-sm text-zinc-700">
{entitlement.feature_id}
</span>
<span className="font-mono text-sm bg-zinc-200 px-2 py-1 rounded">
{entitlement.balance}
</span>
</div>
))}
</div>
)}
</div>
</div>
{/* Referee Section */}
<div className="bg-white border border-zinc-200 rounded-lg p-6 shadow-sm">
<div className="space-y-4">
<div className="flex items-center space-x-2 pb-2 border-b border-zinc-100">
<span className="text-xs font-mono text-zinc-500">
USER ID:
</span>
<span className="font-mono text-sm text-zinc-800 bg-zinc-100 px-2 py-0.5 rounded">
{referee1Id}
</span>
</div>
<h2 className="text-lg font-mono text-zinc-700">Redeem Code</h2>
<div className="space-y-2">
<p className="text-sm font-mono text-zinc-600">
Enter referral code to get started
</p>
<Input
value={referral1Code}
onChange={(e) => setReferral1Code(e.target.value)}
placeholder="Enter code"
className="font-mono text-base"
/>
<button
onClick={async () => {
try {
await redeemReferralCode({
customerId: referee1Id,
referralCode: referral1Code,
});
const { checkout_url } = await attachProduct({
customerId: referee1Id,
productId: "pro",
});
if (checkout_url) {
window.open(checkout_url, "_blank");
} else {
toast.error("Something went wrong");
}
} catch (error) {
toast.error("Failed to redeem code");
}
}}
className="w-full mt-4 bg-zinc-800 hover:bg-zinc-700 text-white font-mono py-2 px-4 rounded-md transition-colors"
>
Redeem & Purchase Pro
</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,83 @@
import { sendEvent } from "@/app/autumn-functions";
import { entitled } from "@/app/autumn-functions";
import { MessageSquare } from "lucide-react";
import { toast } from "sonner";
export default function Application({
customerId,
fetchCustomer,
}: {
customerId: string;
fetchCustomer: () => void;
}) {
const sendMessageClicked = async (featureId: string) => {
const allowed = await entitled({
customerId,
featureId,
});
if (!allowed) {
toast.error(`You're out of ${featureId}!`);
return;
}
await sendEvent({
customerId,
featureId,
});
toast.success(`${featureId} used!`);
};
return (
<div className="border rounded-lg bg-white overflow-hidden flex flex-col">
<div className="border-b p-6">
<div className="flex items-start justify-between">
<div className="space-y-1">
<h2 className="text-lg font-semibold">Feature Access Example</h2>
<p className="text-sm text-muted-foreground">
Test how our feature access and event sending works
</p>
</div>
<div className="h-8 w-8 rounded-lg bg-purple-50 flex items-center justify-center">
<MessageSquare className="h-4 w-4 text-purple-600" />
</div>
</div>
</div>
<div className="p-6 flex-1">
<div className="space-y-2">
<div className="text-sm font-medium">How it works:</div>
<ol className="text-sm space-y-2 text-muted-foreground list-decimal list-inside">
<li>First calls /entitled to check message allowance</li>
<li>If allowed, calls /events to record the message</li>
<li>Updates remaining message count</li>
</ol>
</div>
</div>
<div className="p-6 pt-0 flex gap-2">
<button
className="w-full bg-purple-600 hover:bg-purple-700 transition-colors"
onClick={async () => {
await sendMessageClicked("message-credits");
await fetchCustomer();
}}
>
Use Standard Message
</button>
<button
className="w-full bg-purple-600 hover:bg-purple-700 transition-colors"
onClick={async () => {
await sendMessageClicked("premium-credits");
await fetchCustomer();
}}
>
Use Claude Message
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,125 @@
"use client";
import { attachProduct } from "@/app/autumn-functions";
import { CreditCard } from "lucide-react";
import { toast } from "sonner";
export default function CustomerDetailsExample({
customerData,
}: {
customerData: any;
}) {
const { customer, entitlements, products } = customerData;
const getEntitlement = (featureId: string) => {
return entitlements.find(
(entitlement: any) => entitlement.feature_id === featureId
);
};
const upgradeClicked = async () => {
try {
const res = await attachProduct({
customerId: customer.id,
productId: "pro",
});
window.open(res.checkout_url, "_blank");
} catch (error: any) {
toast.error(`${error}`);
}
};
const buyExtraCreditsClicked = async () => {
try {
const res = await attachProduct({
customerId: customer.id,
productId: "extra-credits",
});
window.open(res.checkout_url, "_blank");
} catch (error: any) {
toast.error(`${error}`);
}
};
const messageCredits = getEntitlement("message-credits");
const premiumCredits = getEntitlement("premium-credits");
const hasPro = products.length > 0 && products[0].id === "pro";
return (
<div className="border rounded-lg bg-white overflow-hidden flex flex-col">
<div className="border-b p-6">
<div className="flex items-start justify-between">
<div className="space-y-1">
<h2 className="text-lg font-semibold">Customer Details</h2>
<p className="text-sm text-muted-foreground">
Current subscription and feature access
</p>
</div>
<div className="h-8 w-8 rounded-lg bg-stone-50 flex items-center justify-center">
<CreditCard className="h-4 w-4 text-stone-600" />
</div>
</div>
</div>
<div className="p-6 flex-1">
<div className="space-y-3">
<div className="flex items-center justify-between py-2 border-b">
<span className="text-sm font-medium">Customer ID</span>
<span className="text-sm font-mono bg-stone-50 px-2 py-1 rounded">
{customer.id}
</span>
</div>
<div className="flex items-center justify-between py-2 border-b">
<span className="text-sm font-medium">Standard Messages Remaining</span>
<span className="text-sm font-mono bg-stone-50 px-2 py-1 rounded">
{messageCredits?.balance || 0}
</span>
</div>
<div className="flex items-center justify-between py-2 border-b">
<span className="text-sm font-medium">Premium Messages Remaining</span>
<span className="text-sm font-mono bg-stone-50 px-2 py-1 rounded">
{premiumCredits?.balance || 0}
</span>
</div>
<div className="flex items-center justify-between py-2">
<span className="text-sm font-medium">Current Plan</span>
<span className="text-sm font-medium">
{hasPro ? (
<span className="bg-purple-50 text-purple-700 px-2 py-1 rounded-full">
Pro
</span>
) : (
<span className="bg-stone-50 text-stone-600 px-2 py-1 rounded-full">
Free
</span>
)}
</span>
</div>
</div>
</div>
<div className="flex gap-2 p-6 pt-0">
<div className="w-full pt-0">
{!hasPro && (
<button
className="w-full"
onClick={upgradeClicked}
>
Upgrade to Pro
</button>
)}
</div>
<div className="w-full pt-0">
<button
className="w-full"
onClick={buyExtraCreditsClicked}
>
Buy Extra Premium Credits
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,52 @@
import Link from "next/link";
export default function Intro() {
return (
<div className="space-y-8">
{/* Header Section */}
<div className="space-y-2">
<h1 className="text-3xl font-bold tracking-tight">
Welcome to the Next.js Autumn template
</h1>
<p className="text-muted-foreground">
Get started with Autumn by setting up your account and exploring the
core features.
</p>
</div>
{/* Setup Requirements */}
<div className="p-6 border rounded-lg bg-stone-50 space-y-4">
<h2 className="font-semibold">Before you get started</h2>
<ul className="space-y-3 text-sm">
<li className="flex items-center gap-2">
<div className="h-2 w-2 rounded-full bg-stone-300" />
<span>
Create your Autumn secret key{" "}
<Link
href="https://app.useautumn.com/sandbox/dev"
className="text-stone-700 underline underline-offset-4 hover:text-stone-900"
target="_blank"
>
here
</Link>{" "}
and add it to the .env.local file
</span>
</li>
<li className="flex items-center gap-2">
<div className="h-2 w-2 rounded-full bg-stone-300" />
<span>
Connect your Stripe account{" "}
<Link
href="https://app.useautumn.com/sandbox/integrations/stripe"
className="text-stone-700 underline underline-offset-4 hover:text-stone-900"
target="_blank"
>
here
</Link>
</span>
</li>
</ul>
</div>
</div>
);
}

View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View File

@@ -0,0 +1,25 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner, ToasterProps } from "sonner"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
} as React.CSSProperties
}
{...props}
/>
)
}
export { Toaster }

View File

@@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

6
example/src/lib/utils.ts Normal file
View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

361
example/src/sdk/autumn.ts Normal file
View File

@@ -0,0 +1,361 @@
import { CreateRewardProgram, ErrCode } from "@autumn/shared";
export default class AutumnError extends Error {
message: string;
code: string;
constructor({ message, code }: { message: string; code: string }) {
super(message);
this.message = message;
this.code = code;
}
toString(): string {
return `${this.message} (code: ${this.code})`;
}
}
export class Autumn {
private apiKey: string;
public headers: Record<string, string>;
public baseUrl: string;
constructor(apiKey?: string, baseUrl?: string) {
this.apiKey = apiKey || process.env.AUTUMN_SECRET_KEY || "";
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
};
this.baseUrl = "https://api.useautumn.com/v1";
// this.baseUrl = baseUrl || "http://localhost:8080/v1";
}
async get(path: string) {
const response = await fetch(`${this.baseUrl}${path}`, {
headers: this.headers,
});
return response.json();
}
async post(path: string, body: any) {
const response = await fetch(`${this.baseUrl}${path}`, {
method: "POST",
headers: this.headers,
body: JSON.stringify(body),
});
if (response.status != 200) {
let error: any;
try {
error = await response.json();
} catch (error) {
throw new AutumnError({
message: "Failed to parse Autumn API error response",
code: ErrCode.InternalError,
});
}
throw new AutumnError({
message: error.message,
code: error.code,
});
}
return response.json();
}
async delete(
path: string,
{
deleteInStripe = false,
}: {
deleteInStripe?: boolean;
} = {}
) {
const response = await fetch(
`${this.baseUrl}${path}?${deleteInStripe ? "delete_in_stripe=true" : ""}`,
{
method: "DELETE",
headers: this.headers,
}
);
if (response.status != 200) {
let error: any;
try {
error = await response.json();
} catch (error) {
throw new AutumnError({
message: "Failed to parse Autumn API error response",
code: ErrCode.InternalError,
});
}
throw new AutumnError({
message: error.message,
code: error.code,
});
}
return response.json();
}
async createCustomer({
id,
email,
name,
fingerprint,
}: {
id: string;
email: string;
name: string;
fingerprint?: string;
}) {
const data = await this.post("/customers", {
id,
email,
name,
fingerprint,
});
return data;
}
async attach({
customerId,
productId,
options,
}: {
customerId: string;
productId: string;
options?: any;
}) {
const data = await this.post(`/attach`, {
customer_id: customerId,
product_id: productId,
options,
});
return data;
}
async sendEvent({
customerId,
eventName,
properties,
customer_data,
idempotency_key,
}: {
customerId: string;
eventName: string;
properties?: any;
customer_data?: any;
idempotency_key?: string;
}) {
const data = await this.post(`/events`, {
customer_id: customerId,
event_name: eventName,
properties,
customer_data,
idempotency_key,
});
return data;
}
async entitled({
customerId,
featureId,
quantity,
customer_data,
}: {
customerId: string;
featureId: string;
quantity?: number;
customer_data?: any;
}) {
const data = await this.post(`/entitled`, {
customer_id: customerId,
feature_id: featureId,
quantity,
customer_data,
});
return data;
}
customers = {
get: async (customerId: string) => {
const data = await this.get(`/customers/${customerId}`);
return data;
},
create: async (customer: { id: string; email: string; name: string }) => {
const data = await this.post(`/customers`, customer);
return data;
},
delete: async (
customerId: string,
{
deleteInStripe = false,
}: {
deleteInStripe?: boolean;
} = {}
) => {
const data = await this.delete(`/customers/${customerId}`, {
deleteInStripe,
});
return data;
},
};
entities = {
create: async (
customerId: string,
entity:
| {
id: string;
name: string;
featureId: string;
}
| {
id: string;
name: string;
featureId: string;
}[]
) => {
let entities = Array.isArray(entity) ? entity : [entity];
const data = await this.post(
`/customers/${customerId}/entities`,
entities.map((e: any) => {
return {
id: e.id,
name: e.name,
feature_id: e.featureId,
};
})
);
return data;
},
list: async (customerId: string) => {
const data = await this.get(`/customers/${customerId}/entities`);
return data;
},
delete: async (customerId: string, entityId: string) => {
const data = await this.delete(
`/customers/${customerId}/entities/${entityId}`
);
return data;
},
};
products = {
update: async (productId: string, product: any) => {
if (product.items && typeof product.items === "object") {
product.items = Object.values(product.items);
}
const data = await this.post(`/products/${productId}`, product);
return data;
},
get: async (
productId: string,
{ v1Schema = false }: { v1Schema?: boolean } = {}
) => {
const data = await this.get(
`/products/${productId}?${v1Schema ? "schemaVersion=1" : ""}`
);
return data;
},
create: async (product: any) => {
const data = await this.post(`/products`, product);
return data;
},
delete: async (productId: string) => {
const data = await this.delete(`/products/${productId}`);
return data;
},
};
rewards = {
create: async (reward: any) => {
const data = await this.post(`/rewards`, reward);
return data;
},
};
rewardPrograms = {
create: async (rewardProgram: CreateRewardProgram) => {
const data = await this.post(`/reward_programs`, rewardProgram);
return data;
},
};
referrals = {
createCode: async ({
customerId,
referralId,
}: {
customerId: string;
referralId: string;
}) => {
const data = await this.post(`/referrals/code`, {
customer_id: customerId,
program_id: referralId,
});
return data;
},
redeem: async ({
customerId,
code,
}: {
customerId: string;
code: string;
}) => {
const data = await this.post(`/referrals/redeem`, {
customer_id: customerId,
code,
});
return data;
},
};
redemptions = {
get: async ({ redemptionId }: { redemptionId: string }) => {
const data = await this.get(`/redemptions/${redemptionId}`);
return data;
},
};
events = {
send: async ({
customerId,
featureId,
value,
properties,
}: {
customerId: string;
featureId: string;
value: number;
properties?: any;
}) => {
const data = await this.post(`/events`, {
customer_id: customerId,
feature_id: featureId,
value,
properties,
});
return data;
},
};
initStripe = async () => {
await this.post(`/products/all/init_stripe`, {});
};
}

28
example/tsconfig.json Normal file
View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"noImplicitAny": false,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}