fix(stripe): allow customizing subscription schema (#2105)

This was documented in docs at https://www.better-auth.com/docs/plugins/stripe#customizing-the-schema but wasn't implemented.
This is now fixed.
This commit is contained in:
Maxwell
2025-04-04 04:23:43 +10:00
committed by GitHub
parent 8d35723221
commit 10893badbc
2 changed files with 75 additions and 57 deletions

View File

@@ -1,62 +1,75 @@
import type { AuthPluginSchema } from "better-auth";
import type { StripeOptions } from "./types";
import { mergeSchema } from "better-auth/db";
export const subscriptions = {
subscription: {
fields: {
plan: {
type: "string",
required: true,
},
referenceId: {
type: "string",
required: true,
},
stripeCustomerId: {
type: "string",
required: false,
},
stripeSubscriptionId: {
type: "string",
required: false,
},
status: {
type: "string",
defaultValue: "incomplete",
},
periodStart: {
type: "date",
required: false,
},
periodEnd: {
type: "date",
required: false,
},
cancelAtPeriodEnd: {
type: "boolean",
required: false,
defaultValue: false,
},
seats: {
type: "number",
required: false,
},
},
},
} satisfies AuthPluginSchema;
export const user = {
user: {
fields: {
stripeCustomerId: {
type: "string",
required: false,
},
},
},
} satisfies AuthPluginSchema;
export const getSchema = (options: StripeOptions) => {
const subscriptions = {
subscription: {
fields: {
plan: {
type: "string",
required: true,
},
referenceId: {
type: "string",
required: true,
},
stripeCustomerId: {
type: "string",
required: false,
},
stripeSubscriptionId: {
type: "string",
required: false,
},
status: {
type: "string",
defaultValue: "incomplete",
},
periodStart: {
type: "date",
required: false,
},
periodEnd: {
type: "date",
required: false,
},
cancelAtPeriodEnd: {
type: "boolean",
required: false,
defaultValue: false,
},
seats: {
type: "number",
required: false,
},
},
if (
options.schema &&
!options.subscription?.enabled &&
"subscription" in options.schema
) {
options.schema.subscription = undefined;
}
return mergeSchema(
{
...(options.subscription?.enabled ? subscriptions : {}),
...user,
},
} satisfies AuthPluginSchema;
const user = {
user: {
fields: {
stripeCustomerId: {
type: "string",
required: false,
},
},
},
} satisfies AuthPluginSchema;
return {
...(options.subscription?.enabled ? subscriptions : {}),
...user,
} as typeof user & typeof subscriptions;
options.schema,
);
};

View File

@@ -1,5 +1,6 @@
import type { Session, User } from "better-auth";
import type { InferOptionSchema, Session, User } from "better-auth";
import type Stripe from "stripe";
import type { subscriptions, user } from "./schema";
export type StripePlan = {
/**
@@ -312,6 +313,10 @@ export interface StripeOptions {
};
};
onEvent?: (event: Stripe.Event) => Promise<void>;
/**
* Schema for the stripe plugin
*/
schema?: InferOptionSchema<typeof subscriptions & typeof user>;
}
export interface Customer {