feat: payment service with IPG

This commit is contained in:
matin jamshidi
2025-01-03 11:29:33 +03:30
parent f2fb7188ad
commit 6c80c1138f
23 changed files with 495 additions and 96 deletions
@@ -0,0 +1,63 @@
import { Injectable, Logger } from "@nestjs/common";
import { PaymentDataAccess } from "../../dataAccess/payment.dataAccess";
import { startSession } from "mongoose";
import { PaymentGateway } from "../IPG/PaymentGateway";
import { UserDataAccess } from "../../dataAccess/user.dataAccess";
@Injectable()
export class PaymentService {
private readonly logger = new Logger(PaymentService.name);
constructor(
private readonly paymentDataAccess: PaymentDataAccess,
private readonly paymentGateway: PaymentGateway,
private readonly userDataAccess: UserDataAccess,
) { }
async createPayment(userId: string, amount: number, courseId: string) {
const session = await startSession();
session.startTransaction();
try {
const paymentData = await this.paymentGateway.requestPayment({ amount, userId, callbackPath: "cart" });
console.log(paymentData)
if (!paymentData) {
throw new Error("Error in payment process");
}
const payment = await this.paymentDataAccess.createPayment(
userId,
amount,
courseId,
paymentData.authority,
session
);
console.log({ payment })
await session.commitTransaction();
await session.endSession();
return { payment: payment, paymentData }
} catch (error) {
await session.abortTransaction();
await session.endSession();
this.logger.warn(error);
}
}
async verifyPayment(authority: string, status: string) {
console.log({ authorityInService: authority })
const paymentData = await this.paymentDataAccess.getPaymentByAuthority(authority);
console.log({ paymentData })
if (!paymentData) {
throw new Error("payment not found");
}
const verifyData = await this.paymentGateway.verifyPayment({ authority, amount: paymentData.amount });
if (verifyData.code === 100 || verifyData.code === 101) {
const registerCourse = await this.userDataAccess.registerCourse(paymentData.userId, paymentData.courseId);
console.log(registerCourse)
if (!registerCourse.success) {
throw new Error("error in register course");
}
return { success: true, payment: paymentData, verifyData }
}
}
}