60 lines
1.9 KiB
TypeScript
60 lines
1.9 KiB
TypeScript
import { BackendVariables } from "@Common/config/variables/Variables";
|
|
import { Subscription } from "le-coffre-resources/dist/Admin";
|
|
import Stripe from "stripe";
|
|
import { Service } from "typedi";
|
|
|
|
@Service()
|
|
export default class StripeService {
|
|
private client: Stripe;
|
|
constructor(protected variables: BackendVariables) {
|
|
this.client = new Stripe(variables.STRIPE_SECRET_KEY);
|
|
}
|
|
|
|
public getClient(): Stripe {
|
|
return this.client;
|
|
}
|
|
|
|
public async createCheckoutSession(subscription: Subscription) {
|
|
const priceId = subscription.type === "STANDARD" ? this.variables.STRIPE_STANDARD_SUBSCRIPTION_PRICE_ID : this.variables.STRIPE_UNLIMITED_SUBSCRIPTION_PRICE_ID;
|
|
return this.client.checkout.sessions.create({
|
|
mode: "subscription",
|
|
payment_method_types: ["card"],
|
|
billing_address_collection: "auto",
|
|
line_items: [
|
|
{
|
|
price: priceId,
|
|
quantity: subscription.type === "STANDARD" ? subscription.nb_seats : 1,
|
|
},
|
|
],
|
|
success_url: this.variables.APP_HOST + "/subscription/success",
|
|
cancel_url: this.variables.APP_HOST + "/subscription/error",
|
|
metadata: {
|
|
subscription: JSON.stringify(subscription),
|
|
env: this.variables.ENV,
|
|
},
|
|
allow_promotion_codes: true,
|
|
});
|
|
|
|
|
|
|
|
}
|
|
|
|
public async getStripeSubscriptionByUid(subscriptionId: string) {
|
|
return await this.client.subscriptions.retrieve(subscriptionId);
|
|
}
|
|
|
|
public async createClientPortalSession(subscriptionId: string) {
|
|
const subscription = await this.client.subscriptions.retrieve(subscriptionId);
|
|
|
|
return this.client.billingPortal.sessions.create({
|
|
customer: subscription.customer as string,
|
|
return_url: this.variables.APP_HOST + "/subscription/manage",
|
|
});
|
|
}
|
|
|
|
public async getCustomerBySubscription(subscriptionId: string) {
|
|
const subscription = await this.client.subscriptions.retrieve(subscriptionId);
|
|
return this.client.customers.retrieve(subscription.customer as string);
|
|
}
|
|
}
|