In this guide, we'll create a simple payment service with NestJS, GraphQL, Prisma, and Stripe. We'll use a basic booking system for an event, where users will request bookings, and the payments will be pending. Once an admin confirms the booking, the user will be charged.
Prerequisites:
- Node.js version 14 or above
- A Stripe account
Step 1: Install and set up NestJS CLI
1.1. Install NestJS CLI globally:
npm install -g @nestjs/cli
1.2. Create a new NestJS project:
nest new payment-service
1.3. Change to the project directory:
cd payment-service
Step 2: Set up GraphQL
2.1. Install required packages:
npm install @nestjs/graphql graphql-tools graphql apollo-server-express
2.2. Import GraphQLModule in app.module.ts:
import { GraphQLModule } from '@nestjs/graphql';
@Module({
imports: [
GraphQLModule.forRoot({
autoSchemaFile: 'schema.gql',
}),
],
})
export class AppModule {}
Step 3: Set up Prisma
3.1. Install Prisma CLI as a development dependency:
npm install --save-dev prisma
npm install --save @prisma/client
3.2. Initialize Prisma:
npx prisma init
3.3. Set up your database connection in prisma/schema.prisma:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
3.4. Add your database models to prisma/schema.prisma. Example:
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
bookings Booking[]
}
model Booking {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId Int
event String
pending Boolean @default(true)
paymentId String?
}
model Payment {
id String @id @default(uuid())
bookingId Int
amount Float
createdAt DateTime @default(now())
}
3.5. Generate and apply the migrations:
npx prisma migrate dev --name init
Step 4: Setup Stripe
4.1. Install Stripe package:
npm install stripe
4.2. Create a "stripe.service.ts" file in the "src" folder with the following content:
import { Injectable } from "@nestjs/common";
import Stripe from "stripe";
@Injectable()
export class StripeService {
private stripe: Stripe;
constructor() {
this.stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: "2020-08-27",
});
}
async createPaymentIntent(amount: number, currency: string): Promise<Stripe.PaymentIntent> {
return this.stripe.paymentIntents.create({
amount,
currency,
});
}
async confirmPaymentIntent(paymentIntentId: string): Promise<Stripe.PaymentIntent> {
return this.stripe.paymentIntents.confirm(paymentIntentId);
}
}
4.3. In the "app.module.ts", import and add StripeService to the providers:
import { StripeService } from './stripe.service';
@Module({
providers: [StripeService],
})
export class AppModule {}
Step 5: Implement resolvers
5.1. Create "booking.resolver.ts" in the "src" folder:
import { Resolver, Mutation, Args, Int } from '@nestjs/graphql';
import { StripeService } from './stripe.service';
import { PrismaService } from './prisma.service';
import { Booking } from '@prisma/client';
@Resolver()
export class BookingResolver {
constructor(
private stripeService: StripeService,
private prisma: PrismaService,
) {}
@Mutation(() => Booking)
async createBooking(
@Args('userId', { type: () => Int }) userId: number,
@Args('event', { type: () => String }) event: string,
): Promise<Booking> {
// Amount and currency should be fetched from your system, based on the event.
const amount = 1000; // Example amount in cents
const currency = 'usd'; // Example currency
const paymentIntent = await this.stripeService.createPaymentIntent(amount, currency);
return this.prisma.booking.create({
data: {
user: { connect: { id: userId } },
event,
paymentId: paymentIntent.id,
},
});
}
@Mutation(() => Booking)
async confirmBooking(@Args('id', { type: () => Int }) id: number): Promise<Booking> {
const booking = await this.prisma.booking.findUnique({ where: { id } });
if (!booking || !booking.pending) {
throw new Error('Invalid booking');
}
await this.stripeService.confirmPaymentIntent(booking.paymentId);
return this.prisma.booking.update({
where: { id },
data: { pending: false },
});
}
}
5.2. In "app.module.ts", import and add BookingResolver and PrismaService to the providers:
import { BookingResolver } from './booking.resolver';
import { PrismaService } from './prisma.service';
@Module({
providers: [BookingResolver, StripeService, PrismaService],
})
export class AppModule {}
Now you have a basic payment service ready to use. To test the application, run npm run start:dev and visit the GraphQL playground at http://localhost:3000/graphql. You can create bookings and confirm them using the NestJS, GraphQL, Prisma, and Stripe setup. Please note that this example lacks proper validation and error handling and should be used for educational purposes only.