stripe
This commit is contained in:
1 parent
01c0e9ef4d
commit
1b162578c2
22 files changed
+450
-72
No files matched your search
@@ -24,5 +24,6 @@ export { default as JobGenerator } from "@/services/infrastructure/JobGenerator.
|
||||
export { default as ServiceRegistry } from "@/services/system/ServiceRegistry.js";
|
||||
export { default as SettingsService } from "@/services/system/SettingsService.js";
|
||||
export { default as BillingService } from "@/services/system/BillingService.js";
|
||||
export { default as StripeService } from "@/services/system/StripeService.js";
|
||||
|
||||
export * from "@/services/infrastructure/NotificationServices/index.js";
|
||||
@@ -15,6 +15,8 @@ export interface IBillingService {
|
||||
orgId: string,
|
||||
planKey: PlanKey
|
||||
): Promise<string>;
|
||||
cancelSubscription(orgId: string): Promise<string>;
|
||||
confirmPlan(orgId: string, expectedPlanKey: PlanKey): Promise<boolean>;
|
||||
}
|
||||
|
||||
const SERVICE_NAME = "BillingService";
|
||||
@@ -27,10 +29,10 @@ class BillingService implements IBillingService {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.stripeClient = new Stripe(config.STRIPE_SECRET);
|
||||
}
|
||||
async listPlans(): Promise<Entitlements[]> {
|
||||
listPlans = async () => {
|
||||
const order: PlanKey[] = ["free", "pro", "business", "enterprise"];
|
||||
return order.map((key) => Plans[key]);
|
||||
}
|
||||
};
|
||||
|
||||
subscribePlan = async (email: string, orgId: string, planKey: PlanKey) => {
|
||||
if (!planKey) {
|
||||
@@ -41,7 +43,6 @@ class BillingService implements IBillingService {
|
||||
throw new ApiError("Invalid planKey", 400);
|
||||
}
|
||||
|
||||
// Ensure billing customer exists for this org
|
||||
const org = await Org.findById(orgId);
|
||||
if (!org) throw new ApiError("Organization not found", 404);
|
||||
if (!org.billingCustomerId) {
|
||||
@@ -63,28 +64,110 @@ class BillingService implements IBillingService {
|
||||
throw new ApiError("Price not found for the selected plan", 404);
|
||||
}
|
||||
|
||||
let redirectUrl: string;
|
||||
const successUrl = `${config.ORIGIN}/billing/success?plan=${planKey}`;
|
||||
const cancelUrl = `${config.ORIGIN}/billing/`;
|
||||
const session = await this.stripeClient.checkout.sessions.create({
|
||||
billing_address_collection: "auto",
|
||||
line_items: [
|
||||
{
|
||||
price,
|
||||
quantity: 1,
|
||||
|
||||
const subscriptionId = org.subscriptionId;
|
||||
|
||||
// Updating an existing subscription
|
||||
if (subscriptionId) {
|
||||
const session = await this.stripeClient.billingPortal.sessions.create({
|
||||
customer: String(org.billingCustomerId),
|
||||
return_url: successUrl,
|
||||
flow_data: {
|
||||
type: "subscription_update",
|
||||
subscription_update: {
|
||||
subscription: subscriptionId,
|
||||
},
|
||||
},
|
||||
],
|
||||
mode: "subscription",
|
||||
success_url: successUrl,
|
||||
cancel_url: cancelUrl,
|
||||
customer: String(org.billingCustomerId),
|
||||
client_reference_id: String(org._id),
|
||||
subscription_data: { metadata: { orgId: String(org._id) } },
|
||||
metadata: { orgId: String(org._id) },
|
||||
});
|
||||
if (session.url === null) {
|
||||
throw new ApiError("Failed to create checkout session", 500);
|
||||
});
|
||||
redirectUrl = session.url;
|
||||
}
|
||||
return session.url;
|
||||
|
||||
// Creating a new subscription
|
||||
else {
|
||||
const session = await this.stripeClient.checkout.sessions.create({
|
||||
billing_address_collection: "auto",
|
||||
line_items: [
|
||||
{
|
||||
price,
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
mode: "subscription",
|
||||
success_url: successUrl,
|
||||
cancel_url: cancelUrl,
|
||||
customer: String(org.billingCustomerId),
|
||||
client_reference_id: String(org._id),
|
||||
subscription_data: { metadata: { orgId: String(org._id) } },
|
||||
metadata: { orgId: String(org._id) },
|
||||
});
|
||||
if (!session.url) {
|
||||
throw new ApiError("Failed to create checkout session", 500);
|
||||
}
|
||||
redirectUrl = session.url;
|
||||
}
|
||||
|
||||
return redirectUrl;
|
||||
};
|
||||
|
||||
cancelSubscription = async (orgId: string): Promise<string> => {
|
||||
const successUrl = `${config.ORIGIN}/billing/success?plan=free`;
|
||||
|
||||
const org = await Org.findById(orgId);
|
||||
if (!org) throw new ApiError("Organization not found", 404);
|
||||
|
||||
const subscriptionId = org.subscriptionId;
|
||||
if (!subscriptionId) {
|
||||
throw new ApiError("No active subscription found", 400);
|
||||
}
|
||||
|
||||
const session = await this.stripeClient.billingPortal.sessions.create({
|
||||
customer: String(org.billingCustomerId),
|
||||
return_url: successUrl,
|
||||
flow_data: {
|
||||
type: "subscription_cancel",
|
||||
subscription_cancel: {
|
||||
subscription: subscriptionId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const redirect = session.url;
|
||||
if (!redirect) {
|
||||
throw new ApiError("Failed to create billing portal session", 500);
|
||||
}
|
||||
|
||||
return redirect;
|
||||
};
|
||||
|
||||
confirmPlan = async (orgId: string, expectedPlanKey: PlanKey) => {
|
||||
const org = await Org.findOne({ _id: orgId });
|
||||
if (!org) throw new ApiError("Organization not found", 404);
|
||||
|
||||
if (!org.subscriptionId) {
|
||||
return expectedPlanKey === "free";
|
||||
}
|
||||
|
||||
const sub = await this.stripeClient.subscriptions.retrieve(
|
||||
org.subscriptionId
|
||||
);
|
||||
const activePlan = sub.items.data[0]?.price.lookup_key;
|
||||
|
||||
if (activePlan === org.planKey) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (activePlan === expectedPlanKey) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (activePlan !== expectedPlanKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import Stripe from "stripe";
|
||||
import { config } from "@/config/index.js";
|
||||
import {
|
||||
Org,
|
||||
Monitor,
|
||||
StatusPage,
|
||||
NotificationChannel,
|
||||
} from "@/db/models/index.js";
|
||||
import { PlanKey, Plans } from "@/types/entitlements.js";
|
||||
|
||||
const SERVICE_NAME = "StripeService";
|
||||
|
||||
interface IStripeService {
|
||||
webhook: (
|
||||
event: string | Buffer,
|
||||
signature: string
|
||||
) => Promise<Stripe.Subscription | null>;
|
||||
}
|
||||
|
||||
class StripeService implements IStripeService {
|
||||
public SERVICE_NAME: string;
|
||||
private stripe: Stripe;
|
||||
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.stripe = new Stripe(config.STRIPE_SECRET);
|
||||
}
|
||||
|
||||
private handleSubscription = async (subscription: Stripe.Subscription) => {
|
||||
const orgId = subscription.metadata.orgId;
|
||||
const subscriptionId = subscription.id;
|
||||
const planKey =
|
||||
(subscription.items.data[0]?.price.lookup_key as PlanKey) || "free";
|
||||
const priceId = subscription.items.data[0]?.price.id || "unknown";
|
||||
const status = subscription.status;
|
||||
const currentPeriodStart =
|
||||
subscription.items.data[0]?.current_period_start || 0;
|
||||
const currentPeriodEnd =
|
||||
subscription.items.data[0]?.current_period_end || 0;
|
||||
|
||||
await Org.findOneAndUpdate(
|
||||
{ _id: orgId },
|
||||
{
|
||||
$set: {
|
||||
planKey,
|
||||
subscriptionId,
|
||||
subscriptionStatus: status,
|
||||
priceId,
|
||||
currentPeriodStart,
|
||||
currentPeriodEnd,
|
||||
entitlements: Plans[planKey],
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
);
|
||||
|
||||
await this.pruneResourcesForOrg(String(orgId), Plans[planKey]);
|
||||
};
|
||||
|
||||
private handleCancel = async (subscription: Stripe.Subscription) => {
|
||||
const orgId = subscription.metadata.orgId;
|
||||
await Org.findOneAndUpdate(
|
||||
{ _id: orgId },
|
||||
{
|
||||
$set: {
|
||||
planKey: "free",
|
||||
entitlements: Plans["free"],
|
||||
},
|
||||
$unset: {
|
||||
subscriptionId: "",
|
||||
subscriptionStatus: "",
|
||||
priceId: "",
|
||||
currentPeriodStart: "",
|
||||
currentPeriodEnd: "",
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
);
|
||||
await this.pruneResourcesForOrg(String(orgId), Plans["free"]);
|
||||
};
|
||||
|
||||
private pruneResourcesForOrg = async (
|
||||
orgId: string,
|
||||
entitlements: {
|
||||
monitorsMax: number;
|
||||
notificationChannelsMax: number;
|
||||
statusPagesMax: number;
|
||||
}
|
||||
) => {
|
||||
const prune = async (
|
||||
model: any,
|
||||
cap: number,
|
||||
filter: Record<string, unknown>
|
||||
) => {
|
||||
if (!Number.isFinite(cap) || cap === Number.MAX_SAFE_INTEGER) return;
|
||||
const count = await model.countDocuments(filter);
|
||||
if (count <= cap) return;
|
||||
const excess = count - cap;
|
||||
const docs = await model
|
||||
.find(filter)
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(excess)
|
||||
.select("_id");
|
||||
const ids = docs.map((d: any) => d._id);
|
||||
if (ids.length) {
|
||||
await model.deleteMany({ _id: { $in: ids } });
|
||||
}
|
||||
};
|
||||
|
||||
const baseFilter = { orgId } as const;
|
||||
await prune(Monitor, entitlements.monitorsMax, baseFilter);
|
||||
await prune(
|
||||
NotificationChannel,
|
||||
entitlements.notificationChannelsMax,
|
||||
baseFilter
|
||||
);
|
||||
await prune(StatusPage, entitlements.statusPagesMax, baseFilter);
|
||||
};
|
||||
|
||||
webhook = async (event: string | Buffer, signature: string) => {
|
||||
const whSecret = config.STRIPE_WEBHOOK_SECRET;
|
||||
if (!whSecret || whSecret === "not_set") {
|
||||
throw new Error("Stripe webhook secret is not set");
|
||||
}
|
||||
|
||||
const stripeEvent = this.stripe.webhooks.constructEvent(
|
||||
event,
|
||||
signature,
|
||||
whSecret
|
||||
);
|
||||
|
||||
let subscription: Stripe.Subscription | null;
|
||||
let status: Stripe.Subscription.Status;
|
||||
switch (stripeEvent.type) {
|
||||
case "customer.subscription.deleted":
|
||||
subscription = stripeEvent.data.object;
|
||||
status = subscription.status;
|
||||
this.handleCancel(subscription);
|
||||
break;
|
||||
case "customer.subscription.created":
|
||||
subscription = stripeEvent.data.object;
|
||||
status = subscription.status;
|
||||
this.handleSubscription(subscription);
|
||||
break;
|
||||
case "customer.subscription.updated":
|
||||
subscription = stripeEvent.data.object;
|
||||
status = subscription.status;
|
||||
this.handleSubscription(subscription);
|
||||
break;
|
||||
|
||||
case "checkout.session.completed":
|
||||
subscription = null;
|
||||
console.log("Checkout session completed.");
|
||||
break;
|
||||
|
||||
case "invoice.payment_succeeded":
|
||||
subscription = null;
|
||||
console.log("Invoice payment succeeded.");
|
||||
break;
|
||||
|
||||
default:
|
||||
// Unexpected event type
|
||||
subscription = null;
|
||||
console.log(`Unhandled event type ${stripeEvent.type}.`);
|
||||
}
|
||||
return subscription;
|
||||
};
|
||||
}
|
||||
|
||||
export default StripeService;
|
||||
Reference in new issue
Block a user