102 lines
2.8 KiB
TypeScript
102 lines
2.8 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import Stripe from 'stripe';
|
|
|
|
@Injectable()
|
|
export class StripeService {
|
|
private stripe: Stripe;
|
|
|
|
constructor(private configService: ConfigService) {
|
|
this.stripe = new Stripe(this.configService.get<string>('STRIPE_SECRET_KEY')!, {
|
|
apiVersion: '2023-10-16',
|
|
});
|
|
}
|
|
|
|
getClient(): Stripe {
|
|
return this.stripe;
|
|
}
|
|
|
|
async createCustomer(email: string, name?: string): Promise<Stripe.Customer> {
|
|
return this.stripe.customers.create({
|
|
email,
|
|
name: name || undefined,
|
|
});
|
|
}
|
|
|
|
async createCheckoutSession(params: {
|
|
customerId: string;
|
|
priceId: string;
|
|
successUrl: string;
|
|
cancelUrl: string;
|
|
metadata?: Record<string, string>;
|
|
}): Promise<Stripe.Checkout.Session> {
|
|
return this.stripe.checkout.sessions.create({
|
|
customer: params.customerId,
|
|
mode: 'subscription',
|
|
line_items: [
|
|
{
|
|
price: params.priceId,
|
|
quantity: 1,
|
|
},
|
|
],
|
|
success_url: params.successUrl,
|
|
cancel_url: params.cancelUrl,
|
|
metadata: params.metadata,
|
|
});
|
|
}
|
|
|
|
async createOneTimeCheckoutSession(params: {
|
|
customerId: string;
|
|
successUrl: string;
|
|
cancelUrl: string;
|
|
metadata?: Record<string, string>;
|
|
currency: string;
|
|
unitAmount: number;
|
|
productName: string;
|
|
productDescription?: string;
|
|
}): Promise<Stripe.Checkout.Session> {
|
|
return this.stripe.checkout.sessions.create({
|
|
customer: params.customerId,
|
|
mode: 'payment',
|
|
line_items: [
|
|
{
|
|
price_data: {
|
|
currency: params.currency.toLowerCase(),
|
|
unit_amount: params.unitAmount,
|
|
product_data: {
|
|
name: params.productName,
|
|
description: params.productDescription,
|
|
},
|
|
},
|
|
quantity: 1,
|
|
},
|
|
],
|
|
success_url: params.successUrl,
|
|
cancel_url: params.cancelUrl,
|
|
metadata: params.metadata,
|
|
});
|
|
}
|
|
|
|
async createPortalSession(customerId: string, returnUrl: string): Promise<Stripe.BillingPortal.Session> {
|
|
return this.stripe.billingPortal.sessions.create({
|
|
customer: customerId,
|
|
return_url: returnUrl,
|
|
});
|
|
}
|
|
|
|
async getSubscription(subscriptionId: string): Promise<Stripe.Subscription> {
|
|
return this.stripe.subscriptions.retrieve(subscriptionId);
|
|
}
|
|
|
|
async cancelSubscription(subscriptionId: string): Promise<Stripe.Subscription> {
|
|
return this.stripe.subscriptions.update(subscriptionId, {
|
|
cancel_at_period_end: true,
|
|
});
|
|
}
|
|
|
|
constructWebhookEvent(payload: Buffer, signature: string): Stripe.Event {
|
|
const webhookSecret = this.configService.get<string>('STRIPE_WEBHOOK_SECRET')!;
|
|
return this.stripe.webhooks.constructEvent(payload, signature, webhookSecret);
|
|
}
|
|
}
|