feat(payment): implement Zibal IPG payment gateway integration, admin merchant configuration and verification page
Deploy Canina / deploy (push) Successful in 3m28s

This commit is contained in:
parsa aghaei committed 2026-08-16 11:40:24 +03:30
1 parent 03900e726a
commit 8992060cb7
94 files changed
+53456 -29275

No files matched your search

+441
View File
@@ -0,0 +1,441 @@
import {
Injectable,
NotFoundException,
BadRequestException,
Logger,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { ZibalService } from './zibal.service';
import { SmsService } from '../common/services/sms.service';
import { Prisma } from '@prisma/client';
@Injectable()
export class PaymentService {
private readonly logger = new Logger(PaymentService.name);
constructor(
private readonly prisma: PrismaService,
private readonly zibalService: ZibalService,
private readonly smsService: SmsService,
) {}
/**
* 1. Initiate Online Payment for an Order via Zibal
*/
async initiateOrderPayment(
userId: string,
orderId: string,
customCallbackUrl?: string,
) {
const order = await this.prisma.order.findFirst({
where: { id: orderId, userId },
include: { user: true },
});
if (!order) {
throw new NotFoundException('سفارش مورد نظر یافت نشد');
}
if (order.status !== 'processing' && order.status !== 'pending_payment') {
if (['shipped', 'delivered'].includes(order.status)) {
throw new BadRequestException('این سفارش قبلاً تکمیل و ارسال شده است');
}
}
const amountTomans = Number(order.totalAmount);
const amountRials = Math.round(amountTomans * 10);
if (amountRials < 1000) {
throw new BadRequestException('مبلغ سفارش کمتر از حداقل مجاز درگاه بانکی (۱,۰۰۰ ریال) است');
}
const frontendUrl = await this.zibalService.getFrontendUrl();
// Default callback points to frontend verify page (or backend proxy)
const callbackUrl =
customCallbackUrl || `${frontendUrl}/payment/verify?orderId=${order.id}`;
// Create a pending PaymentTransaction in database
const transaction = await this.prisma.paymentTransaction.create({
data: {
userId,
orderId: order.id,
amount: new Prisma.Decimal(amountTomans),
amountRials: BigInt(amountRials),
gateway: 'zibal',
status: 'PENDING',
type: 'ORDER',
description: `پرداخت آنلاین سفارش ${order.trackingNumber || order.id}`,
},
});
try {
const zibalRes = await this.zibalService.requestPayment({
amountRials,
callbackUrl,
orderId: order.id,
mobile: order.user?.mobile || undefined,
description: `پرداخت سفارش ${order.trackingNumber || ''} - پت‌شاپ کانینا`,
});
if (zibalRes.result !== 100) {
const errorMsg = this.zibalService.getResultMessage(zibalRes.result);
await this.prisma.paymentTransaction.update({
where: { id: transaction.id },
data: {
status: 'FAILED',
resultCode: zibalRes.result,
message: errorMsg,
},
});
throw new BadRequestException(`خطا در ایجاد تراکنش زیبال: ${errorMsg}`);
}
const trackId = String(zibalRes.trackId);
// Update transaction with trackId
await this.prisma.paymentTransaction.update({
where: { id: transaction.id },
data: {
trackId,
resultCode: zibalRes.result,
message: zibalRes.message,
},
});
const paymentUrl = this.zibalService.getStartUrl(trackId);
return {
success: true,
trackId,
paymentUrl,
orderId: order.id,
amount: amountTomans,
};
} catch (err: any) {
this.logger.error(`Error requesting payment from Zibal: ${err.message}`, err.stack);
throw new BadRequestException(err.message || 'خطا در اتصال به درگاه پرداخت');
}
}
/**
* 2. Initiate Online Wallet Top-Up via Zibal
*/
async initiateWalletTopup(
userId: string,
amountTomans: number,
customCallbackUrl?: string,
) {
if (amountTomans < 1000) {
throw new BadRequestException('حداقل مبلغ افزایش موجودی ۱,۰۰۰ تومان است');
}
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) {
throw new NotFoundException('کاربر یافت نشد');
}
const amountRials = Math.round(amountTomans * 10);
const frontendUrl = await this.zibalService.getFrontendUrl();
const callbackUrl =
customCallbackUrl || `${frontendUrl}/payment/verify?type=wallet`;
const transaction = await this.prisma.paymentTransaction.create({
data: {
userId,
amount: new Prisma.Decimal(amountTomans),
amountRials: BigInt(amountRials),
gateway: 'zibal',
status: 'PENDING',
type: 'WALLET_TOPUP',
description: `افزایش موجودی کیف پول کاربر ${user.mobile}`,
},
});
try {
const zibalRes = await this.zibalService.requestPayment({
amountRials,
callbackUrl,
mobile: user.mobile || undefined,
description: `شارژ کیف پول - پت شاپ کانینا`,
});
if (zibalRes.result !== 100) {
const errorMsg = this.zibalService.getResultMessage(zibalRes.result);
await this.prisma.paymentTransaction.update({
where: { id: transaction.id },
data: {
status: 'FAILED',
resultCode: zibalRes.result,
message: errorMsg,
},
});
throw new BadRequestException(`خطا در ایجاد تراکنش زیبال: ${errorMsg}`);
}
const trackId = String(zibalRes.trackId);
await this.prisma.paymentTransaction.update({
where: { id: transaction.id },
data: {
trackId,
resultCode: zibalRes.result,
message: zibalRes.message,
},
});
return {
success: true,
trackId,
paymentUrl: this.zibalService.getStartUrl(trackId),
amount: amountTomans,
};
} catch (err: any) {
this.logger.error(`Error requesting wallet topup from Zibal: ${err.message}`);
throw new BadRequestException(err.message || 'خطا در ارتباط با درگاه بانکی');
}
}
/**
* 3. Verify & Process Callback from Zibal
*/
async verifyAndProcess(
trackId: string,
successParam?: string,
statusParam?: string,
orderIdParam?: string,
) {
this.logger.log(
`Processing callback for trackId=${trackId}, success=${successParam}, status=${statusParam}, orderId=${orderIdParam}`,
);
let transaction = await this.prisma.paymentTransaction.findUnique({
where: { trackId },
include: {
order: {
include: { user: true, orderItems: { include: { product: true } } },
},
user: true,
},
});
if (!transaction) {
// If transaction not found by trackId, check if orderId exists
if (orderIdParam) {
transaction = await this.prisma.paymentTransaction.findFirst({
where: { orderId: orderIdParam },
orderBy: { createdAt: 'desc' },
include: {
order: {
include: { user: true, orderItems: { include: { product: true } } },
},
user: true,
},
});
}
}
if (!transaction) {
throw new NotFoundException('تراکنش پرداخت در سیستم یافت نشد');
}
// If transaction is already verified, return successful details immediately
if (transaction.status === 'VERIFIED') {
return {
success: true,
alreadyVerified: true,
status: 'VERIFIED',
trackId: transaction.trackId,
refNumber: transaction.refNumber,
cardNumber: transaction.cardNumber,
amount: Number(transaction.amount),
orderId: transaction.orderId,
message: 'تراکنش قبلاً با موفقیت تایید و پردازش شده است',
};
}
// If user cancelled or Zibal signaled failure at the gate
if (successParam === '0' || statusParam === '3') {
const statusMessage = this.zibalService.getStatusMessage(statusParam || 3);
await this.prisma.paymentTransaction.update({
where: { id: transaction.id },
data: {
status: 'FAILED',
message: statusMessage,
},
});
return {
success: false,
status: 'FAILED',
trackId,
message: statusMessage,
orderId: transaction.orderId,
};
}
// Call Zibal verify endpoint
try {
const verifyRes = await this.zibalService.verifyPayment(trackId);
const isSuccess = verifyRes.result === 100 || verifyRes.result === 201;
if (!isSuccess) {
const errorMsg = this.zibalService.getResultMessage(verifyRes.result);
await this.prisma.paymentTransaction.update({
where: { id: transaction.id },
data: {
status: 'FAILED',
resultCode: verifyRes.result,
message: errorMsg,
cardNumber: verifyRes.cardNumber,
},
});
return {
success: false,
status: 'FAILED',
trackId,
resultCode: verifyRes.result,
message: errorMsg,
orderId: transaction.orderId,
};
}
// SUCCESSFUL PAYMENT!
const refNumber = verifyRes.refNumber ? String(verifyRes.refNumber) : undefined;
const cardNumber = verifyRes.cardNumber || undefined;
const paidDate = verifyRes.paidAt ? new Date(verifyRes.paidAt) : new Date();
await this.prisma.$transaction(async (tx) => {
// 1. Mark transaction as VERIFIED
await tx.paymentTransaction.update({
where: { id: transaction.id },
data: {
status: 'VERIFIED',
resultCode: verifyRes.result,
refNumber,
cardNumber,
paidAt: paidDate,
message: 'پرداخت با موفقیت انجام و تایید شد',
},
});
// 2. If it's an Order payment
if (transaction.type === 'ORDER' && transaction.orderId) {
await tx.order.update({
where: { id: transaction.orderId },
data: {
status: 'processing',
paymentMethod: 'online',
},
});
// If charity donation was made, update user's total charity
if (transaction.order && Number(transaction.order.charityDonation) > 0) {
await tx.user.update({
where: { id: transaction.userId },
data: {
charityDonationTotal: {
increment: Number(transaction.order.charityDonation),
},
},
});
}
}
// 3. If it's a Wallet Top-up
if (transaction.type === 'WALLET_TOPUP') {
await tx.user.update({
where: { id: transaction.userId },
data: {
walletBalance: {
increment: Number(transaction.amount),
},
},
});
await tx.walletTransaction.create({
data: {
userId: transaction.userId,
amount: transaction.amount,
type: 'deposit',
status: 'completed',
transactionReference: refNumber || `ZBL-${trackId}`,
description: `افزایش اعتبار آنلاین از طریق درگاه زیبال (شناسه: ${trackId})`,
},
});
}
});
// Send SMS notification if order payment
if (transaction.type === 'ORDER' && transaction.order?.user?.mobile) {
const mobile = transaction.order.user.mobile;
const trackingNum = transaction.order.trackingNumber || transaction.order.id;
const formattedAmount = Number(transaction.amount).toLocaleString('fa-IR');
this.smsService
.sendOrderConfirmation(mobile, trackingNum, formattedAmount)
.catch((err) => {
this.logger.warn(`Could not send SMS confirmation: ${err}`);
});
}
return {
success: true,
status: 'VERIFIED',
trackId,
refNumber,
cardNumber,
amount: Number(transaction.amount),
orderId: transaction.orderId,
type: transaction.type,
message: 'پرداخت با موفقیت انجام شد',
};
} catch (err: any) {
this.logger.error(`Error during verify: ${err.message}`, err.stack);
return {
success: false,
status: 'ERROR',
trackId,
message: err.message || 'خطا در فرایند تایید تراکنش',
orderId: transaction.orderId,
};
}
}
/**
* 4. Get Payment Transaction Details
*/
async getTransaction(trackId: string) {
const transaction = await this.prisma.paymentTransaction.findUnique({
where: { trackId },
include: {
order: {
include: {
orderItems: {
include: { product: true },
},
},
},
},
});
if (!transaction) {
throw new NotFoundException('تراکنش یافت نشد');
}
return {
id: transaction.id,
trackId: transaction.trackId,
refNumber: transaction.refNumber,
amount: Number(transaction.amount),
status: transaction.status,
message: transaction.message,
gateway: transaction.gateway,
type: transaction.type,
cardNumber: transaction.cardNumber,
paidAt: transaction.paidAt,
createdAt: transaction.createdAt,
order: transaction.order,
};
}
}