秋季计费

秋季计费的更佳认证插件

Autumn 是用于运行 SaaS 定价计划的开源基础设施。它位于您的应用程序和 Stripe 之间,作为客户订阅状态、用量计量和功能权限的数据库。

该插件由 Autumn 团队维护。如有错误、问题或功能请求, 请访问 Autumn GitHub 仓库

在 Autumn 的 Discord 上寻求帮助

我们在线随时为您解答任何问题。

功能

  • One function for all checkout, subscription and payment flows
  • No webhooks required: query Autumn for the data you need
  • Manages your application's free and paid plans
  • Usage tracking for usage billing and periodic limits
  • Custom plans and pricing changes through Autumn's dashboard

Setup Autumn Account

First, create your pricing plans in Autumn's dashboard, where you define what each plan and product gets access to and how it should be billed. In this example, we're handling the free and pro plans for an AI chatbot, which comes with a number of messages per month.

安装 Autumn SDK

npm install autumn-js

如果您使用的是分离的客户端和服务器结构,请确保在项目的两个部分都安装该插件。

AUTUMN_SECRET_KEY 添加到环境变量

您可以在 Autumn 仪表盘的“开发者”中找到它。

.env
AUTUMN_SECRET_KEY=am_sk_xxxxxxxxxx

将 Autumn 插件添加到您的 auth 配置中

auth.ts
import { autumn } from "autumn-js/better-auth";

export const auth = betterAuth({
  // ...
  plugins: [autumn()],
});
auth.ts
import { autumn } from "autumn-js/better-auth";
import { organization } from "better-auth/plugins";

export const auth = betterAuth({
  // ...
  plugins: [organization(), autumn({ customerScope: "organization" })],
});
auth.ts
import { autumn } from "autumn-js/better-auth";
import { organization } from "better-auth/plugins";

export const auth = betterAuth({
  // ...
  plugins: [
    organization(),
    autumn({ customerScope: "user_and_organization" })
  ],
});
auth.ts
import { autumn } from "autumn-js/better-auth";
import { organization } from "better-auth/plugins";

export const auth = betterAuth({
  // ...
  plugins: [
    organization(),
    autumn({
      identify: async ({ session, organization }) => {
        return {
          customerId: "your_customer_id",
          customerData: {
            name: "Customer Name",
            email: "customer@gmail.com",
          },
        };
      },
    }),
  ],
});

Autumn will auto-create your customers when they sign up, and assign them any default plans you created (eg your Free plan). You can choose who becomes a customer: individual users, organizations, both, or something custom like workspaces.

Add <AutumnProvider />

In your layout file, wrap your application with the AutumnProvider component, and pass in the useBetterAuth to true.

app/layout.tsx
import { AutumnProvider } from "autumn-js/react";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        <AutumnProvider useBetterAuth={true}>
          {children}
        </AutumnProvider>
      </body>
    </html>
  );
}

使用方法

处理支付

当客户想购买专业版时,调用 attach 函数重定向客户到 Stripe 结账页面。

如果客户已有支付方式,AttachDialog 会打开,方便客户确认订阅或购买,并处理支付。

Make sure you've pasted in your Stripe test secret key in the Autumn dashboard.

import { useCustomer, AttachDialog } from "autumn-js/react";

export default function PurchaseButton() {
  const { attach } = useCustomer();

  return (
    <button
      onClick={async () => {
        await attach({
          productId: "pro",
          dialog: AttachDialog,
        });
      }}
    >
      升级到专业版
    </button>
  );
}

AttachDialog 组件可以直接从 autumn-js/react 库中使用(如上例所示),也可以下载作为 shadcn/ui 组件 进行自定义。

集成定价逻辑

通过以下函数集成您的客户端和服务器端定价层逻辑:

  • check to see if the customer is allowed to send a message.
  • track a usage event in Autumn (typically done server-side)
  • customer to display any relevant billing data in your UI (subscriptions, feature balances)

服务器端,您可以通过 auth 对象访问 Autumn 的函数。

import { useCustomer } from "autumn-js/react";

export default function SendChatMessage() {
  const { customer, allowed, refetch } = useCustomer();

  return (
    <>
      <button
        onClick={async () => {
          if (allowed({ featureId: "messages" })) {
            //... send chatbot message server-side, then
            await refetch(); // refetch customer usage data
            alert(
              "Remaining messages: " + customer?.features.messages?.balance
            );
          } else {
            alert("You're out of messages");
          }
        }}
      >
        Send Message
      </button>
    </>
  );
}
import { auth } from "@/lib/auth";

// check on the backend if the customer can send a message
const { allowed } = await auth.api.check({
  headers: await headers(), // pass the request headers
  body: {
    featureId: "messages",
  },
});

// server-side function to send the message

// then track the usage
await auth.api.track({
  headers: await headers(),
  body: {
    featureId: "messages",
    value: 2,
  },
});

其他功能

openBillingPortal()

打开计费门户,客户可更新支付方式或取消计划。

import { useCustomer } from "autumn-js/react";

export default function BillingSettings() {
  const { openBillingPortal } = useCustomer();

  return (
    <button
      onClick={async () => {
        await openBillingPortal({
          returnUrl: "/settings/billing",
        });
      }}
    >
      管理计费
    </button>
  );
}

cancel()

取消产品或订阅。

import { useCustomer } from "autumn-js/react";

export default function CancelSubscription() {
  const { cancel } = useCustomer();

  return (
    <button
      onClick={async () => {
        await cancel({ productId: "pro" });
      }}
    >
      取消订阅
    </button>
  );
}

获取发票历史记录

useCustomer 传入 expand 参数以获取更多信息。您可以展开 invoicestrials_usedpayment_methodrewards

import { useCustomer } from "autumn-js/react";

export default function CustomerProfile() {
  const { customer } = useCustomer({ expand: ["invoices"] });

  return (
    <div>
      <h2>客户档案</h2>
      <p>姓名: {customer?.name}</p>
      <p>邮箱: {customer?.email}</p>
      <p>余额: {customer?.features.chat_messages?.balance}</p>
    </div>
  );
}