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

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`, {});
};
}