project init
This commit is contained in:
69
apps/api/src/payments/stripe.service.ts
Normal file
69
apps/api/src/payments/stripe.service.ts
Normal file
@ -0,0 +1,69 @@
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user