npm package: @stackproviders/better-auth-billing
Description: Extensible billing, subscription, and credits plugin for Better Auth
Latest version: 1.0.2

# @stackproviders/better-auth-billing

> Extensible billing, subscription, and credits plugin for **Better Auth** — robust monetization built directly into your authentication layer.

[![npm version](https://img.shields.io/npm/v/@stackproviders/better-auth-billing.svg?style=flat-square)](https://www.npmjs.com/package/@stackproviders/better-auth-billing)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg?style=flat-square)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](https://opensource.org/licenses/MIT)

**Better Auth Billing** bridges the gap between identity and revenue. It extends [Better Auth](https://github.com/better-auth) to provide out-of-the-box endpoints for handling trials, subscriptions, checkout sessions, and credit management, linked directly to your users or organizations.

An incredibly powerful, developer- and AI-friendly tool.

---

## 🚀 Installation

Install via your preferred package manager (Note: `better-auth` is a required peer dependency).

```bash
# npm
npm install @stackproviders/better-auth-billing better-auth

# pnpm (Recommended)
pnpm add @stackproviders/better-auth-billing better-auth

# yarn
yarn add @stackproviders/better-auth-billing better-auth
```

---

## 🛠 Integration & Setup

To use the plugin, simply add it to your Better Auth server configuration and the client configuration. 

### 1. Server Configuration (`auth.ts` or `auth.server.ts`)

```typescript
import { betterAuth } from "better-auth";
import { billingPlugin } from "@stackproviders/better-auth-billing";

export const auth = betterAuth({
  // ... your other plugins and settings
  plugins: [
    billingPlugin({
      targetModel: "organization", // Or "user" depending on your SaaS model
      trialDays: 14, // Set default trial days
      onSubscribe: async (targetId, planId, subscriptionId, event) => {
        console.log(`Subscribed: ${targetId} on ${planId}`);
        // Connect to your payment gateway logic here
      },
      onCancel: async (targetId, subscriptionId) => {
        console.log(`Cancelled: ${subscriptionId} for ${targetId}`);
      }
    }),
  ],
});
```

### 2. Client Configuration (`auth.client.ts`)

For fully typed client-side methods:

```typescript
import { createAuthClient } from "better-auth/client";
import { billingClient } from "@stackproviders/better-auth-billing/client";

export const authClient = createAuthClient({
  // ... your client config
  plugins: [
    billingClient()
  ],
});
```

---

## 💻 Full Usage Examples

Once configured, the plugin exposes `billing` methods globally on your `authClient`.

### Fetching Billing Status

Instantly retrieve the active subscription or trial state for the current user/organization.

```typescript
import { authClient } from "@/lib/auth.client";

async function checkBillingStatus() {
  const { data, error } = await authClient.billing.status();

  if (error) {
    console.error("Failed to parse billing status", error);
    return;
  }

  // AI & Dev Friendly State machine
  switch (data.status) {
    case "active":
      console.log("User is on plan:", data.planName);
      break;
    case "trialing":
      console.log(`Trial ends in ${data.trialDaysLeft} days!`);
      break;
    case "expired":
      console.warn("Trial or subscription has expired.");
      break;
    default:
      console.log("Inactive or no organization selected.");
  }
}
```

### Starting a Trial

Start a risk-free trial.

```typescript
async function startFreeTrial() {
  const { data, error } = await authClient.billing.startTrial();
  if (data?.success) {
    console.log(`Trial activated for ${data.trialDays} days`);
  }
}
```

### Subscribing to a Plan

Assuming you've seeded `billingPlan` records in your database, pass the `planId` to subscribe.

```typescript
async function upgradePlan(planId: string) {
  const { data, error } = await authClient.billing.subscribe({
    planId: planId
  });

  if (data?.success) {
    console.log("Upgraded to new subscription!", data.subscription);
  }
}
```

### Credit Management (Top-ups and Deductions)

Add and deduct credits with ease:

```typescript
// Add Credits (e.g. after a stripe transaction is handled)
await authClient.billing.credits.add({
  amount: 1500,
  description: "One-time AI Credits Top-up",
});

// Deduct Credits (e.g. when a user generates an AI image)
const deductResult = await authClient.billing.credits.deduct({
  amount: 50,
  description: "Image Generation",
});

if (deductResult.error) {
  console.log("Not enough credits!");
} else {
  console.log("Remaining Balance:", deductResult.data.balance);
}
```

---

## 🏗 Schema Extensions

By adding `billingPlugin`, it will automatically inject necessary tables/fields directly into Better Auth's schema context. You'll need to run your sync tools (e.g., `npx @better-auth/cli generate` or Prisma integrations) to commit these to your database. 

The models injected include:
- `billingPlan`
- `subscription`
- `checkoutSession`
- `creditBalance`
- `creditTransaction`
- `usageRecord`

---

## 🤖 AI & Developer Friendly 

This SDK aims to serve modern development environments by remaining purely type-safe across server boundaries. 

When configuring your AI-agents or Copilot, remember that all billing interactions run via REST mappings hooked directly into the `$InferServerPlugin` properties of the `billingClient`. You never need manual AST inference to figure out route targets.

### Endpoints Hooked Automatically

| Endpoint | Method | Action |
| --- | --- | --- |
| `/billing/status` | GET | Check current subscription/trial status |
| `/billing/plans` | GET | Retrieve available billing plans |
| `/billing/start-trial` | POST | Trigger trial for an organization/user |
| `/billing/create-checkout`| POST | Spawn a checkout session URL |
| `/billing/subscribe` | POST | Move to `ACTIVE` subscription |
| `/billing/credits/add` | POST | Allocate credit points |
| `/billing/credits/deduct` | POST | Use credit points |

---

## 📚 Links & References

- [npm Package](https://www.npmjs.com/package/@stackproviders/better-auth-billing)
- [Better Auth Docs](https://better-auth.com)
- [GitHub Repository](https://github.com/stackproviders/payment-platform)

## License

[MIT](LICENSE) © StackProviders