To create a product with multiple prices using Stripe API and NestJS, you can follow these steps:
- Install Stripe Node.js library.
Install the Stripe Node.js library to interact with the Stripe API in your NestJS app by running the following command:
npm install --save stripe
- Create a Stripe module.
Create a new file stripe.module.ts and import the Stripe library.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import Stripe from 'stripe';
@Module({
imports: [ConfigModule], // Configuration module for API keys
providers: [
{
provide: 'STRIPE',
useFactory: async () => {
const stripeApiKey = 'your_stripe_secret_key';
return new Stripe(stripeApiKey, {
apiVersion: '2020-08-27',
});
},
},
],
exports: ['STRIPE'],
})
export class StripeModule {}
Replace 'your_stripe_secret_key' with your Stripe secret key.
Now, you can use the Stripe instance in your application services.
- Create a PriceService.
Create a new file price.service.ts.
import { Injectable } from '@nestjs/common';
import { Inject } from '@nestjs/common/decorators/core/component.decorators';
import Stripe from 'stripe';
@Injectable()
export class PriceService {
constructor(@Inject('STRIPE') private readonly stripe: Stripe) {}
async createProductWithPrices(
name: string,
prices: { amount: number; currency: string; nickname: string }[],
): Promise<Stripe.Product & { prices: Stripe.Price[] }> {
const product = await this.stripe.products.create({ name });
const pricePromises = prices.map((price) =>
this.stripe.prices.create({
unit_amount: price.amount,
currency: price.currency,
product: product.id,
nickname: price.nickname,
}),
);
const stripePrices = await Promise.all(pricePromises);
return {
...product,
prices: stripePrices,
};
}
}
In the PriceService, we have a createProductWithPrices method that creates a product and multiple prices associated with it.
- Update AppModule.
In app.module.ts, add the StripeModule and PriceService imports.
import { Module } from '@nestjs/common';
import { StripeModule } from './stripe.module';
import { PriceService } from './price.service';
@Module({
imports: [StripeModule],
providers: [PriceService],
})
export class AppModule {}
Now, you can use the PriceService to create a product with multiple prices. For example, in your controller:
import { Controller, Post } from '@nestjs/common';
import { PriceService } from './price.service';
@Controller()
export class AppController {
constructor(private readonly priceService: PriceService) {}
@Post('/create-product-with-prices')
async createProductWithPrices() {
return this.priceService.createProductWithPrices('My Product', [
{ amount: 1000, currency: 'usd', nickname: 'Basic plan' },
{ amount: 2000, currency: 'usd', nickname: 'Pro plan' },
]);
}
}
This will create a new product with two prices associated with it when you make a POST request to /create-product-with-prices. Make sure to adjust the code according to your application architecture, as necessary.